Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Upgrades project_invitation resource to auto-generated SDK #1900

Merged
merged 11 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (

func DataSource() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceMongoDBAtlasProjectInvitationRead,
ReadContext: dataSourceRead,
Schema: map[string]*schema.Schema{
"project_id": {
Type: schema.TypeString,
Expand Down Expand Up @@ -49,43 +49,42 @@ func DataSource() *schema.Resource {
}
}

func dataSourceMongoDBAtlasProjectInvitationRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
// Get client connection.
conn := meta.(*config.MongoDBClient).Atlas
func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
connV2 := meta.(*config.MongoDBClient).AtlasV2
projectID := d.Get("project_id").(string)
username := d.Get("username").(string)
invitationID := d.Get("invitation_id").(string)

projectInvitation, _, err := conn.Projects.Invitation(ctx, projectID, invitationID)
projectInvitation, _, err := connV2.ProjectsApi.GetProjectInvitation(ctx, projectID, invitationID).Execute()
if err != nil {
return diag.FromErr(fmt.Errorf("error getting Project Invitation information: %w", err))
}

if err := d.Set("username", projectInvitation.Username); err != nil {
if err := d.Set("username", projectInvitation.GetUsername()); err != nil {
return diag.FromErr(fmt.Errorf("error getting `username` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("project_id", projectInvitation.GroupID); err != nil {
if err := d.Set("project_id", projectInvitation.GetGroupId()); err != nil {
return diag.FromErr(fmt.Errorf("error getting `username` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("invitation_id", projectInvitation.ID); err != nil {
if err := d.Set("invitation_id", projectInvitation.GetId()); err != nil {
return diag.FromErr(fmt.Errorf("error getting `invitation_id` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("expires_at", projectInvitation.ExpiresAt); err != nil {
if err := d.Set("expires_at", conversion.TimePtrToStringPtr(projectInvitation.ExpiresAt)); err != nil {
return diag.FromErr(fmt.Errorf("error getting `expires_at` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("created_at", projectInvitation.CreatedAt); err != nil {
if err := d.Set("created_at", conversion.TimePtrToStringPtr(projectInvitation.CreatedAt)); err != nil {
return diag.FromErr(fmt.Errorf("error getting `created_at` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("inviter_username", projectInvitation.InviterUsername); err != nil {
if err := d.Set("inviter_username", projectInvitation.GetInviterUsername()); err != nil {
return diag.FromErr(fmt.Errorf("error getting `inviter_username` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("roles", projectInvitation.Roles); err != nil {
if err := d.Set("roles", projectInvitation.GetRoles()); err != nil {
return diag.FromErr(fmt.Errorf("error getting `roles` for Project Invitation (%s): %s", d.Id(), err))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func TestAccProjectDSProjectInvitation_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { acc.PreCheckBasic(t) },
ProtoV6ProviderFactories: acc.TestAccProviderV6Factories,
CheckDestroy: testAccCheckMongoDBAtlasProjectInvitationDestroy,
CheckDestroy: checkDestroy,
Steps: []resource.TestStep{
{
Config: testAccDataSourceMongoDBAtlasProjectInvitationConfig(orgID, projectName, name, initialRole),
Expand Down
132 changes: 63 additions & 69 deletions internal/service/projectinvitation/resource_project_invitation.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ import (
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
matlas "go.mongodb.org/atlas/mongodbatlas"
"go.mongodb.org/atlas-sdk/v20231115005/admin"
)

func Resource() *schema.Resource {
return &schema.Resource{
CreateContext: resourceMongoDBAtlasProjectInvitationCreate,
ReadContext: resourceMongoDBAtlasProjectInvitationRead,
DeleteContext: resourceMongoDBAtlasProjectInvitationDelete,
UpdateContext: resourceMongoDBAtlasProjectInvitationUpdate,
CreateContext: resourceCreate,
ReadContext: resourceRead,
UpdateContext: resourceUpdate,
DeleteContext: resourceDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceMongoDBAtlasProjectInvitationImportState,
StateContext: resourceImport,
},
Schema: map[string]*schema.Schema{
"project_id": {
Expand Down Expand Up @@ -61,51 +61,72 @@ func Resource() *schema.Resource {
}
}

func resourceMongoDBAtlasProjectInvitationRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
// Get client connection.
conn := meta.(*config.MongoDBClient).Atlas
func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
connV2 := meta.(*config.MongoDBClient).AtlasV2
projectID := d.Get("project_id").(string)

roles := createProjectStringListFromSetSchema(d.Get("roles").(*schema.Set))
invitationReq := &admin.GroupInvitationRequest{
Roles: &roles,
Username: conversion.StringPtr(d.Get("username").(string)),
}

invitationRes, _, err := connV2.ProjectsApi.CreateProjectInvitation(ctx, projectID, invitationReq).Execute()
if err != nil {
return diag.FromErr(fmt.Errorf("error creating Project invitation for user %s: %w", d.Get("username").(string), err))
}

d.SetId(conversion.EncodeStateID(map[string]string{
"username": invitationRes.GetUsername(),
"project_id": invitationRes.GetGroupId(),
"invitation_id": invitationRes.GetId(),
}))

return resourceRead(ctx, d, meta)
}

func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
connV2 := meta.(*config.MongoDBClient).AtlasV2
ids := conversion.DecodeStateID(d.Id())
projectID := ids["project_id"]
username := ids["username"]
invitationID := ids["invitation_id"]

projectInvitation, resp, err := conn.Projects.Invitation(ctx, projectID, invitationID)
projectInvitation, resp, err := connV2.ProjectsApi.GetProjectInvitation(ctx, projectID, invitationID).Execute()
if err != nil {
// case 404
// deleted in the backend case
if resp != nil && resp.StatusCode == http.StatusNotFound {
if resp != nil && resp.StatusCode == http.StatusNotFound { // case 404: deleted in the backend case
d.SetId("")
return nil
}

return diag.FromErr(fmt.Errorf("error getting Project Invitation information: %w", err))
}

if err := d.Set("username", projectInvitation.Username); err != nil {
if err := d.Set("username", projectInvitation.GetUsername()); err != nil {
return diag.FromErr(fmt.Errorf("error getting `username` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("project_id", projectInvitation.GroupID); err != nil {
if err := d.Set("project_id", projectInvitation.GetGroupId()); err != nil {
return diag.FromErr(fmt.Errorf("error getting `project_id` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("invitation_id", projectInvitation.ID); err != nil {
if err := d.Set("invitation_id", projectInvitation.GetId()); err != nil {
return diag.FromErr(fmt.Errorf("error getting `invitation_id` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("expires_at", projectInvitation.ExpiresAt); err != nil {
if err := d.Set("expires_at", conversion.TimePtrToStringPtr(projectInvitation.ExpiresAt)); err != nil {
return diag.FromErr(fmt.Errorf("error getting `expires_at` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("created_at", projectInvitation.CreatedAt); err != nil {
if err := d.Set("created_at", conversion.TimePtrToStringPtr(projectInvitation.CreatedAt)); err != nil {
return diag.FromErr(fmt.Errorf("error getting `created_at` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("inviter_username", projectInvitation.InviterUsername); err != nil {
if err := d.Set("inviter_username", projectInvitation.GetInviterUsername()); err != nil {
return diag.FromErr(fmt.Errorf("error getting `inviter_username` for Project Invitation (%s): %w", d.Id(), err))
}

if err := d.Set("roles", projectInvitation.Roles); err != nil {
if err := d.Set("roles", projectInvitation.GetRoles()); err != nil {
return diag.FromErr(fmt.Errorf("error getting `roles` for Project Invitation (%s): %w", d.Id(), err))
}

Expand All @@ -118,94 +139,67 @@ func resourceMongoDBAtlasProjectInvitationRead(ctx context.Context, d *schema.Re
return nil
}

func resourceMongoDBAtlasProjectInvitationCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
// Get client connection.
conn := meta.(*config.MongoDBClient).Atlas
projectID := d.Get("project_id").(string)

invitationReq := &matlas.Invitation{
Roles: createProjectStringListFromSetSchema(d.Get("roles").(*schema.Set)),
Username: d.Get("username").(string),
}

invitationRes, _, err := conn.Projects.InviteUser(ctx, projectID, invitationReq)
if err != nil {
return diag.FromErr(fmt.Errorf("error creating Project invitation for user %s: %w", d.Get("username").(string), err))
}

d.SetId(conversion.EncodeStateID(map[string]string{
"username": invitationRes.Username,
"project_id": invitationRes.GroupID,
"invitation_id": invitationRes.ID,
}))

return resourceMongoDBAtlasProjectInvitationRead(ctx, d, meta)
}

func resourceMongoDBAtlasProjectInvitationDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
conn := meta.(*config.MongoDBClient).Atlas
func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
connV2 := meta.(*config.MongoDBClient).AtlasV2
ids := conversion.DecodeStateID(d.Id())
projectID := ids["project_id"]
username := ids["username"]
invitationID := ids["invitation_id"]

_, err := conn.Projects.DeleteInvitation(ctx, projectID, invitationID)
roles := conversion.ExpandStringListFromSetSchema(d.Get("roles").(*schema.Set))
invitationReq := &admin.GroupInvitationUpdateRequest{
Roles: &roles,
}
_, _, err := connV2.ProjectsApi.UpdateProjectInvitationById(ctx, projectID, invitationID, invitationReq).Execute()
if err != nil {
return diag.FromErr(fmt.Errorf("error deleting Project invitation for user %s: %w", username, err))
return diag.FromErr(fmt.Errorf("error updating Project invitation for user %s: %w", username, err))
}

return nil
return resourceRead(ctx, d, meta)
}

func resourceMongoDBAtlasProjectInvitationUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
conn := meta.(*config.MongoDBClient).Atlas
func resourceDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
connV2 := meta.(*config.MongoDBClient).AtlasV2
ids := conversion.DecodeStateID(d.Id())
projectID := ids["project_id"]
username := ids["username"]
invitationID := ids["invitation_id"]

invitationReq := &matlas.Invitation{
Roles: conversion.ExpandStringListFromSetSchema(d.Get("roles").(*schema.Set)),
}

_, _, err := conn.Projects.UpdateInvitationByID(ctx, projectID, invitationID, invitationReq)
_, _, err := connV2.ProjectsApi.DeleteProjectInvitation(ctx, projectID, invitationID).Execute()
if err != nil {
return diag.FromErr(fmt.Errorf("error updating Project invitation for user %s: %w", username, err))
return diag.FromErr(fmt.Errorf("error deleting Project invitation for user %s: %w", username, err))
}

return resourceMongoDBAtlasProjectInvitationRead(ctx, d, meta)
return nil
}

func resourceMongoDBAtlasProjectInvitationImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) {
conn := meta.(*config.MongoDBClient).Atlas
func resourceImport(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) {
connV2 := meta.(*config.MongoDBClient).AtlasV2
projectID, username, err := splitProjectInvitationImportID(d.Id())
if err != nil {
return nil, err
}

projectInvitations, _, err := conn.Projects.Invitations(ctx, projectID, nil)
projectInvitations, _, err := connV2.ProjectsApi.ListProjectInvitations(ctx, projectID).Execute()
if err != nil {
return nil, fmt.Errorf("couldn't import Project invitations, error: %s", err)
}

for _, projectInvitation := range projectInvitations {
if projectInvitation.Username != username {
if conversion.SafeString(projectInvitation.Username) != username {
continue
}

if err := d.Set("username", projectInvitation.Username); err != nil {
if err := d.Set("username", projectInvitation.GetUsername()); err != nil {
return nil, fmt.Errorf("error getting `username` for Project Invitation (%s): %w", username, err)
}
if err := d.Set("project_id", projectInvitation.GroupID); err != nil {
if err := d.Set("project_id", projectInvitation.GetGroupId()); err != nil {
return nil, fmt.Errorf("error getting `project_id` for Project Invitation (%s): %w", username, err)
}
if err := d.Set("invitation_id", projectInvitation.ID); err != nil {
if err := d.Set("invitation_id", projectInvitation.GetId()); err != nil {
return nil, fmt.Errorf("error getting `invitation_id` for Project Invitation (%s): %w", username, err)
}
d.SetId(conversion.EncodeStateID(map[string]string{
"username": username,
"project_id": projectID,
"invitation_id": projectInvitation.ID,
"invitation_id": projectInvitation.GetId(),
}))
return []*schema.ResourceData{d}, nil
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package projectinvitation_test

import (
"fmt"
"os"
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/plancheck"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig"
)

func TestAccMigrationProjectInvitation_basic(t *testing.T) {
var (
resourceName = "mongodbatlas_project_invitation.test"
orgID = os.Getenv("MONGODB_ATLAS_ORG_ID")
projectName = acctest.RandomWithPrefix("test-acc")
name = fmt.Sprintf("test-acc-%[email protected]", acctest.RandString(10))
roles = []string{"GROUP_DATA_ACCESS_ADMIN", "GROUP_CLUSTER_MANAGER"}
)

resource.Test(t, resource.TestCase{
PreCheck: func() { mig.PreCheckBasic(t) },
CheckDestroy: checkDestroy,
Steps: []resource.TestStep{
{
ExternalProviders: mig.ExternalProviders(),
Config: configBasic(orgID, projectName, name, roles),
Check: resource.ComposeTestCheckFunc(
checkExists(resourceName),
resource.TestCheckResourceAttrSet(resourceName, "project_id"),
resource.TestCheckResourceAttrSet(resourceName, "invitation_id"),
resource.TestCheckResourceAttr(resourceName, "username", name),
resource.TestCheckResourceAttr(resourceName, "roles.#", "2"),
resource.TestCheckTypeSetElemAttr(resourceName, "roles.*", roles[0]),
resource.TestCheckTypeSetElemAttr(resourceName, "roles.*", roles[1]),
),
},
{
ProtoV6ProviderFactories: acc.TestAccProviderV6Factories,
Config: configBasic(orgID, projectName, name, roles),
ConfigPlanChecks: resource.ConfigPlanChecks{
PreApply: []plancheck.PlanCheck{
acc.DebugPlan(),
plancheck.ExpectEmptyPlan(),
},
},
},
},
})
}
Loading
Loading