Skip to content

Commit ba78a8b

Browse files
csanxCristina Sánchez Sánchez
andauthored
chore: Update mongodbatlas_cloud_user_team_assignment resource to use new query param user_id (#3574)
* Updated SDK * Revert "Updated SDK" This reverts commit f8d2d0a. * Added userId as param to filter * Changed to sequential test * Fix * Refactored Read method in resource and datasource * Fixed CheckDestroy * Removed redundant `found`parameter * Fixed checkDestroy --------- Co-authored-by: Cristina Sánchez Sánchez <[email protected]>
1 parent 601bab7 commit ba78a8b

File tree

3 files changed

+59
-154
lines changed

3 files changed

+59
-154
lines changed

internal/service/clouduserteamassignment/data_source.go

Lines changed: 5 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,9 @@ package clouduserteamassignment
22

33
import (
44
"context"
5-
"fmt"
65

76
"github.com/hashicorp/terraform-plugin-framework/datasource"
87
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
9-
"go.mongodb.org/atlas-sdk/v20250312006/admin"
108
)
119

1210
var _ datasource.DataSource = &cloudUserTeamAssignmentDS{}
@@ -46,50 +44,13 @@ func (d *cloudUserTeamAssignmentDS) Read(ctx context.Context, req datasource.Rea
4644
return
4745
}
4846

49-
var userListResp *admin.PaginatedOrgUser
50-
var userResp *admin.OrgUserResponse
51-
var err error
52-
53-
if userID != "" {
54-
userListResp, _, err = connV2.MongoDBCloudUsersApi.ListTeamUsers(ctx, orgID, teamID).Execute()
55-
if err != nil {
56-
resp.Diagnostics.AddError(fmt.Sprintf("error retrieving resource by user_id: %s", userID), err.Error())
57-
return
58-
}
59-
60-
if userListResp == nil || len(userListResp.GetResults()) == 0 {
61-
resp.Diagnostics.AddError("resource not found", "no user found with the specified user_id")
62-
return
63-
}
64-
results := userListResp.GetResults()
65-
for i := range results {
66-
if results[i].GetId() == userID {
67-
userResp = &results[i]
68-
break
69-
}
70-
}
71-
} else if username != "" {
72-
params := &admin.ListTeamUsersApiParams{
73-
OrgId: orgID,
74-
TeamId: teamID,
75-
Username: &username,
76-
}
77-
userListResp, _, err = connV2.MongoDBCloudUsersApi.ListTeamUsersWithParams(ctx, params).Execute()
78-
if err != nil {
79-
resp.Diagnostics.AddError(fmt.Sprintf("error retrieving resource by username: %s", username), err.Error())
80-
return
81-
}
82-
83-
if userListResp == nil || len(userListResp.GetResults()) == 0 {
84-
resp.Diagnostics.AddError("resource not found", "no user found with the specified username")
85-
return
86-
}
87-
88-
userResp = &(userListResp.GetResults())[0]
47+
userResp, err := fetchTeamUser(ctx, connV2, orgID, teamID, &userID, &username)
48+
if err != nil {
49+
resp.Diagnostics.AddError("error retrieving user", err.Error())
50+
return
8951
}
90-
9152
if userResp == nil {
92-
resp.State.RemoveResource(ctx)
53+
resp.Diagnostics.AddError("resource not found", "no user found with the specified identifier")
9354
return
9455
}
9556

internal/service/clouduserteamassignment/resource.go

Lines changed: 42 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package clouduserteamassignment
33
import (
44
"context"
55
"fmt"
6-
"net/http"
76
"regexp"
87

98
"github.com/hashicorp/terraform-plugin-framework/path"
@@ -17,8 +16,7 @@ import (
1716
const (
1817
resourceName = "cloud_user_team_assignment"
1918
warnUnsupportedOperation = "Operation not supported"
20-
errorReadingByUserID = "Error getting team users by user_id"
21-
errorReadingByUsername = "Error getting team users by username"
19+
errorReadingUsers = "Error retrieving team users"
2220
invalidImportID = "Invalid import ID format"
2321
)
2422

@@ -73,72 +71,60 @@ func (r *rs) Create(ctx context.Context, req resource.CreateRequest, resp *resou
7371
resp.Diagnostics.Append(resp.State.Set(ctx, newUserTeamAssignmentModel)...)
7472
}
7573

74+
func fetchTeamUser(ctx context.Context, connV2 *admin.APIClient, orgID, teamID string, userID, username *string) (*admin.OrgUserResponse, error) {
75+
var params admin.ListTeamUsersApiParams
76+
if userID != nil && *userID != "" {
77+
params = admin.ListTeamUsersApiParams{
78+
UserId: userID,
79+
OrgId: orgID,
80+
TeamId: teamID,
81+
}
82+
} else if username != nil && *username != "" {
83+
params = admin.ListTeamUsersApiParams{
84+
Username: username,
85+
OrgId: orgID,
86+
TeamId: teamID,
87+
}
88+
}
89+
90+
userListResp, httpResp, err := connV2.MongoDBCloudUsersApi.ListTeamUsersWithParams(ctx, &params).Execute()
91+
if err != nil {
92+
if validate.StatusNotFound(httpResp) {
93+
return nil, nil
94+
}
95+
return nil, err
96+
}
97+
98+
if userListResp == nil || len(userListResp.GetResults()) == 0 {
99+
return nil, nil
100+
}
101+
userResp := userListResp.GetResults()[0]
102+
return &userResp, nil
103+
}
104+
76105
func (r *rs) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
77106
var state TFUserTeamAssignmentModel
78107
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
79108
if resp.Diagnostics.HasError() {
80109
return
81110
}
111+
82112
connV2 := r.Client.AtlasV2
83113
orgID := state.OrgId.ValueString()
84114
teamID := state.TeamId.ValueString()
85115

86-
var userListResp *admin.PaginatedOrgUser
87-
var httpResp *http.Response
88-
var err error
89-
90-
var userResp *admin.OrgUserResponse
116+
var userID, username *string
91117
if !state.UserId.IsNull() && state.UserId.ValueString() != "" {
92-
userID := state.UserId.ValueString()
93-
userListResp, httpResp, err = connV2.MongoDBCloudUsersApi.ListTeamUsers(ctx, orgID, teamID).Execute()
94-
95-
if err != nil {
96-
if validate.StatusNotFound(httpResp) {
97-
resp.State.RemoveResource(ctx)
98-
return
99-
}
100-
resp.Diagnostics.AddError(errorReadingByUserID, err.Error())
101-
return
102-
}
103-
if userListResp != nil {
104-
if len(userListResp.GetResults()) == 0 {
105-
resp.State.RemoveResource(ctx)
106-
return
107-
}
108-
results := userListResp.GetResults()
109-
for i := range results {
110-
if results[i].GetId() == userID {
111-
userResp = &results[i]
112-
break
113-
}
114-
}
115-
}
116-
} else if !state.Username.IsNull() && state.Username.ValueString() != "" { // required for import
117-
username := state.Username.ValueString()
118-
params := &admin.ListTeamUsersApiParams{
119-
Username: &username,
120-
OrgId: orgID,
121-
TeamId: teamID,
122-
}
123-
userListResp, httpResp, err = connV2.MongoDBCloudUsersApi.ListTeamUsersWithParams(ctx, params).Execute()
124-
125-
if err != nil {
126-
if validate.StatusNotFound(httpResp) {
127-
resp.State.RemoveResource(ctx)
128-
return
129-
}
130-
resp.Diagnostics.AddError(errorReadingByUsername, err.Error())
131-
return
132-
}
133-
if userListResp != nil {
134-
if len(userListResp.GetResults()) == 0 {
135-
resp.State.RemoveResource(ctx)
136-
return
137-
}
138-
userResp = &(userListResp.GetResults())[0]
139-
}
118+
userID = state.UserId.ValueStringPointer()
119+
} else if !state.Username.IsNull() && state.Username.ValueString() != "" {
120+
username = state.Username.ValueStringPointer()
140121
}
141122

123+
userResp, err := fetchTeamUser(ctx, connV2, orgID, teamID, userID, username)
124+
if err != nil {
125+
resp.Diagnostics.AddError(errorReadingUsers, err.Error())
126+
return
127+
}
142128
if userResp == nil {
143129
resp.State.RemoveResource(ctx)
144130
return

internal/service/clouduserteamassignment/resource_test.go

Lines changed: 12 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,20 @@ import (
44
"context"
55
"fmt"
66
"os"
7-
"regexp"
87
"testing"
98

109
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
1110
"github.com/hashicorp/terraform-plugin-testing/terraform"
1211
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
12+
"go.mongodb.org/atlas-sdk/v20250312006/admin"
1313
)
1414

1515
var resourceName = "mongodbatlas_cloud_user_team_assignment.test"
1616
var dataSourceName1 = "data.mongodbatlas_cloud_user_team_assignment.test1"
1717
var dataSourceName2 = "data.mongodbatlas_cloud_user_team_assignment.test2"
1818

1919
func TestAccCloudUserTeamAssignment_basic(t *testing.T) {
20-
resource.ParallelTest(t, *basicTestCase(t))
21-
}
22-
23-
func TestAccCloudUserTeamAssignmentDS_error(t *testing.T) {
24-
resource.ParallelTest(t, *errorTestCase(t))
20+
resource.Test(t, *basicTestCase(t))
2521
}
2622

2723
func basicTestCase(t *testing.T) *resource.TestCase {
@@ -70,24 +66,6 @@ func basicTestCase(t *testing.T) *resource.TestCase {
7066
}
7167
}
7268

73-
func errorTestCase(t *testing.T) *resource.TestCase {
74-
t.Helper()
75-
76-
orgID := os.Getenv("MONGODB_ATLAS_ORG_ID")
77-
teamName := acc.RandomName()
78-
79-
return &resource.TestCase{
80-
PreCheck: func() { acc.PreCheckBasic(t) },
81-
ProtoV6ProviderFactories: acc.TestAccProviderV6Factories,
82-
Steps: []resource.TestStep{
83-
{
84-
Config: configError(orgID, teamName),
85-
ExpectError: regexp.MustCompile("either username or user_id must be provided"),
86-
},
87-
},
88-
}
89-
}
90-
9169
func configBasic(orgID, userID, teamName string) string {
9270
return fmt.Sprintf(`
9371
resource "mongodbatlas_team" "test" {
@@ -114,21 +92,6 @@ func configBasic(orgID, userID, teamName string) string {
11492
orgID, userID, teamName)
11593
}
11694

117-
func configError(orgID, teamName string) string {
118-
return fmt.Sprintf(`
119-
resource "mongodbatlas_team" "test" {
120-
org_id = %[1]q
121-
name = %[2]q
122-
}
123-
124-
125-
data "mongodbatlas_cloud_user_team_assignment" "test" {
126-
org_id = %[1]q
127-
team_id = mongodbatlas_team.test.team_id
128-
}
129-
`, orgID, teamName)
130-
}
131-
13295
func checks(orgID, userID string) resource.TestCheckFunc {
13396
return resource.ComposeAggregateTestCheckFunc(
13497
resource.TestCheckResourceAttr(resourceName, "org_id", orgID),
@@ -156,23 +119,18 @@ func checkDestroy(s *terraform.State) error {
156119
orgID := rs.Primary.Attributes["org_id"]
157120
teamID := rs.Primary.Attributes["team_id"]
158121
userID := rs.Primary.Attributes["user_id"]
159-
username := rs.Primary.Attributes["username"]
160122
conn := acc.ConnV2()
123+
ctx := context.Background()
161124

162-
userListResp, _, err := conn.MongoDBCloudUsersApi.ListTeamUsers(context.Background(), orgID, teamID).Execute()
163-
if err != nil {
164-
continue
165-
}
166-
167-
if userListResp != nil && userListResp.Results != nil {
168-
results := *userListResp.Results
169-
for i := range results {
170-
if userID != "" && results[i].GetId() == userID {
171-
return fmt.Errorf("cloud user team assignment for user (%s) in team (%s) still exists", userID, teamID)
172-
}
173-
if username != "" && results[i].GetUsername() == username {
174-
return fmt.Errorf("cloud user team assignment for user (%s) in team (%s) still exists", username, teamID)
175-
}
125+
if userID != "" {
126+
userIDParams := &admin.ListTeamUsersApiParams{
127+
UserId: &userID,
128+
OrgId: orgID,
129+
TeamId: teamID,
130+
}
131+
userListUserID, _, err := conn.MongoDBCloudUsersApi.ListTeamUsersWithParams(ctx, userIDParams).Execute()
132+
if userListUserID.HasResults() {
133+
return fmt.Errorf("cloud user team assignment for user (%s) in team (%s) still exists %s", userID, teamID, err)
176134
}
177135
}
178136
}

0 commit comments

Comments
 (0)