From dbd287c273f1a65574634017929345fedcc1bb86 Mon Sep 17 00:00:00 2001 From: Amine Chikhaoui Date: Fri, 1 Sep 2023 12:09:09 -0400 Subject: [PATCH] add ability to read an organization membership by org membership id This will be useful in case you need to read all organization memberships and pull out information such as emails of all users so that it can be used to create downstream resources, example: ```terraform data "tfe_organization_members" "users" { organization = var.tfc_org } data "tfe_organization_membership" "test" { for_each = toset([ for index, member in data.tfe_organization_members.users.members : member.organization_membership_id ]) organization = var.tfc_org organization_membership_id = each.value } output "user_emails" { value = [ for index, member in data.tfe_organization_membership.test : member.email ] } ``` Related issue: #871 --- .../provider/data_source_organization_membership.go | 8 ++++++++ internal/provider/organization_members_helpers.go | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/internal/provider/data_source_organization_membership.go b/internal/provider/data_source_organization_membership.go index def811eb3..895c8d7c4 100644 --- a/internal/provider/data_source_organization_membership.go +++ b/internal/provider/data_source_organization_membership.go @@ -67,6 +67,14 @@ func dataSourceTFEOrganizationMembershipRead(d *schema.ResourceData, meta interf d.SetId(orgMember.ID) } else { + orgMember, err := fetchOrganizationMemberById(context.Background(), config.Client, orgMemberID) + if err != nil { + return fmt.Errorf( + "could not find organization membership (%s) for organization %s: %w", orgMemberID, organization, err, + ) + } + + d.Set("email", orgMember.Email) d.SetId(orgMemberID) } diff --git a/internal/provider/organization_members_helpers.go b/internal/provider/organization_members_helpers.go index 0226a10ed..5b37ca32d 100644 --- a/internal/provider/organization_members_helpers.go +++ b/internal/provider/organization_members_helpers.go @@ -103,3 +103,15 @@ func fetchOrganizationMemberByNameOrEmail(ctx context.Context, client *tfe.Clien return nil, tfe.ErrResourceNotFound } + +func fetchOrganizationMemberById(ctx context.Context, client *tfe.Client, orgMemberId string) (*tfe.OrganizationMembership, error) { + orgMember, err := client.OrganizationMemberships.Read(ctx, orgMemberId) + if err != nil { + return nil, fmt.Errorf("failed to read organization membership %s: %w", orgMemberId, err) + } + if orgMember != nil { + return orgMember, nil + } + + return nil, tfe.ErrResourceNotFound +}