From b198e500bef90a0efd44eaf2f7a8167b177d7e37 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Wed, 14 Feb 2024 16:29:59 +0100 Subject: [PATCH 01/52] rename --- .../data_source_advanced_cluster.go | 8 +- .../data_source_advanced_clusters.go | 6 +- .../resource_advanced_cluster.go | 90 ++++----- ...ource_advanced_cluster_schema_migration.go | 8 +- .../resource_advanced_cluster_test.go | 181 +++++++++++------- 5 files changed, 166 insertions(+), 127 deletions(-) diff --git a/internal/service/advancedcluster/data_source_advanced_cluster.go b/internal/service/advancedcluster/data_source_advanced_cluster.go index 5fa44bf005..f5686c2130 100644 --- a/internal/service/advancedcluster/data_source_advanced_cluster.go +++ b/internal/service/advancedcluster/data_source_advanced_cluster.go @@ -116,7 +116,7 @@ func DataSource() *schema.Resource { Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "analytics_specs": advancedClusterRegionConfigsSpecsSchema(), + "analytics_specs": schemaSpecs(), "auto_scaling": { Type: schema.TypeList, Computed: true, @@ -177,7 +177,7 @@ func DataSource() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "electable_specs": advancedClusterRegionConfigsSpecsSchema(), + "electable_specs": schemaSpecs(), "priority": { Type: schema.TypeInt, Computed: true, @@ -186,7 +186,7 @@ func DataSource() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "read_only_specs": advancedClusterRegionConfigsSpecsSchema(), + "read_only_specs": schemaSpecs(), "region_name": { Type: schema.TypeString, Computed: true, @@ -241,7 +241,7 @@ func dataSourceMongoDBAtlasAdvancedClusterRead(ctx context.Context, d *schema.Re return nil } - return diag.FromErr(fmt.Errorf(errorClusterAdvancedRead, clusterName, err)) + return diag.FromErr(fmt.Errorf(errorRead, clusterName, err)) } if err := d.Set("backup_enabled", cluster.BackupEnabled); err != nil { diff --git a/internal/service/advancedcluster/data_source_advanced_clusters.go b/internal/service/advancedcluster/data_source_advanced_clusters.go index 7d27d38095..66dbb294b6 100644 --- a/internal/service/advancedcluster/data_source_advanced_clusters.go +++ b/internal/service/advancedcluster/data_source_advanced_clusters.go @@ -124,7 +124,7 @@ func PluralDataSource() *schema.Resource { Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "analytics_specs": advancedClusterRegionConfigsSpecsSchema(), + "analytics_specs": schemaSpecs(), "auto_scaling": { Type: schema.TypeList, Computed: true, @@ -185,7 +185,7 @@ func PluralDataSource() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "electable_specs": advancedClusterRegionConfigsSpecsSchema(), + "electable_specs": schemaSpecs(), "priority": { Type: schema.TypeInt, Computed: true, @@ -194,7 +194,7 @@ func PluralDataSource() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "read_only_specs": advancedClusterRegionConfigsSpecsSchema(), + "read_only_specs": schemaSpecs(), "region_name": { Type: schema.TypeString, Computed: true, diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 53068e88c9..b2ddc89966 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -25,33 +25,33 @@ import ( "golang.org/x/exp/slices" ) -type acCtxKey string - const ( - errorClusterAdvancedCreate = "error creating MongoDB ClusterAdvanced: %s" - errorClusterAdvancedRead = "error reading MongoDB ClusterAdvanced (%s): %s" - errorClusterAdvancedDelete = "error deleting MongoDB ClusterAdvanced (%s): %s" - errorClusterAdvancedUpdate = "error updating MongoDB ClusterAdvanced (%s): %s" - errorAdvancedClusterAdvancedConfUpdate = "error updating Advanced Configuration Option form MongoDB Cluster (%s): %s" - errorAdvancedClusterAdvancedConfRead = "error reading Advanced Configuration Option form MongoDB Cluster (%s): %s" + errorCreate = "error creating advanced cluster: %s" + errorRead = "error reading advanced cluster (%s): %s" + errorDelete = "error deleting advanced cluster (%s): %s" + errorUpdate = "error updating advanced cluster (%s): %s" + errorConfigUpdate = "error updating advanced cluster configuration options (%s): %s" + errorConfigRead = "error reading advanced cluster configuration options (%s): %s" ) +type acCtxKey string + var upgradeRequestCtxKey acCtxKey = "upgradeRequest" func Resource() *schema.Resource { return &schema.Resource{ - CreateWithoutTimeout: resourceMongoDBAtlasAdvancedClusterCreate, - ReadWithoutTimeout: resourceMongoDBAtlasAdvancedClusterRead, - UpdateWithoutTimeout: resourceMongoDBAtlasAdvancedClusterUpdateOrUpgrade, - DeleteWithoutTimeout: resourceMongoDBAtlasAdvancedClusterDelete, + CreateWithoutTimeout: resourceCreate, + ReadWithoutTimeout: resourceRead, + UpdateWithoutTimeout: resourceUpdateOrUpgrade, + DeleteWithoutTimeout: resourceDelete, Importer: &schema.ResourceImporter{ - StateContext: resourceMongoDBAtlasAdvancedClusterImportState, + StateContext: resourceImport, }, SchemaVersion: 1, StateUpgraders: []schema.StateUpgrader{ { Type: ResourceV0().CoreConfigSchema().ImpliedType(), - Upgrade: resourceMongoDBAtlasAdvancedClusterStateUpgradeV0, + Upgrade: resourceStateUpgradeV0, Version: 0, }, }, @@ -178,7 +178,7 @@ func Resource() *schema.Resource { Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "analytics_specs": advancedClusterRegionConfigsSpecsSchema(), + "analytics_specs": schemaSpecs(), "auto_scaling": { Type: schema.TypeList, MaxItems: 1, @@ -253,7 +253,7 @@ func Resource() *schema.Resource { Type: schema.TypeString, Optional: true, }, - "electable_specs": advancedClusterRegionConfigsSpecsSchema(), + "electable_specs": schemaSpecs(), "priority": { Type: schema.TypeInt, Required: true, @@ -263,7 +263,7 @@ func Resource() *schema.Resource { Required: true, ValidateDiagFunc: StringIsUppercase(), }, - "read_only_specs": advancedClusterRegionConfigsSpecsSchema(), + "read_only_specs": schemaSpecs(), "region_name": { Type: schema.TypeString, Required: true, @@ -323,7 +323,7 @@ func Resource() *schema.Resource { } } -func advancedClusterRegionConfigsSpecsSchema() *schema.Schema { +func schemaSpecs() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, MaxItems: 1, @@ -352,7 +352,7 @@ func advancedClusterRegionConfigsSpecsSchema() *schema.Schema { } } -func resourceMongoDBAtlasAdvancedClusterCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { +func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { if v, ok := d.GetOk("accept_data_risks_and_force_replica_set_reconfig"); ok { if v.(string) != "" { return diag.FromErr(fmt.Errorf("accept_data_risks_and_force_replica_set_reconfig can not be set in creation, only in update")) @@ -375,7 +375,7 @@ func resourceMongoDBAtlasAdvancedClusterCreate(ctx context.Context, d *schema.Re if _, ok := d.GetOk("bi_connector_config"); ok { biConnector, err := ExpandBiConnectorConfig(d) if err != nil { - return diag.FromErr(fmt.Errorf(errorClusterAdvancedCreate, err)) + return diag.FromErr(fmt.Errorf(errorCreate, err)) } request.BiConnector = biConnector } @@ -420,14 +420,14 @@ func resourceMongoDBAtlasAdvancedClusterCreate(ctx context.Context, d *schema.Re cluster, _, err := conn.AdvancedClusters.Create(ctx, projectID, request) if err != nil { - return diag.FromErr(fmt.Errorf(errorClusterAdvancedCreate, err)) + return diag.FromErr(fmt.Errorf(errorCreate, err)) } timeout := d.Timeout(schema.TimeoutCreate) stateConf := &retry.StateChangeConf{ Pending: []string{"CREATING", "UPDATING", "REPAIRING", "REPEATING", "PENDING"}, Target: []string{"IDLE"}, - Refresh: resourceClusterAdvancedRefreshFunc(ctx, d.Get("name").(string), projectID, conn), + Refresh: resourceRefreshFunc(ctx, d.Get("name").(string), projectID, conn), Timeout: timeout, MinTimeout: 1 * time.Minute, Delay: 3 * time.Minute, @@ -436,7 +436,7 @@ func resourceMongoDBAtlasAdvancedClusterCreate(ctx context.Context, d *schema.Re // Wait, catching any errors _, err = stateConf.WaitForStateContext(ctx) if err != nil { - return diag.FromErr(fmt.Errorf(errorClusterAdvancedCreate, err)) + return diag.FromErr(fmt.Errorf(errorCreate, err)) } /* @@ -450,7 +450,7 @@ func resourceMongoDBAtlasAdvancedClusterCreate(ctx context.Context, d *schema.Re if ok { _, _, err := conn.Clusters.UpdateProcessArgs(ctx, projectID, cluster.Name, advancedConfReq) if err != nil { - return diag.FromErr(fmt.Errorf(errorAdvancedClusterAdvancedConfUpdate, cluster.Name, err)) + return diag.FromErr(fmt.Errorf(errorConfigUpdate, cluster.Name, err)) } } } @@ -463,7 +463,7 @@ func resourceMongoDBAtlasAdvancedClusterCreate(ctx context.Context, d *schema.Re _, _, err = updateAdvancedCluster(ctx, conn, request, projectID, d.Get("name").(string), timeout) if err != nil { - return diag.FromErr(fmt.Errorf(errorClusterAdvancedUpdate, d.Get("name").(string), err)) + return diag.FromErr(fmt.Errorf(errorUpdate, d.Get("name").(string), err)) } } @@ -473,10 +473,10 @@ func resourceMongoDBAtlasAdvancedClusterCreate(ctx context.Context, d *schema.Re "cluster_name": cluster.Name, })) - return resourceMongoDBAtlasAdvancedClusterRead(ctx, d, meta) + return resourceRead(ctx, d, meta) } -func resourceMongoDBAtlasAdvancedClusterRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { +func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Get client connection. conn := meta.(*config.MongoDBClient).Atlas ids := conversion.DecodeStateID(d.Id()) @@ -490,7 +490,7 @@ func resourceMongoDBAtlasAdvancedClusterRead(ctx context.Context, d *schema.Reso return nil } - return diag.FromErr(fmt.Errorf(errorClusterAdvancedRead, clusterName, err)) + return diag.FromErr(fmt.Errorf(errorRead, clusterName, err)) } log.Printf("[DEBUG] GET ClusterAdvanced %+v", cluster) @@ -589,7 +589,7 @@ func resourceMongoDBAtlasAdvancedClusterRead(ctx context.Context, d *schema.Reso */ processArgs, _, err := conn.Clusters.GetProcessArgs(ctx, projectID, clusterName) if err != nil { - return diag.FromErr(fmt.Errorf(errorAdvancedClusterAdvancedConfRead, clusterName, err)) + return diag.FromErr(fmt.Errorf(errorConfigRead, clusterName, err)) } if err := d.Set("advanced_configuration", FlattenProcessArgs(processArgs)); err != nil { @@ -599,7 +599,7 @@ func resourceMongoDBAtlasAdvancedClusterRead(ctx context.Context, d *schema.Reso return nil } -func resourceMongoDBAtlasAdvancedClusterUpdateOrUpgrade(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { +func resourceUpdateOrUpgrade(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { if upgradeRequest := getUpgradeRequest(d); upgradeRequest != nil { upgradeCtx := context.WithValue(ctx, upgradeRequestCtxKey, upgradeRequest) return resourceMongoDBAtlasAdvancedClusterUpgrade(upgradeCtx, d, meta) @@ -623,7 +623,7 @@ func resourceMongoDBAtlasAdvancedClusterUpgrade(ctx context.Context, d *schema.R upgradeResponse, _, err := UpgradeCluster(ctx, conn, upgradeRequest, projectID, clusterName, d.Timeout(schema.TimeoutUpdate)) if err != nil { - return diag.FromErr(fmt.Errorf(errorClusterAdvancedUpdate, clusterName, err)) + return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, err)) } d.SetId(conversion.EncodeStateID(map[string]string{ @@ -632,7 +632,7 @@ func resourceMongoDBAtlasAdvancedClusterUpgrade(ctx context.Context, d *schema.R "cluster_name": clusterName, })) - return resourceMongoDBAtlasAdvancedClusterRead(ctx, d, meta) + return resourceRead(ctx, d, meta) } func resourceMongoDBAtlasAdvancedClusterUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { @@ -718,7 +718,7 @@ func resourceMongoDBAtlasAdvancedClusterUpdate(ctx context.Context, d *schema.Re if !reflect.DeepEqual(advancedConfReq, matlas.ProcessArgs{}) { _, _, err := conn.Clusters.UpdateProcessArgs(ctx, projectID, clusterName, advancedConfReq) if err != nil { - return diag.FromErr(fmt.Errorf(errorAdvancedClusterAdvancedConfUpdate, clusterName, err)) + return diag.FromErr(fmt.Errorf(errorConfigUpdate, clusterName, err)) } } } @@ -730,14 +730,14 @@ func resourceMongoDBAtlasAdvancedClusterUpdate(ctx context.Context, d *schema.Re _, resp, err := updateAdvancedCluster(ctx, conn, cluster, projectID, clusterName, timeout) if err != nil { if resp == nil || resp.StatusCode == 400 { - return retry.NonRetryableError(fmt.Errorf(errorClusterAdvancedUpdate, clusterName, err)) + return retry.NonRetryableError(fmt.Errorf(errorUpdate, clusterName, err)) } - return retry.RetryableError(fmt.Errorf(errorClusterAdvancedUpdate, clusterName, err)) + return retry.RetryableError(fmt.Errorf(errorUpdate, clusterName, err)) } return nil }) if err != nil { - return diag.FromErr(fmt.Errorf(errorClusterAdvancedUpdate, clusterName, err)) + return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, err)) } } @@ -748,14 +748,14 @@ func resourceMongoDBAtlasAdvancedClusterUpdate(ctx context.Context, d *schema.Re _, _, err := updateAdvancedCluster(ctx, conn, clusterRequest, projectID, clusterName, timeout) if err != nil { - return diag.FromErr(fmt.Errorf(errorClusterAdvancedUpdate, clusterName, err)) + return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, err)) } } - return resourceMongoDBAtlasAdvancedClusterRead(ctx, d, meta) + return resourceRead(ctx, d, meta) } -func resourceMongoDBAtlasAdvancedClusterDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { +func resourceDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Get client connection. conn := meta.(*config.MongoDBClient).Atlas ids := conversion.DecodeStateID(d.Id()) @@ -771,7 +771,7 @@ func resourceMongoDBAtlasAdvancedClusterDelete(ctx context.Context, d *schema.Re _, err := conn.AdvancedClusters.Delete(ctx, projectID, clusterName, options) if err != nil { - return diag.FromErr(fmt.Errorf(errorClusterAdvancedDelete, clusterName, err)) + return diag.FromErr(fmt.Errorf(errorDelete, clusterName, err)) } log.Println("[INFO] Waiting for MongoDB ClusterAdvanced to be destroyed") @@ -779,7 +779,7 @@ func resourceMongoDBAtlasAdvancedClusterDelete(ctx context.Context, d *schema.Re stateConf := &retry.StateChangeConf{ Pending: []string{"IDLE", "CREATING", "UPDATING", "REPAIRING", "DELETING"}, Target: []string{"DELETED"}, - Refresh: resourceClusterAdvancedRefreshFunc(ctx, clusterName, projectID, conn), + Refresh: resourceRefreshFunc(ctx, clusterName, projectID, conn), Timeout: d.Timeout(schema.TimeoutDelete), MinTimeout: 30 * time.Second, Delay: 1 * time.Minute, // Wait 30 secs before starting @@ -788,13 +788,13 @@ func resourceMongoDBAtlasAdvancedClusterDelete(ctx context.Context, d *schema.Re // Wait, catching any errors _, err = stateConf.WaitForStateContext(ctx) if err != nil { - return diag.FromErr(fmt.Errorf(errorClusterAdvancedDelete, clusterName, err)) + return diag.FromErr(fmt.Errorf(errorDelete, clusterName, err)) } return nil } -func resourceMongoDBAtlasAdvancedClusterImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { +func resourceImport(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { conn := meta.(*config.MongoDBClient).Atlas projectID, name, err := splitSClusterAdvancedImportID(d.Id()) @@ -1239,7 +1239,7 @@ func flattenAdvancedReplicationSpecAutoScaling(apiObject *matlas.AdvancedAutoSca return tfList } -func resourceClusterAdvancedRefreshFunc(ctx context.Context, name, projectID string, client *matlas.Client) retry.StateRefreshFunc { +func resourceRefreshFunc(ctx context.Context, name, projectID string, client *matlas.Client) retry.StateRefreshFunc { return func() (any, string, error) { c, resp, err := client.AdvancedClusters.Get(ctx, projectID, name) @@ -1323,7 +1323,7 @@ func updateAdvancedCluster( stateConf := &retry.StateChangeConf{ Pending: []string{"CREATING", "UPDATING", "REPAIRING"}, Target: []string{"IDLE"}, - Refresh: resourceClusterAdvancedRefreshFunc(ctx, name, projectID, conn), + Refresh: resourceRefreshFunc(ctx, name, projectID, conn), Timeout: timeout, MinTimeout: 30 * time.Second, Delay: 1 * time.Minute, diff --git a/internal/service/advancedcluster/resource_advanced_cluster_schema_migration.go b/internal/service/advancedcluster/resource_advanced_cluster_schema_migration.go index 88a4f86aaf..7cd69985ca 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_schema_migration.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_schema_migration.go @@ -129,7 +129,7 @@ func ResourceV0() *schema.Resource { Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "analytics_specs": advancedClusterRegionConfigsSpecsSchema(), + "analytics_specs": schemaSpecs(), "auto_scaling": { Type: schema.TypeList, MaxItems: 1, @@ -169,7 +169,7 @@ func ResourceV0() *schema.Resource { Type: schema.TypeString, Optional: true, }, - "electable_specs": advancedClusterRegionConfigsSpecsSchema(), + "electable_specs": schemaSpecs(), "priority": { Type: schema.TypeInt, Required: true, @@ -178,7 +178,7 @@ func ResourceV0() *schema.Resource { Type: schema.TypeString, Required: true, }, - "read_only_specs": advancedClusterRegionConfigsSpecsSchema(), + "read_only_specs": schemaSpecs(), "region_name": { Type: schema.TypeString, Required: true, @@ -232,7 +232,7 @@ func ResourceV0() *schema.Resource { } } -func resourceMongoDBAtlasAdvancedClusterStateUpgradeV0(ctx context.Context, rawState map[string]any, meta any) (map[string]any, error) { +func resourceStateUpgradeV0(ctx context.Context, rawState map[string]any, meta any) (map[string]any, error) { return MigrateBIConnectorConfig(rawState), nil } diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 86aa44838b..3774fae276 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -17,6 +17,45 @@ import ( matlas "go.mongodb.org/atlas/mongodbatlas" ) +func TestAccClusterAdvancedCluster_basic(t *testing.T) { + // TEMPORARY: to delete, based on TestAccClusterAdvancedCluster_basicTenant + var ( + cluster matlas.AdvancedCluster + resourceName = "mongodbatlas_advanced_cluster.test" + dataSourceName = "data.mongodbatlas_advanced_cluster.test" + dataSourceClustersName = "data.mongodbatlas_advanced_clusters.test" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acctest.RandomWithPrefix("test-acc") + rName = acctest.RandomWithPrefix("test-acc") + ) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acc.PreCheckBasic(t) }, + ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, + CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + Steps: []resource.TestStep{ + { + Config: configTenant(orgID, projectName, rName), + Check: resource.ComposeTestCheckFunc( + checkExists(resourceName, &cluster), + testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), + resource.TestCheckResourceAttrSet(resourceName, "project_id"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), + resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), + resource.TestCheckResourceAttrSet(resourceName, "termination_protection_enabled"), + resource.TestCheckResourceAttr(dataSourceName, "name", rName), + resource.TestCheckResourceAttr(dataSourceName, "termination_protection_enabled", "false"), + resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.#"), + resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.replication_specs.#"), + resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.name"), + resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.termination_protection_enabled"), + ), + }, + }, + }) +} + func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { var ( cluster matlas.AdvancedCluster @@ -35,9 +74,9 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigTenant(orgID, projectName, rName), + Config: configTenant(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -53,9 +92,9 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigTenant(orgID, projectName, rNameUpdated), + Config: configTenant(orgID, projectName, rNameUpdated), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), @@ -96,9 +135,9 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigSingleProvider(orgID, projectName, rName), + Config: configSingleProvider(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -110,9 +149,9 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigMultiCloud(orgID, projectName, rName), + Config: configMultiCloud(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -150,9 +189,9 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigMultiCloud(orgID, projectName, rName), + Config: configMultiCloud(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -166,9 +205,9 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigMultiCloud(orgID, projectName, rNameUpdated), + Config: configMultiCloud(orgID, projectName, rNameUpdated), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), @@ -208,9 +247,9 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigMultiCloudSharded(orgID, projectName, rName), + Config: configMultiCloudSharded(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -219,9 +258,9 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigMultiCloudSharded(orgID, projectName, rNameUpdated), + Config: configMultiCloudSharded(orgID, projectName, rNameUpdated), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), @@ -257,9 +296,9 @@ func TestAccClusterAdvancedCluster_UnpausedToPaused(t *testing.T) { CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigSingleProviderPaused(orgID, projectName, rName, false, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, rName, false, instanceSize), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -269,9 +308,9 @@ func TestAccClusterAdvancedCluster_UnpausedToPaused(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigSingleProviderPaused(orgID, projectName, rName, true, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, rName, true, instanceSize), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -281,7 +320,7 @@ func TestAccClusterAdvancedCluster_UnpausedToPaused(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigSingleProviderPaused(orgID, projectName, rName, true, anotherInstanceSize), + Config: configSingleProviderPaused(orgID, projectName, rName, true, anotherInstanceSize), ExpectError: regexp.MustCompile("CANNOT_UPDATE_PAUSED_CLUSTER"), }, { @@ -311,9 +350,9 @@ func TestAccClusterAdvancedCluster_PausedToUnpaused(t *testing.T) { CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigSingleProviderPaused(orgID, projectName, rName, true, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, rName, true, instanceSize), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -323,9 +362,9 @@ func TestAccClusterAdvancedCluster_PausedToUnpaused(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigSingleProviderPaused(orgID, projectName, rName, false, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, rName, false, instanceSize), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -335,11 +374,11 @@ func TestAccClusterAdvancedCluster_PausedToUnpaused(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigSingleProviderPaused(orgID, projectName, rName, true, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, rName, true, instanceSize), ExpectError: regexp.MustCompile("CANNOT_PAUSE_RECENTLY_RESUMED_CLUSTER"), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigSingleProviderPaused(orgID, projectName, rName, false, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, rName, false, instanceSize), }, { ResourceName: resourceName, @@ -352,7 +391,7 @@ func TestAccClusterAdvancedCluster_PausedToUnpaused(t *testing.T) { }) } -func TestAccClusterAdvancedCluster_advancedConf(t *testing.T) { +func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -394,9 +433,9 @@ func TestAccClusterAdvancedCluster_advancedConf(t *testing.T) { CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigAdvancedConf(orgID, projectName, rName, processArgs), + Config: configAdvanced(orgID, projectName, rName, processArgs), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), @@ -413,9 +452,9 @@ func TestAccClusterAdvancedCluster_advancedConf(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigAdvancedConf(orgID, projectName, rNameUpdated, processArgsUpdated), + Config: configAdvanced(orgID, projectName, rNameUpdated, processArgsUpdated), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), @@ -435,7 +474,7 @@ func TestAccClusterAdvancedCluster_advancedConf(t *testing.T) { }) } -func TestAccClusterAdvancedCluster_DefaultWrite(t *testing.T) { +func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -472,9 +511,9 @@ func TestAccClusterAdvancedCluster_DefaultWrite(t *testing.T) { CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigAdvancedConfDefaultWrite(orgID, projectName, rName, processArgs), + Config: configAdvancedDefaultWrite(orgID, projectName, rName, processArgs), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_read_concern", "available"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_write_concern", "1"), @@ -488,9 +527,9 @@ func TestAccClusterAdvancedCluster_DefaultWrite(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigAdvancedConfDefaultWrite(orgID, projectName, rNameUpdated, processArgsUpdated), + Config: configAdvancedDefaultWrite(orgID, projectName, rNameUpdated, processArgsUpdated), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_read_concern", "available"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_write_concern", "majority"), @@ -507,7 +546,7 @@ func TestAccClusterAdvancedCluster_DefaultWrite(t *testing.T) { }) } -func TestAccClusterAdvancedClusterConfig_ReplicationSpecsAutoScaling(t *testing.T) { +func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing.T) { var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -531,18 +570,18 @@ func TestAccClusterAdvancedClusterConfig_ReplicationSpecsAutoScaling(t *testing. CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigReplicationSpecsAutoScaling(orgID, projectName, rName, autoScaling), + Config: configReplicationSpecsAutoScaling(orgID, projectName, rName, autoScaling), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), testAccCheckMongoDBAtlasAdvancedClusterScaling(&cluster, *autoScaling.Compute.Enabled), ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigReplicationSpecsAutoScaling(orgID, projectName, rNameUpdated, autoScalingUpdated), + Config: configReplicationSpecsAutoScaling(orgID, projectName, rNameUpdated, autoScalingUpdated), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), testAccCheckMongoDBAtlasAdvancedClusterScaling(&cluster, *autoScalingUpdated.Compute.Enabled), @@ -552,7 +591,7 @@ func TestAccClusterAdvancedClusterConfig_ReplicationSpecsAutoScaling(t *testing. }) } -func TestAccClusterAdvancedClusterConfig_ReplicationSpecsAnalyticsAutoScaling(t *testing.T) { +func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t *testing.T) { var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -576,18 +615,18 @@ func TestAccClusterAdvancedClusterConfig_ReplicationSpecsAnalyticsAutoScaling(t CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigReplicationSpecsAnalyticsAutoScaling(orgID, projectName, rName, autoScaling), + Config: configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, rName, autoScaling), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), testAccCheckMongoDBAtlasAdvancedClusterAnalyticsScaling(&cluster, *autoScaling.Compute.Enabled), ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigReplicationSpecsAnalyticsAutoScaling(orgID, projectName, rNameUpdated, autoScalingUpdated), + Config: configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, rNameUpdated, autoScalingUpdated), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), testAccCheckMongoDBAtlasAdvancedClusterAnalyticsScaling(&cluster, *autoScalingUpdated.Compute.Enabled), @@ -597,7 +636,7 @@ func TestAccClusterAdvancedClusterConfig_ReplicationSpecsAnalyticsAutoScaling(t }) } -func TestAccClusterAdvancedClusterConfig_ReplicationSpecsAndShardUpdating(t *testing.T) { +func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *testing.T) { var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -614,18 +653,18 @@ func TestAccClusterAdvancedClusterConfig_ReplicationSpecsAndShardUpdating(t *tes CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigMultiZoneWithShards(orgID, projectName, rName, numShards, numShards), + Config: configMultiZoneWithShards(orgID, projectName, rName, numShards, numShards), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.num_shards", "1"), resource.TestCheckResourceAttr(resourceName, "replication_specs.1.num_shards", "1"), ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigMultiZoneWithShards(orgID, projectName, rName, numShardsUpdated, numShards), + Config: configMultiZoneWithShards(orgID, projectName, rName, numShardsUpdated, numShards), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.num_shards", "2"), resource.TestCheckResourceAttr(resourceName, "replication_specs.1.num_shards", "1"), @@ -635,7 +674,7 @@ func TestAccClusterAdvancedClusterConfig_ReplicationSpecsAndShardUpdating(t *tes }) } -func TestAccClusterAdvancedCluster_WithTags(t *testing.T) { +func TestAccClusterAdvancedCluster_withTags(t *testing.T) { var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -652,9 +691,9 @@ func TestAccClusterAdvancedCluster_WithTags(t *testing.T) { CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasAdvancedClusterConfigWithTags(orgID, projectName, rName, []matlas.Tag{}), + Config: configWithTags(orgID, projectName, rName, []matlas.Tag{}), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -664,7 +703,7 @@ func TestAccClusterAdvancedCluster_WithTags(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigWithTags(orgID, projectName, rName, []matlas.Tag{ + Config: configWithTags(orgID, projectName, rName, []matlas.Tag{ { Key: "key 1", Value: "value 1", @@ -675,7 +714,7 @@ func TestAccClusterAdvancedCluster_WithTags(t *testing.T) { }, }), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -691,14 +730,14 @@ func TestAccClusterAdvancedCluster_WithTags(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasAdvancedClusterConfigWithTags(orgID, projectName, rName, []matlas.Tag{ + Config: configWithTags(orgID, projectName, rName, []matlas.Tag{ { Key: "key 3", Value: "value 3", }, }), Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -714,7 +753,7 @@ func TestAccClusterAdvancedCluster_WithTags(t *testing.T) { }) } -func testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName string, cluster *matlas.AdvancedCluster) resource.TestCheckFunc { +func checkExists(resourceName string, cluster *matlas.AdvancedCluster) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { @@ -763,7 +802,7 @@ func testAccCheckMongoDBAtlasAdvancedClusterAnalyticsScaling(cluster *matlas.Adv } } -func testAccMongoDBAtlasAdvancedClusterConfigTenant(orgID, projectName, name string) string { +func configTenant(orgID, projectName, name string) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { name = %[2]q @@ -798,7 +837,7 @@ data "mongodbatlas_advanced_clusters" "test" { `, orgID, projectName, name) } -func testAccMongoDBAtlasAdvancedClusterConfigWithTags(orgID, projectName, name string, tags []matlas.Tag) string { +func configWithTags(orgID, projectName, name string, tags []matlas.Tag) string { var tagsConf string for _, label := range tags { tagsConf += fmt.Sprintf(` @@ -850,7 +889,7 @@ func testAccMongoDBAtlasAdvancedClusterConfigWithTags(orgID, projectName, name s `, orgID, projectName, name, tagsConf) } -func testAccMongoDBAtlasAdvancedClusterConfigSingleProvider(orgID, projectName, name string) string { +func configSingleProvider(orgID, projectName, name string) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { name = %[2]q @@ -886,7 +925,7 @@ data "mongodbatlas_advanced_cluster" "test" { `, orgID, projectName, name) } -func testAccMongoDBAtlasAdvancedClusterConfigMultiCloud(orgID, projectName, name string) string { +func configMultiCloud(orgID, projectName, name string) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { name = %[2]q @@ -935,7 +974,7 @@ data "mongodbatlas_advanced_clusters" "test" { `, orgID, projectName, name) } -func testAccMongoDBAtlasAdvancedClusterConfigMultiCloudSharded(orgID, projectName, name string) string { +func configMultiCloudSharded(orgID, projectName, name string) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { name = %[2]q @@ -975,7 +1014,7 @@ resource "mongodbatlas_advanced_cluster" "test" { `, orgID, projectName, name) } -func testAccMongoDBAtlasAdvancedClusterConfigSingleProviderPaused(orgID, projectName, name string, paused bool, instanceSize string) string { +func configSingleProviderPaused(orgID, projectName, name string, paused bool, instanceSize string) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { name = %[2]q @@ -1006,7 +1045,7 @@ resource "mongodbatlas_advanced_cluster" "test" { `, orgID, projectName, name, paused, instanceSize) } -func testAccMongoDBAtlasAdvancedClusterConfigAdvancedConf(orgID, projectName, name string, p *matlas.ProcessArgs) string { +func configAdvanced(orgID, projectName, name string, p *matlas.ProcessArgs) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { name = %[2]q @@ -1058,7 +1097,7 @@ data "mongodbatlas_advanced_clusters" "test" { *p.OplogSizeMB, *p.SampleSizeBIConnector, *p.SampleRefreshIntervalBIConnector, *p.TransactionLifetimeLimitSeconds) } -func testAccMongoDBAtlasAdvancedClusterConfigAdvancedConfDefaultWrite(orgID, projectName, name string, p *matlas.ProcessArgs) string { +func configAdvancedDefaultWrite(orgID, projectName, name string, p *matlas.ProcessArgs) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { name = %[2]q @@ -1101,7 +1140,7 @@ resource "mongodbatlas_advanced_cluster" "test" { *p.OplogSizeMB, *p.SampleSizeBIConnector, *p.SampleRefreshIntervalBIConnector, p.DefaultReadConcern, p.DefaultWriteConcern) } -func testAccMongoDBAtlasAdvancedClusterConfigReplicationSpecsAutoScaling(orgID, projectName, name string, p *matlas.AutoScaling) string { +func configReplicationSpecsAutoScaling(orgID, projectName, name string, p *matlas.AutoScaling) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { name = %[2]q @@ -1139,7 +1178,7 @@ resource "mongodbatlas_advanced_cluster" "test" { `, orgID, projectName, name, *p.Compute.Enabled, *p.DiskGBEnabled, p.Compute.MaxInstanceSize) } -func testAccMongoDBAtlasAdvancedClusterConfigReplicationSpecsAnalyticsAutoScaling(orgID, projectName, name string, p *matlas.AutoScaling) string { +func configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, name string, p *matlas.AutoScaling) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { @@ -1179,7 +1218,7 @@ resource "mongodbatlas_advanced_cluster" "test" { `, orgID, projectName, name, *p.Compute.Enabled, *p.DiskGBEnabled, p.Compute.MaxInstanceSize) } -func testAccMongoDBAtlasAdvancedClusterConfigMultiZoneWithShards(orgID, projectName, name, numShardsFirstZone, numShardsSecondZone string) string { +func configMultiZoneWithShards(orgID, projectName, name, numShardsFirstZone, numShardsSecondZone string) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { From 1f96b8221f64d6a8e03d83439f1800aab92dc0b2 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Wed, 14 Feb 2024 16:31:50 +0100 Subject: [PATCH 02/52] mig.TestStep --- ...esource_advanced_cluster_migration_test.go | 33 +++++-------------- 1 file changed, 8 insertions(+), 25 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go index 565ff9476b..098a88d6e4 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go @@ -6,7 +6,6 @@ import ( "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" matlas "go.mongodb.org/atlas/mongodbatlas" @@ -19,6 +18,7 @@ func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") rName = acctest.RandomWithPrefix("test-acc") + config = configSingleProvider(orgID, projectName, rName) ) resource.ParallelTest(t, resource.TestCase{ @@ -27,9 +27,9 @@ func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: testAccMongoDBAtlasAdvancedClusterConfigSingleProvider(orgID, projectName, rName), + Config: config, Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -38,16 +38,7 @@ func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: testAccMongoDBAtlasAdvancedClusterConfigSingleProvider(orgID, projectName, rName), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStep(config), }, }) } @@ -59,6 +50,7 @@ func TestAccMigrationAdvancedClusterRS_multiCloud(t *testing.T) { orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") rName = acctest.RandomWithPrefix("test-acc") + config = configMultiCloud(orgID, projectName, rName) ) resource.ParallelTest(t, resource.TestCase{ @@ -67,9 +59,9 @@ func TestAccMigrationAdvancedClusterRS_multiCloud(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: testAccMongoDBAtlasAdvancedClusterConfigMultiCloud(orgID, projectName, rName), + Config: config, Check: resource.ComposeTestCheckFunc( - testAccCheckMongoDBAtlasAdvancedClusterExists(resourceName, &cluster), + checkExists(resourceName, &cluster), testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -78,16 +70,7 @@ func TestAccMigrationAdvancedClusterRS_multiCloud(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: testAccMongoDBAtlasAdvancedClusterConfigMultiCloud(orgID, projectName, rName), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStep(config), }, }) } From 9464d48af7d8dae3f40f0b03d14bccdc3250fc4a Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Wed, 14 Feb 2024 16:32:40 +0100 Subject: [PATCH 03/52] SkipInUnitTest --- .../resource_advanced_cluster_schema_migration_test.go | 3 +++ internal/testutil/acc/skip.go | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_schema_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_schema_migration_test.go index 2a6c966a03..e07b219eb9 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_schema_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_schema_migration_test.go @@ -6,9 +6,11 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/advancedcluster" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) func TestAccMigrationAdvancedCluster_empty_advancedConfig(t *testing.T) { + acc.SkipInUnitTest(t) // needed because TF test infra is not used v0State := map[string]any{ "project_id": "test-id", "name": "test-cluster", @@ -61,6 +63,7 @@ func TestAccMigrationAdvancedCluster_empty_advancedConfig(t *testing.T) { } func TestAccMigrationAdvancedCluster_v0StateUpgrade_ReplicationSpecs(t *testing.T) { + acc.SkipInUnitTest(t) // needed because TF test infra is not used v0State := map[string]any{ "project_id": "test-id", "name": "test-cluster", diff --git a/internal/testutil/acc/skip.go b/internal/testutil/acc/skip.go index e6b36d18ca..801f95ce72 100644 --- a/internal/testutil/acc/skip.go +++ b/internal/testutil/acc/skip.go @@ -13,3 +13,11 @@ func SkipTestForCI(tb testing.TB) { tb.Skip() } } + +// SkipInUnitTest is rarely needed, it is used in acc and mig tests to make sure that they don't run in unit test mode. +func SkipInUnitTest(tb testing.TB) { + tb.Helper() + if os.Getenv("TF_ACC") == "" { + tb.Skip() + } +} From 508d117c2efe1ccc98ab744178dc46a724ff7d44 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Wed, 14 Feb 2024 16:36:31 +0100 Subject: [PATCH 04/52] TEMPORARY skip most acc tests --- .../resource_advanced_cluster_migration_test.go | 2 ++ .../resource_advanced_cluster_test.go | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go index 098a88d6e4..1219ccff8c 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go @@ -12,6 +12,7 @@ import ( ) func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -44,6 +45,7 @@ func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { } func TestAccMigrationAdvancedClusterRS_multiCloud(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 3774fae276..eb518c3979 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -57,6 +57,7 @@ func TestAccClusterAdvancedCluster_basic(t *testing.T) { } func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -120,6 +121,7 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { } func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -172,6 +174,7 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { } func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -232,6 +235,7 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { } func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -279,7 +283,8 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { }) } -func TestAccClusterAdvancedCluster_UnpausedToPaused(t *testing.T) { +func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -334,7 +339,8 @@ func TestAccClusterAdvancedCluster_UnpausedToPaused(t *testing.T) { }) } -func TestAccClusterAdvancedCluster_PausedToUnpaused(t *testing.T) { +func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -392,6 +398,7 @@ func TestAccClusterAdvancedCluster_PausedToUnpaused(t *testing.T) { } func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -475,6 +482,7 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { } func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -547,6 +555,7 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { } func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -592,6 +601,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. } func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -637,6 +647,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t } func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" @@ -675,6 +686,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes } func TestAccClusterAdvancedCluster_withTags(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" From cee25523474a6ef0d75f15ddc78734c23764bd1d Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Wed, 14 Feb 2024 16:56:21 +0100 Subject: [PATCH 05/52] CheckDestroyTeamAdvancedCluster with new SDK --- internal/testutil/acc/advanced_cluster.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/testutil/acc/advanced_cluster.go b/internal/testutil/acc/advanced_cluster.go index 35d30d77af..24f1be40b6 100644 --- a/internal/testutil/acc/advanced_cluster.go +++ b/internal/testutil/acc/advanced_cluster.go @@ -47,7 +47,7 @@ func CheckDestroyTeamAdvancedCluster(s *terraform.State) error { } // Try to find the cluster - _, _, err := Conn().AdvancedClusters.Get(context.Background(), rs.Primary.Attributes["project_id"], rs.Primary.Attributes["cluster_name"]) + _, _, err := ConnV2().ClustersApi.GetCluster(context.Background(), rs.Primary.Attributes["project_id"], rs.Primary.Attributes["cluster_name"]).Execute() if err == nil { return fmt.Errorf("cluster (%s:%s) still exists", rs.Primary.Attributes["cluster_name"], rs.Primary.ID) From 9ed4f9dc35cffb9be3aaa693a998b5061ea0d4ce Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 08:12:01 +0100 Subject: [PATCH 06/52] more renames --- .../service/advancedcluster/common_advanced_cluster.go | 6 +++--- .../advancedcluster/data_source_advanced_cluster.go | 8 ++++---- .../advancedcluster/data_source_advanced_clusters.go | 8 ++++---- .../service/advancedcluster/resource_advanced_cluster.go | 4 ++-- .../resource_advanced_cluster_schema_migration.go | 4 ++-- internal/service/cluster/data_source_cluster.go | 2 +- internal/service/cluster/data_source_clusters.go | 2 +- internal/service/cluster/resource_cluster.go | 4 ++-- 8 files changed, 19 insertions(+), 19 deletions(-) diff --git a/internal/service/advancedcluster/common_advanced_cluster.go b/internal/service/advancedcluster/common_advanced_cluster.go index 8d9726cc34..87528f3049 100644 --- a/internal/service/advancedcluster/common_advanced_cluster.go +++ b/internal/service/advancedcluster/common_advanced_cluster.go @@ -391,7 +391,7 @@ func ExpandLabelSliceFromSetSchema(d *schema.ResourceData) []matlas.Label { return res } -func ClusterAdvancedConfigurationSchemaComputed() *schema.Schema { +func SchemaAdvancedConfigDS() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, Computed: true, @@ -446,7 +446,7 @@ func ClusterAdvancedConfigurationSchemaComputed() *schema.Schema { } } -func ClusterConnectionStringsSchema() *schema.Schema { +func SchemaConnectionStrings() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, Computed: true, @@ -520,7 +520,7 @@ func ClusterConnectionStringsSchema() *schema.Schema { } } -func ClusterAdvancedConfigurationSchema() *schema.Schema { +func SchemaAdvancedConfig() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, Optional: true, diff --git a/internal/service/advancedcluster/data_source_advanced_cluster.go b/internal/service/advancedcluster/data_source_advanced_cluster.go index f5686c2130..3f303dfce6 100644 --- a/internal/service/advancedcluster/data_source_advanced_cluster.go +++ b/internal/service/advancedcluster/data_source_advanced_cluster.go @@ -13,13 +13,13 @@ import ( func DataSource() *schema.Resource { return &schema.Resource{ - ReadContext: dataSourceMongoDBAtlasAdvancedClusterRead, + ReadContext: dataSourceRead, Schema: map[string]*schema.Schema{ "project_id": { Type: schema.TypeString, Required: true, }, - "advanced_configuration": ClusterAdvancedConfigurationSchemaComputed(), + "advanced_configuration": SchemaAdvancedConfigDS(), "backup_enabled": { Type: schema.TypeBool, Computed: true, @@ -46,7 +46,7 @@ func DataSource() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "connection_strings": ClusterConnectionStringsSchema(), + "connection_strings": SchemaConnectionStrings(), "create_date": { Type: schema.TypeString, Computed: true, @@ -229,7 +229,7 @@ func DataSource() *schema.Resource { } } -func dataSourceMongoDBAtlasAdvancedClusterRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { +func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Get client connection. conn := meta.(*config.MongoDBClient).Atlas projectID := d.Get("project_id").(string) diff --git a/internal/service/advancedcluster/data_source_advanced_clusters.go b/internal/service/advancedcluster/data_source_advanced_clusters.go index 66dbb294b6..884d20f1e5 100644 --- a/internal/service/advancedcluster/data_source_advanced_clusters.go +++ b/internal/service/advancedcluster/data_source_advanced_clusters.go @@ -16,7 +16,7 @@ import ( func PluralDataSource() *schema.Resource { return &schema.Resource{ - ReadContext: dataSourceMongoDBAtlasAdvancedClustersRead, + ReadContext: dataSourcePluralRead, Schema: map[string]*schema.Schema{ "project_id": { Type: schema.TypeString, @@ -27,7 +27,7 @@ func PluralDataSource() *schema.Resource { Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "advanced_configuration": ClusterAdvancedConfigurationSchemaComputed(), + "advanced_configuration": SchemaAdvancedConfigDS(), "backup_enabled": { Type: schema.TypeBool, Computed: true, @@ -54,7 +54,7 @@ func PluralDataSource() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "connection_strings": ClusterConnectionStringsSchema(), + "connection_strings": SchemaConnectionStrings(), "create_date": { Type: schema.TypeString, Computed: true, @@ -240,7 +240,7 @@ func PluralDataSource() *schema.Resource { } } -func dataSourceMongoDBAtlasAdvancedClustersRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { +func dataSourcePluralRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { // Get client connection. conn := meta.(*config.MongoDBClient).Atlas projectID := d.Get("project_id").(string) diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index b2ddc89966..a154ec887e 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -99,7 +99,7 @@ func Resource() *schema.Resource { Type: schema.TypeString, Required: true, }, - "connection_strings": ClusterConnectionStringsSchema(), + "connection_strings": SchemaConnectionStrings(), "create_date": { Type: schema.TypeString, Computed: true, @@ -308,7 +308,7 @@ func Resource() *schema.Resource { Computed: true, ValidateFunc: validation.StringInSlice([]string{"LTS", "CONTINUOUS"}, false), }, - "advanced_configuration": ClusterAdvancedConfigurationSchema(), + "advanced_configuration": SchemaAdvancedConfig(), "accept_data_risks_and_force_replica_set_reconfig": { Type: schema.TypeString, Optional: true, diff --git a/internal/service/advancedcluster/resource_advanced_cluster_schema_migration.go b/internal/service/advancedcluster/resource_advanced_cluster_schema_migration.go index 7cd69985ca..5894aabbbf 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_schema_migration.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_schema_migration.go @@ -49,7 +49,7 @@ func ResourceV0() *schema.Resource { Type: schema.TypeString, Required: true, }, - "connection_strings": ClusterConnectionStringsSchema(), + "connection_strings": SchemaConnectionStrings(), "create_date": { Type: schema.TypeString, Computed: true, @@ -222,7 +222,7 @@ func ResourceV0() *schema.Resource { Default: "LTS", ValidateFunc: validation.StringInSlice([]string{"LTS", "CONTINUOUS"}, false), }, - "advanced_configuration": ClusterAdvancedConfigurationSchema(), + "advanced_configuration": SchemaAdvancedConfig(), }, Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(3 * time.Hour), diff --git a/internal/service/cluster/data_source_cluster.go b/internal/service/cluster/data_source_cluster.go index de63af56f9..535326abdc 100644 --- a/internal/service/cluster/data_source_cluster.go +++ b/internal/service/cluster/data_source_cluster.go @@ -25,7 +25,7 @@ func DataSource() *schema.Resource { Type: schema.TypeString, Required: true, }, - "advanced_configuration": advancedcluster.ClusterAdvancedConfigurationSchemaComputed(), + "advanced_configuration": advancedcluster.SchemaAdvancedConfigDS(), "auto_scaling_disk_gb_enabled": { Type: schema.TypeBool, Computed: true, diff --git a/internal/service/cluster/data_source_clusters.go b/internal/service/cluster/data_source_clusters.go index f42ad47141..8a4ad60c4d 100644 --- a/internal/service/cluster/data_source_clusters.go +++ b/internal/service/cluster/data_source_clusters.go @@ -32,7 +32,7 @@ func PluralDataSource() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "advanced_configuration": advancedcluster.ClusterAdvancedConfigurationSchemaComputed(), + "advanced_configuration": advancedcluster.SchemaAdvancedConfigDS(), "auto_scaling_disk_gb_enabled": { Type: schema.TypeBool, Computed: true, diff --git a/internal/service/cluster/resource_cluster.go b/internal/service/cluster/resource_cluster.go index 30c4089d1d..a6f73f5b82 100644 --- a/internal/service/cluster/resource_cluster.go +++ b/internal/service/cluster/resource_cluster.go @@ -113,7 +113,7 @@ func Resource() *schema.Resource { Optional: true, Computed: true, }, - "connection_strings": advancedcluster.ClusterConnectionStringsSchema(), + "connection_strings": advancedcluster.SchemaConnectionStrings(), "disk_size_gb": { Type: schema.TypeFloat, Optional: true, @@ -306,7 +306,7 @@ func Resource() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "advanced_configuration": advancedcluster.ClusterAdvancedConfigurationSchema(), + "advanced_configuration": advancedcluster.SchemaAdvancedConfig(), "labels": { Type: schema.TypeSet, Optional: true, From c8a699113393fad0bf19061ac5b5acd95c9c8937 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 08:19:10 +0100 Subject: [PATCH 07/52] unify CheckDestroy --- ...esource_advanced_cluster_migration_test.go | 4 +- .../resource_advanced_cluster_test.go | 26 ++++---- .../service/cluster/resource_cluster_test.go | 62 +++++++++---------- .../resource_online_archive_test.go | 8 +-- .../resource_search_deployment_test.go | 2 +- internal/testutil/acc/advanced_cluster.go | 29 ++------- 6 files changed, 57 insertions(+), 74 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go index 1219ccff8c..c070d459d5 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go @@ -24,7 +24,7 @@ func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { mig.PreCheckBasic(t) }, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), @@ -57,7 +57,7 @@ func TestAccMigrationAdvancedClusterRS_multiCloud(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { mig.PreCheckBasic(t) }, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index eb518c3979..f41f805f2c 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -32,7 +32,7 @@ func TestAccClusterAdvancedCluster_basic(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configTenant(orgID, projectName, rName), @@ -72,7 +72,7 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configTenant(orgID, projectName, rName), @@ -134,7 +134,7 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configSingleProvider(orgID, projectName, rName), @@ -189,7 +189,7 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configMultiCloud(orgID, projectName, rName), @@ -248,7 +248,7 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configMultiCloudSharded(orgID, projectName, rName), @@ -298,7 +298,7 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configSingleProviderPaused(orgID, projectName, rName, false, instanceSize), @@ -353,7 +353,7 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configSingleProviderPaused(orgID, projectName, rName, true, instanceSize), @@ -437,7 +437,7 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configAdvanced(orgID, projectName, rName, processArgs), @@ -516,7 +516,7 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configAdvancedDefaultWrite(orgID, projectName, rName, processArgs), @@ -576,7 +576,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configReplicationSpecsAutoScaling(orgID, projectName, rName, autoScaling), @@ -622,7 +622,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, rName, autoScaling), @@ -661,7 +661,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configMultiZoneWithShards(orgID, projectName, rName, numShards, numShards), @@ -700,7 +700,7 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyTeamAdvancedCluster, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configWithTags(orgID, projectName, rName, []matlas.Tag{}), diff --git a/internal/service/cluster/resource_cluster_test.go b/internal/service/cluster/resource_cluster_test.go index 28ef371843..605105449a 100644 --- a/internal/service/cluster/resource_cluster_test.go +++ b/internal/service/cluster/resource_cluster_test.go @@ -32,7 +32,7 @@ func TestAccClusterRSCluster_basicAWS_simple(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAWS(orgID, projectName, name, true, true), @@ -90,7 +90,7 @@ func TestAccClusterRSCluster_basicAWS_instanceScale(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAWSNVMEInstance(orgID, projectName, name, "M40_NVME"), @@ -132,7 +132,7 @@ func TestAccClusterRSCluster_basic_Partial_AdvancedConf(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAdvancedConf(orgID, projectName, name, "false", &matlas.ProcessArgs{ @@ -203,7 +203,7 @@ func TestAccClusterRSCluster_basic_DefaultWriteRead_AdvancedConf(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAdvancedConfDefaultWriteRead(orgID, projectName, name, "false", &matlas.ProcessArgs{ @@ -263,7 +263,7 @@ func TestAccClusterRSCluster_emptyAdvancedConf(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAdvancedConfPartial(orgID, projectName, name, "false", &matlas.ProcessArgs{ @@ -308,7 +308,7 @@ func TestAccClusterRSCluster_basicAdvancedConf(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAdvancedConf(orgID, projectName, name, "false", &matlas.ProcessArgs{ @@ -374,7 +374,7 @@ func TestAccClusterRSCluster_basicAzure(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAzure(orgID, projectName, name, "true", "M30", true), @@ -415,7 +415,7 @@ func TestAccClusterRSCluster_AzureUpdateToNVME(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAzure(orgID, projectName, name, "true", "M60", true), @@ -459,7 +459,7 @@ func TestAccClusterRSCluster_basicGCP(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigGCP(orgID, projectName, name, "true"), @@ -503,7 +503,7 @@ func TestAccClusterRSCluster_WithBiConnectorGCP(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigGCPWithBiConnector(orgID, projectName, name, "true", false), @@ -575,7 +575,7 @@ func TestAccClusterRSCluster_MultiRegion(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigMultiRegion(orgID, projectName, name, "true", createRegionsConfig), @@ -644,7 +644,7 @@ func TestAccClusterRSCluster_ProviderRegionName(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigMultiRegionWithProviderRegionNameInvalid(orgID, projectName, name, "false", updatedRegionsConfig), @@ -708,7 +708,7 @@ func TestAccClusterRSCluster_Global(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: acc.ConfigClusterGlobal(resourceSuffix, orgID, projectName, name, "false"), @@ -744,7 +744,7 @@ func TestAccClusterRSCluster_AWSWithLabels(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterAWSConfigdWithLabels(orgID, projectName, name, "false", "M10", "EU_CENTRAL_1", []matlas.Label{}), @@ -826,7 +826,7 @@ func TestAccClusterRSCluster_WithTags(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigWithTags(orgID, projectName, name, "false", "M10", "EU_CENTRAL_1", []matlas.Tag{}), @@ -920,7 +920,7 @@ func TestAccClusterRSCluster_withPrivateEndpointLink(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t); acc.PreCheckAwsEnv(t); acc.PreCheckPeeringEnvAWS(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigWithPrivateEndpointLink( @@ -955,7 +955,7 @@ func TestAccClusterRSCluster_withAzureNetworkPeering(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAzureWithNetworkPeering(projectID, providerName, directoryID, subcrptionID, resourceGroupName, vNetName, clusterName, atlasCidrBlock, region), @@ -986,7 +986,7 @@ func TestAccClusterRSCluster_withGCPNetworkPeering(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t); acc.PreCheckPeeringEnvGCP(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigGCPWithNetworkPeering(gcpProjectID, gcpRegion, projectID, providerName, gcpPeeringName, clusterName, gcpClusterRegion), @@ -1022,7 +1022,7 @@ func TestAccClusterRSCluster_withAzureAndContainerID(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t); acc.PreCheckPeeringEnvAzure(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAzureWithContainerID(projectID, clusterName, providerName, region, directoryID, subcrptionID, resourceGroupName, vNetName), @@ -1055,7 +1055,7 @@ func TestAccClusterRSCluster_withAWSAndContainerID(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAWSWithContainerID(awsAccessKey, awsSecretKey, projectID, clusterName, providerName, awsRegion, vpcCIDRBlock, awsAccountID), @@ -1085,7 +1085,7 @@ func TestAccClusterRSCluster_withGCPAndContainerID(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t); acc.PreCheckPeeringEnvGCP(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigGCPWithContainerID(gcpProjectID, gcpRegion, projectID, clusterName, providerName, gcpClusterRegion, gcpPeeringName), @@ -1124,7 +1124,7 @@ func TestAccClusterRSCluster_withAutoScalingAWS(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAWSWithAutoscaling(orgID, projectName, name, "true", "false", "true", "false", minSize, maxSize, instanceSize), @@ -1179,7 +1179,7 @@ func TestAccClusterRSCluster_importBasic(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAWS(orgID, projectName, clusterName, true, false), @@ -1209,7 +1209,7 @@ func TestAccClusterRSCluster_tenant(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigTenant(orgID, projectName, name, "M2", "2", dbMajorVersion), @@ -1249,7 +1249,7 @@ func TestAccClusterRSCluster_tenant_m5(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigTenant(orgID, projectName, name, "M5", "5", dbMajorVersion), @@ -1278,7 +1278,7 @@ func TestAccClusterRSCluster_basicGCPRegionNameWesternUS(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigGCPRegionName(orgID, projectName, clusterName, regionName), @@ -1304,7 +1304,7 @@ func TestAccClusterRSCluster_basicGCPRegionNameUSWest2(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigGCPRegionName(orgID, projectName, clusterName, regionName), @@ -1404,7 +1404,7 @@ func TestAccClusterRSCluster_RegionsConfig(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigRegions(orgID, projectName, clusterName, replications), @@ -1451,7 +1451,7 @@ func TestAccClusterRSCluster_basicAWS_UnpauseToPaused(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAWSPaused(orgID, projectName, name, true, false), @@ -1504,7 +1504,7 @@ func TestAccClusterRSCluster_basicAWS_PausedToUnpaused(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: testAccMongoDBAtlasClusterConfigAWSPaused(orgID, projectName, name, true, true), @@ -1550,7 +1550,7 @@ func TestAccClusterRSCluster_withDefaultBiConnectorAndAdvancedConfiguration_main resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { ExternalProviders: acc.ExternalProviders("1.11.0"), diff --git a/internal/service/onlinearchive/resource_online_archive_test.go b/internal/service/onlinearchive/resource_online_archive_test.go index 1b75c61fe4..cbbc19974e 100644 --- a/internal/service/onlinearchive/resource_online_archive_test.go +++ b/internal/service/onlinearchive/resource_online_archive_test.go @@ -33,7 +33,7 @@ func TestAccBackupRSOnlineArchive(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { // We need this step to pupulate the cluster with Sample Data @@ -133,7 +133,7 @@ func TestAccBackupRSOnlineArchiveBasic(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { // We need this step to pupulate the cluster with Sample Data @@ -184,7 +184,7 @@ func TestAccBackupRSOnlineArchiveWithProcessRegion(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { // We need this step to pupulate the cluster with Sample Data @@ -229,7 +229,7 @@ func TestAccBackupRSOnlineArchiveInvalidProcessRegion(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckClusterDestroy, + CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { Config: configWithDataProcessRegion(orgID, projectName, name, cloudProvider, "UNKNOWN"), diff --git a/internal/service/searchdeployment/resource_search_deployment_test.go b/internal/service/searchdeployment/resource_search_deployment_test.go index 6c13b9cfb7..747e37b602 100644 --- a/internal/service/searchdeployment/resource_search_deployment_test.go +++ b/internal/service/searchdeployment/resource_search_deployment_test.go @@ -137,7 +137,7 @@ func checkDestroy(state *terraform.State) error { if projectDestroyedErr := acc.CheckDestroyProject(state); projectDestroyedErr != nil { return projectDestroyedErr } - if clusterDestroyedErr := acc.CheckDestroyTeamAdvancedCluster(state); clusterDestroyedErr != nil { + if clusterDestroyedErr := acc.CheckDestroyCluster(state); clusterDestroyedErr != nil { return clusterDestroyedErr } for _, rs := range state.RootModule().Resources { diff --git a/internal/testutil/acc/advanced_cluster.go b/internal/testutil/acc/advanced_cluster.go index 24f1be40b6..14b8226cac 100644 --- a/internal/testutil/acc/advanced_cluster.go +++ b/internal/testutil/acc/advanced_cluster.go @@ -25,38 +25,21 @@ var ( } ) -func CheckClusterDestroy(s *terraform.State) error { +func CheckDestroyCluster(s *terraform.State) error { for _, rs := range s.RootModule().Resources { - if rs.Type != "mongodbatlas_cluster" { + if rs.Type != "mongodbatlas_cluster" && rs.Type != "mongodbatlas_advanced_cluster" { continue } - - // Try to find the cluster - _, _, err := Conn().Clusters.Get(context.Background(), rs.Primary.Attributes["project_id"], rs.Primary.Attributes["cluster_name"]) + projectID := rs.Primary.Attributes["project_id"] + clusterName := rs.Primary.Attributes["cluster_name"] + _, _, err := ConnV2().ClustersApi.GetCluster(context.Background(), projectID, clusterName).Execute() if err == nil { - return fmt.Errorf("cluster (%s:%s) still exists", rs.Primary.Attributes["cluster_name"], rs.Primary.ID) + return fmt.Errorf("cluster (%s:%s) still exists", clusterName, rs.Primary.ID) } } return nil } -func CheckDestroyTeamAdvancedCluster(s *terraform.State) error { - for _, rs := range s.RootModule().Resources { - if rs.Type != "mongodbatlas_advanced_cluster" { - continue - } - - // Try to find the cluster - _, _, err := ConnV2().ClustersApi.GetCluster(context.Background(), rs.Primary.Attributes["project_id"], rs.Primary.Attributes["cluster_name"]).Execute() - - if err == nil { - return fmt.Errorf("cluster (%s:%s) still exists", rs.Primary.Attributes["cluster_name"], rs.Primary.ID) - } - } - - return nil -} - func ConfigClusterGlobal(resourceName, orgID, projectName, name, backupEnabled string) string { return fmt.Sprintf(` From 5f09abf73ee2005b52116e54d99b7e810000e5e5 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 08:21:52 +0100 Subject: [PATCH 08/52] acc.SkipInUnitTest in atlas_user ds --- internal/service/atlasuser/data_source_atlas_user_test.go | 8 ++------ .../service/atlasuser/data_source_atlas_users_test.go | 4 +--- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/internal/service/atlasuser/data_source_atlas_user_test.go b/internal/service/atlasuser/data_source_atlas_user_test.go index f3346e802f..219d05bc50 100644 --- a/internal/service/atlasuser/data_source_atlas_user_test.go +++ b/internal/service/atlasuser/data_source_atlas_user_test.go @@ -14,9 +14,7 @@ import ( ) func TestAccConfigDSAtlasUser_ByUserID(t *testing.T) { - if os.Getenv("TF_ACC") == "" { // needed while fetchUser is called from the test - t.Skip() - } + acc.SkipInUnitTest(t) // needed while fetchUser is called from the test var ( dataSourceName = "data.mongodbatlas_atlas_user.test" userID = os.Getenv("MONGODB_ATLAS_PROJECT_OWNER_ID") @@ -37,9 +35,7 @@ func TestAccConfigDSAtlasUser_ByUserID(t *testing.T) { } func TestAccConfigDSAtlasUser_ByUsername(t *testing.T) { - if os.Getenv("TF_ACC") == "" { // needed while fetchUserByUsername is called from the test - t.Skip() - } + acc.SkipInUnitTest(t) // needed while fetchUserByUsername is called from the test var ( dataSourceName = "data.mongodbatlas_atlas_user.test" username = os.Getenv("MONGODB_ATLAS_USERNAME") diff --git a/internal/service/atlasuser/data_source_atlas_users_test.go b/internal/service/atlasuser/data_source_atlas_users_test.go index 28deea0fba..9bb48758aa 100644 --- a/internal/service/atlasuser/data_source_atlas_users_test.go +++ b/internal/service/atlasuser/data_source_atlas_users_test.go @@ -16,9 +16,7 @@ import ( ) func TestAccConfigDSAtlasUsers_ByOrgID(t *testing.T) { - if os.Getenv("TF_ACC") == "" { // needed while fetchOrgUsers is called from the test - t.Skip() - } + acc.SkipInUnitTest(t) // needed while fetchOrgUsers is called from the test var ( dataSourceName = "data.mongodbatlas_atlas_users.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") From 387ce06c1fc1a53bb45a274a3a9c619e41662063 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 08:38:47 +0100 Subject: [PATCH 09/52] remove unneeded testAccCheckMongoDBAtlasAdvancedClusterAttributes --- ...esource_advanced_cluster_migration_test.go | 2 - .../resource_advanced_cluster_test.go | 49 +++++-------------- 2 files changed, 13 insertions(+), 38 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go index c070d459d5..19f38dfeae 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go @@ -31,7 +31,6 @@ func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { Config: config, Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "true"), @@ -64,7 +63,6 @@ func TestAccMigrationAdvancedClusterRS_multiCloud(t *testing.T) { Config: config, Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index f41f805f2c..45e2065a0c 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -38,7 +38,6 @@ func TestAccClusterAdvancedCluster_basic(t *testing.T) { Config: configTenant(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -78,7 +77,6 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { Config: configTenant(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -96,7 +94,6 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { Config: configTenant(orgID, projectName, rNameUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -140,7 +137,6 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { Config: configSingleProvider(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "true"), @@ -154,7 +150,6 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { Config: configMultiCloud(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), @@ -195,7 +190,6 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { Config: configMultiCloud(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), @@ -211,7 +205,6 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { Config: configMultiCloud(orgID, projectName, rNameUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), @@ -254,7 +247,6 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { Config: configMultiCloudSharded(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -265,7 +257,6 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { Config: configMultiCloudSharded(orgID, projectName, rNameUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -304,7 +295,6 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { Config: configSingleProviderPaused(orgID, projectName, rName, false, instanceSize), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -316,7 +306,6 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { Config: configSingleProviderPaused(orgID, projectName, rName, true, instanceSize), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -359,7 +348,6 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { Config: configSingleProviderPaused(orgID, projectName, rName, true, instanceSize), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -371,7 +359,6 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { Config: configSingleProviderPaused(orgID, projectName, rName, false, instanceSize), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -443,7 +430,7 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { Config: configAdvanced(orgID, projectName, rName, processArgs), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.minimum_enabled_tls_protocol", "TLS1_1"), @@ -462,7 +449,7 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { Config: configAdvanced(orgID, projectName, rNameUpdated, processArgsUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), + resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.minimum_enabled_tls_protocol", "TLS1_2"), @@ -522,7 +509,7 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { Config: configAdvancedDefaultWrite(orgID, projectName, rName, processArgs), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_read_concern", "available"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_write_concern", "1"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), @@ -538,7 +525,7 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { Config: configAdvancedDefaultWrite(orgID, projectName, rNameUpdated, processArgsUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), + resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_read_concern", "available"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_write_concern", "majority"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), @@ -582,7 +569,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. Config: configReplicationSpecsAutoScaling(orgID, projectName, rName, autoScaling), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), testAccCheckMongoDBAtlasAdvancedClusterScaling(&cluster, *autoScaling.Compute.Enabled), ), @@ -591,7 +578,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. Config: configReplicationSpecsAutoScaling(orgID, projectName, rNameUpdated, autoScalingUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), + resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), testAccCheckMongoDBAtlasAdvancedClusterScaling(&cluster, *autoScalingUpdated.Compute.Enabled), ), @@ -628,7 +615,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t Config: configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, rName, autoScaling), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), testAccCheckMongoDBAtlasAdvancedClusterAnalyticsScaling(&cluster, *autoScaling.Compute.Enabled), ), @@ -637,7 +624,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t Config: configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, rNameUpdated, autoScalingUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rNameUpdated), + resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), testAccCheckMongoDBAtlasAdvancedClusterAnalyticsScaling(&cluster, *autoScalingUpdated.Compute.Enabled), ), @@ -667,7 +654,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes Config: configMultiZoneWithShards(orgID, projectName, rName, numShards, numShards), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.num_shards", "1"), resource.TestCheckResourceAttr(resourceName, "replication_specs.1.num_shards", "1"), ), @@ -676,7 +663,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes Config: configMultiZoneWithShards(orgID, projectName, rName, numShardsUpdated, numShards), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.num_shards", "2"), resource.TestCheckResourceAttr(resourceName, "replication_specs.1.num_shards", "1"), ), @@ -706,7 +693,7 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { Config: configWithTags(orgID, projectName, rName, []matlas.Tag{}), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "tags.#", "0"), @@ -727,7 +714,7 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { }), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "tags.#", "2"), @@ -750,7 +737,7 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { }), Check: resource.ComposeTestCheckFunc( checkExists(resourceName, &cluster), - testAccCheckMongoDBAtlasAdvancedClusterAttributes(&cluster, rName), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "tags.#", "1"), @@ -784,16 +771,6 @@ func checkExists(resourceName string, cluster *matlas.AdvancedCluster) resource. } } -func testAccCheckMongoDBAtlasAdvancedClusterAttributes(cluster *matlas.AdvancedCluster, name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - if cluster.Name != name { - return fmt.Errorf("bad name: %s", cluster.Name) - } - - return nil - } -} - func testAccCheckMongoDBAtlasAdvancedClusterScaling(cluster *matlas.AdvancedCluster, computeEnabled bool) resource.TestCheckFunc { return func(s *terraform.State) error { if *cluster.ReplicationSpecs[0].RegionConfigs[0].AutoScaling.Compute.Enabled != computeEnabled { From 1c0099de7ddecd361676d18f43411c05a61bbbf2 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 08:51:28 +0100 Subject: [PATCH 10/52] refactor testAccCheckMongoDBAtlasAdvancedClusterScaling and testAccCheckMongoDBAtlasAdvancedClusterAnalyticsScaling --- .../resource_advanced_cluster_test.go | 28 +++---------------- 1 file changed, 4 insertions(+), 24 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 45e2065a0c..5ff4edf51a 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -571,7 +571,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. checkExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), - testAccCheckMongoDBAtlasAdvancedClusterScaling(&cluster, *autoScaling.Compute.Enabled), + resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.auto_scaling.0.compute_enabled", "false"), ), }, { @@ -580,7 +580,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. checkExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), - testAccCheckMongoDBAtlasAdvancedClusterScaling(&cluster, *autoScalingUpdated.Compute.Enabled), + resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.auto_scaling.0.compute_enabled", "true"), ), }, }, @@ -617,7 +617,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t checkExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), - testAccCheckMongoDBAtlasAdvancedClusterAnalyticsScaling(&cluster, *autoScaling.Compute.Enabled), + resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.analytics_auto_scaling.0.compute_enabled", "false"), ), }, { @@ -626,7 +626,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t checkExists(resourceName, &cluster), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), - testAccCheckMongoDBAtlasAdvancedClusterAnalyticsScaling(&cluster, *autoScalingUpdated.Compute.Enabled), + resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.analytics_auto_scaling.0.compute_enabled", "true"), ), }, }, @@ -771,26 +771,6 @@ func checkExists(resourceName string, cluster *matlas.AdvancedCluster) resource. } } -func testAccCheckMongoDBAtlasAdvancedClusterScaling(cluster *matlas.AdvancedCluster, computeEnabled bool) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *cluster.ReplicationSpecs[0].RegionConfigs[0].AutoScaling.Compute.Enabled != computeEnabled { - return fmt.Errorf("compute_enabled: %d", cluster.ReplicationSpecs[0].RegionConfigs[0].AutoScaling.Compute.Enabled) - } - - return nil - } -} - -func testAccCheckMongoDBAtlasAdvancedClusterAnalyticsScaling(cluster *matlas.AdvancedCluster, computeEnabled bool) resource.TestCheckFunc { - return func(s *terraform.State) error { - if *cluster.ReplicationSpecs[0].RegionConfigs[0].AnalyticsAutoScaling.Compute.Enabled != computeEnabled { - return fmt.Errorf("compute_enabled: %d", cluster.ReplicationSpecs[0].RegionConfigs[0].AnalyticsAutoScaling.Compute.Enabled) - } - - return nil - } -} - func configTenant(orgID, projectName, name string) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { From b5585704e01bf17d6e47abcc9a11eb5cebf8d84a Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 08:57:08 +0100 Subject: [PATCH 11/52] refactor checkExists --- ...esource_advanced_cluster_migration_test.go | 7 +- .../resource_advanced_cluster_test.go | 72 ++++++++----------- 2 files changed, 30 insertions(+), 49 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go index 19f38dfeae..224a8fd533 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go @@ -8,13 +8,11 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" - matlas "go.mongodb.org/atlas/mongodbatlas" ) func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") @@ -30,7 +28,7 @@ func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { ExternalProviders: mig.ExternalProviders(), Config: config, Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "true"), @@ -46,7 +44,6 @@ func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { func TestAccMigrationAdvancedClusterRS_multiCloud(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") @@ -62,7 +59,7 @@ func TestAccMigrationAdvancedClusterRS_multiCloud(t *testing.T) { ExternalProviders: mig.ExternalProviders(), Config: config, Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 5ff4edf51a..234a51feeb 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -3,7 +3,6 @@ package advancedcluster_test import ( "context" "fmt" - "log" "os" "regexp" "testing" @@ -20,7 +19,6 @@ import ( func TestAccClusterAdvancedCluster_basic(t *testing.T) { // TEMPORARY: to delete, based on TestAccClusterAdvancedCluster_basicTenant var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" dataSourceName = "data.mongodbatlas_advanced_cluster.test" dataSourceClustersName = "data.mongodbatlas_advanced_clusters.test" @@ -37,7 +35,7 @@ func TestAccClusterAdvancedCluster_basic(t *testing.T) { { Config: configTenant(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -58,7 +56,6 @@ func TestAccClusterAdvancedCluster_basic(t *testing.T) { func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" dataSourceName = "data.mongodbatlas_advanced_cluster.test" dataSourceClustersName = "data.mongodbatlas_advanced_clusters.test" @@ -76,7 +73,7 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { { Config: configTenant(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -93,7 +90,7 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { { Config: configTenant(orgID, projectName, rNameUpdated), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -120,7 +117,6 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" dataSourceName = fmt.Sprintf("data.%s", resourceName) orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") @@ -136,7 +132,7 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { { Config: configSingleProvider(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "true"), @@ -149,7 +145,7 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { { Config: configMultiCloud(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), @@ -171,7 +167,6 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" dataSourceName = "data.mongodbatlas_advanced_cluster.test" dataSourceClustersName = "data.mongodbatlas_advanced_clusters.test" @@ -189,7 +184,7 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { { Config: configMultiCloud(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), @@ -204,7 +199,7 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { { Config: configMultiCloud(orgID, projectName, rNameUpdated), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), @@ -230,7 +225,6 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") @@ -246,7 +240,7 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { { Config: configMultiCloudSharded(orgID, projectName, rName), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -256,7 +250,7 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { { Config: configMultiCloudSharded(orgID, projectName, rNameUpdated), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -277,7 +271,6 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") @@ -294,7 +287,7 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { { Config: configSingleProviderPaused(orgID, projectName, rName, false, instanceSize), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -305,7 +298,7 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { { Config: configSingleProviderPaused(orgID, projectName, rName, true, instanceSize), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -331,7 +324,6 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") @@ -347,7 +339,7 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { { Config: configSingleProviderPaused(orgID, projectName, rName, true, instanceSize), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -358,7 +350,7 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { { Config: configSingleProviderPaused(orgID, projectName, rName, false, instanceSize), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -387,7 +379,6 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" dataSourceName = "data.mongodbatlas_advanced_cluster.test" dataSourceNameClusters = "data.mongodbatlas_advanced_clusters.test" @@ -429,7 +420,7 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { { Config: configAdvanced(orgID, projectName, rName, processArgs), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), @@ -448,7 +439,7 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { { Config: configAdvanced(orgID, projectName, rNameUpdated, processArgsUpdated), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), @@ -471,7 +462,6 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") @@ -508,7 +498,7 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { { Config: configAdvancedDefaultWrite(orgID, projectName, rName, processArgs), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_read_concern", "available"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_write_concern", "1"), @@ -524,7 +514,7 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { { Config: configAdvancedDefaultWrite(orgID, projectName, rNameUpdated, processArgsUpdated), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_read_concern", "available"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_write_concern", "majority"), @@ -544,7 +534,6 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") @@ -568,7 +557,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. { Config: configReplicationSpecsAutoScaling(orgID, projectName, rName, autoScaling), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.auto_scaling.0.compute_enabled", "false"), @@ -577,7 +566,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. { Config: configReplicationSpecsAutoScaling(orgID, projectName, rNameUpdated, autoScalingUpdated), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.auto_scaling.0.compute_enabled", "true"), @@ -590,7 +579,6 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") @@ -614,7 +602,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t { Config: configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, rName, autoScaling), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.analytics_auto_scaling.0.compute_enabled", "false"), @@ -623,7 +611,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t { Config: configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, rNameUpdated, autoScalingUpdated), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.analytics_auto_scaling.0.compute_enabled", "true"), @@ -636,7 +624,6 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") @@ -653,7 +640,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes { Config: configMultiZoneWithShards(orgID, projectName, rName, numShards, numShards), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.num_shards", "1"), resource.TestCheckResourceAttr(resourceName, "replication_specs.1.num_shards", "1"), @@ -662,7 +649,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes { Config: configMultiZoneWithShards(orgID, projectName, rName, numShardsUpdated, numShards), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.num_shards", "2"), resource.TestCheckResourceAttr(resourceName, "replication_specs.1.num_shards", "1"), @@ -675,7 +662,6 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes func TestAccClusterAdvancedCluster_withTags(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - cluster matlas.AdvancedCluster resourceName = "mongodbatlas_advanced_cluster.test" dataSourceName = "data.mongodbatlas_advanced_cluster.test" dataSourceClustersName = "data.mongodbatlas_advanced_clusters.test" @@ -692,7 +678,7 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { { Config: configWithTags(orgID, projectName, rName, []matlas.Tag{}), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -713,7 +699,7 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { }, }), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -736,7 +722,7 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { }, }), Check: resource.ComposeTestCheckFunc( - checkExists(resourceName, &cluster), + checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -752,7 +738,7 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { }) } -func checkExists(resourceName string, cluster *matlas.AdvancedCluster) resource.TestCheckFunc { +func checkExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { @@ -762,9 +748,7 @@ func checkExists(resourceName string, cluster *matlas.AdvancedCluster) resource. return fmt.Errorf("no ID is set") } ids := conversion.DecodeStateID(rs.Primary.ID) - log.Printf("[DEBUG] projectID: %s, name %s", ids["project_id"], ids["cluster_name"]) - if clusterResp, _, err := acc.Conn().AdvancedClusters.Get(context.Background(), ids["project_id"], ids["cluster_name"]); err == nil { - *cluster = *clusterResp + if _, _, err := acc.ConnV2().ClustersApi.GetCluster(context.Background(), ids["project_id"], ids["cluster_name"]).Execute(); err == nil { return nil } return fmt.Errorf("cluster(%s:%s) does not exist", rs.Primary.Attributes["project_id"], rs.Primary.ID) From 0de9b7e65337f8b225edb1ba5e43e621e806a0b6 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 09:25:39 +0100 Subject: [PATCH 12/52] import --- .../advancedcluster/resource_advanced_cluster.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index a154ec887e..49a1b2e283 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -795,30 +795,30 @@ func resourceDelete(ctx context.Context, d *schema.ResourceData, meta any) diag. } func resourceImport(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { - conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID, name, err := splitSClusterAdvancedImportID(d.Id()) if err != nil { return nil, err } - u, _, err := conn.AdvancedClusters.Get(ctx, *projectID, *name) + cluster, _, err := connV2.ClustersApi.GetCluster(ctx, *projectID, *name).Execute() if err != nil { return nil, fmt.Errorf("couldn't import cluster %s in project %s, error: %s", *name, *projectID, err) } - if err := d.Set("project_id", u.GroupID); err != nil { - log.Printf(ErrorClusterAdvancedSetting, "project_id", u.ID, err) + if err := d.Set("project_id", cluster.GetGroupId()); err != nil { + log.Printf(ErrorClusterAdvancedSetting, "project_id", cluster.GetId(), err) } - if err := d.Set("name", u.Name); err != nil { - log.Printf(ErrorClusterAdvancedSetting, "name", u.ID, err) + if err := d.Set("name", cluster.GetName()); err != nil { + log.Printf(ErrorClusterAdvancedSetting, "name", cluster.GetId(), err) } d.SetId(conversion.EncodeStateID(map[string]string{ - "cluster_id": u.ID, + "cluster_id": cluster.GetId(), "project_id": *projectID, - "cluster_name": u.Name, + "cluster_name": cluster.GetName(), })) return []*schema.ResourceData{d}, nil From 8c0dd506b8b007e004b8bae6afec84c65671e936 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 09:26:39 +0100 Subject: [PATCH 13/52] TEMPORARY only run advanced cluster tests --- .github/workflows/acceptance-tests-runner.yml | 8 ++++---- .github/workflows/migration-tests.yml | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/acceptance-tests-runner.yml b/.github/workflows/acceptance-tests-runner.yml index 938780945f..1b28dc8b5c 100644 --- a/.github/workflows/acceptance-tests-runner.yml +++ b/.github/workflows/acceptance-tests-runner.yml @@ -123,15 +123,15 @@ jobs: outputs: cluster_outage_simulation: ${{ steps.filter.outputs.cluster_outage_simulation == 'true' || env.mustTrigger == 'true' }} advanced_cluster: ${{ steps.filter.outputs.advanced_cluster == 'true' || env.mustTrigger == 'true' }} - cluster: ${{ steps.filter.outputs.cluster == 'true' || env.mustTrigger == 'true' }} - search_deployment: ${{ steps.filter.outputs.search_deployment == 'true' || env.mustTrigger == 'true' }} + cluster: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + search_deployment: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE stream: ${{ steps.filter.outputs.stream == 'true' || env.mustTrigger == 'true' }} generic: ${{ steps.filter.outputs.generic == 'true' || env.mustTrigger == 'true' }} - backup: ${{ steps.filter.outputs.backup == 'true' || env.mustTrigger == 'true' }} + backup: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE project: ${{ steps.filter.outputs.project == 'true' || env.mustTrigger == 'true' }} serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} network: ${{ steps.filter.outputs.network == 'true' || env.mustTrigger == 'true' }} - config: ${{ steps.filter.outputs.config == 'true' || env.mustTrigger == 'true' }} + config: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE assume_role: ${{ steps.filter.outputs.assume_role == 'true' || env.mustTrigger == 'true' }} event_trigger: ${{ steps.filter.outputs.event_trigger == 'true' || env.mustTrigger == 'true' }} search_index: ${{ steps.filter.outputs.search_index == 'true' || env.mustTrigger == 'true' }} diff --git a/.github/workflows/migration-tests.yml b/.github/workflows/migration-tests.yml index a93b4ed873..27b9d3cc29 100644 --- a/.github/workflows/migration-tests.yml +++ b/.github/workflows/migration-tests.yml @@ -55,19 +55,19 @@ jobs: mustTrigger: ${{ github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.test_group == '') }} outputs: project: ${{ steps.filter.outputs.project == 'true' || env.mustTrigger == 'true' }} - config: ${{ steps.filter.outputs.config == 'true' || env.mustTrigger == 'true' }} + config: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE advanced_cluster: ${{ steps.filter.outputs.advanced_cluster == 'true' || env.mustTrigger == 'true' }} - backup: ${{ steps.filter.outputs.backup == 'true' || env.mustTrigger == 'true' }} + backup: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE stream: ${{ steps.filter.outputs.stream == 'true' || env.mustTrigger == 'true' }} federated: ${{ steps.filter.outputs.federated == 'true' || env.mustTrigger == 'true' }} - search_deployment: ${{ steps.filter.outputs.search_deployment == 'true' || env.mustTrigger == 'true' }} + search_deployment: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE generic: ${{ steps.filter.outputs.generic == 'true' || env.mustTrigger == 'true' }} network: ${{ steps.filter.outputs.network == 'true' || env.mustTrigger == 'true' }} encryption: ${{ steps.filter.outputs.encryption == 'true' || env.mustTrigger == 'true' }} serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} data_lake: ${{ steps.filter.outputs.data_lake == 'true' || env.mustTrigger == 'true' }} cluster_outage_simulation: ${{ steps.filter.outputs.cluster_outage_simulation == 'true' || env.mustTrigger == 'true' }} - cluster: ${{ steps.filter.outputs.cluster == 'true' || env.mustTrigger == 'true' }} + cluster: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 - uses: dorny/paths-filter@0bc4621a3135347011ad047f9ecf449bf72ce2bd From bb2c153adea6d325c338743ab617658973ca826e Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 09:37:51 +0100 Subject: [PATCH 14/52] add new mig test --- ...esource_advanced_cluster_migration_test.go | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go index 224a8fd533..f90ca4c06a 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go @@ -10,7 +10,37 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" ) -func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { +func TestAccMigrationAdvancedCluster_basic(t *testing.T) { + // TEMPORARY: to delete, based on TestAccClusterAdvancedCluster_basicTenant + var ( + resourceName = "mongodbatlas_advanced_cluster.test" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acctest.RandomWithPrefix("test-acc") + rName = acctest.RandomWithPrefix("test-acc") + config = configTenant(orgID, projectName, rName) + ) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acc.PreCheckBasic(t) }, + CheckDestroy: acc.CheckDestroyCluster, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + checkExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "project_id"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), + resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), + resource.TestCheckResourceAttrSet(resourceName, "termination_protection_enabled"), + ), + }, + mig.TestStep(config), + }, + }) +} + +func TestAccMigrationAdvancedCluster_singleAWSProvider(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( resourceName = "mongodbatlas_advanced_cluster.test" @@ -41,7 +71,7 @@ func TestAccMigrationAdvancedClusterRS_singleAWSProvider(t *testing.T) { }) } -func TestAccMigrationAdvancedClusterRS_multiCloud(t *testing.T) { +func TestAccMigrationAdvancedCluster_multiCloud(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( resourceName = "mongodbatlas_advanced_cluster.test" From 7940d801a48f677477d4d9fe90adc1a0ed59ac8e Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 09:43:52 +0100 Subject: [PATCH 15/52] extract resource and ds names in tests --- ...esource_advanced_cluster_migration_test.go | 27 ++-- .../resource_advanced_cluster_test.go | 127 ++++++++---------- 2 files changed, 67 insertions(+), 87 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go index f90ca4c06a..b817ecfa5b 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go @@ -13,11 +13,10 @@ import ( func TestAccMigrationAdvancedCluster_basic(t *testing.T) { // TEMPORARY: to delete, based on TestAccClusterAdvancedCluster_basicTenant var ( - resourceName = "mongodbatlas_advanced_cluster.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - config = configTenant(orgID, projectName, rName) + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acctest.RandomWithPrefix("test-acc") + rName = acctest.RandomWithPrefix("test-acc") + config = configTenant(orgID, projectName, rName) ) resource.ParallelTest(t, resource.TestCase{ @@ -43,11 +42,10 @@ func TestAccMigrationAdvancedCluster_basic(t *testing.T) { func TestAccMigrationAdvancedCluster_singleAWSProvider(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - config = configSingleProvider(orgID, projectName, rName) + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acctest.RandomWithPrefix("test-acc") + rName = acctest.RandomWithPrefix("test-acc") + config = configSingleProvider(orgID, projectName, rName) ) resource.ParallelTest(t, resource.TestCase{ @@ -74,11 +72,10 @@ func TestAccMigrationAdvancedCluster_singleAWSProvider(t *testing.T) { func TestAccMigrationAdvancedCluster_multiCloud(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - config = configMultiCloud(orgID, projectName, rName) + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acctest.RandomWithPrefix("test-acc") + rName = acctest.RandomWithPrefix("test-acc") + config = configMultiCloud(orgID, projectName, rName) ) resource.ParallelTest(t, resource.TestCase{ diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 234a51feeb..c1ad605487 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -16,15 +16,18 @@ import ( matlas "go.mongodb.org/atlas/mongodbatlas" ) +const ( + resourceName = "mongodbatlas_advanced_cluster.test" + dataSourceName = "data.mongodbatlas_advanced_cluster.test" + dataSourcePluralName = "data.mongodbatlas_advanced_clusters.test" +) + func TestAccClusterAdvancedCluster_basic(t *testing.T) { // TEMPORARY: to delete, based on TestAccClusterAdvancedCluster_basicTenant var ( - resourceName = "mongodbatlas_advanced_cluster.test" - dataSourceName = "data.mongodbatlas_advanced_cluster.test" - dataSourceClustersName = "data.mongodbatlas_advanced_clusters.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acctest.RandomWithPrefix("test-acc") + rName = acctest.RandomWithPrefix("test-acc") ) resource.ParallelTest(t, resource.TestCase{ @@ -43,10 +46,10 @@ func TestAccClusterAdvancedCluster_basic(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "termination_protection_enabled"), resource.TestCheckResourceAttr(dataSourceName, "name", rName), resource.TestCheckResourceAttr(dataSourceName, "termination_protection_enabled", "false"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.replication_specs.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.name"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.termination_protection_enabled"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.termination_protection_enabled"), ), }, }, @@ -56,13 +59,10 @@ func TestAccClusterAdvancedCluster_basic(t *testing.T) { func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" - dataSourceName = "data.mongodbatlas_advanced_cluster.test" - dataSourceClustersName = "data.mongodbatlas_advanced_clusters.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - rNameUpdated = acctest.RandomWithPrefix("test-acc") + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acctest.RandomWithPrefix("test-acc") + rName = acctest.RandomWithPrefix("test-acc") + rNameUpdated = acctest.RandomWithPrefix("test-acc") ) resource.ParallelTest(t, resource.TestCase{ @@ -81,10 +81,10 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "termination_protection_enabled"), resource.TestCheckResourceAttr(dataSourceName, "name", rName), resource.TestCheckResourceAttr(dataSourceName, "termination_protection_enabled", "false"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.replication_specs.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.name"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.termination_protection_enabled"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.termination_protection_enabled"), ), }, { @@ -98,10 +98,10 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "labels.#", "0"), resource.TestCheckResourceAttr(dataSourceName, "name", rNameUpdated), resource.TestCheckResourceAttr(dataSourceName, "termination_protection_enabled", "false"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.replication_specs.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.name"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.termination_protection_enabled"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.termination_protection_enabled"), ), }, { @@ -117,7 +117,6 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" dataSourceName = fmt.Sprintf("data.%s", resourceName) orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") @@ -167,13 +166,10 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" - dataSourceName = "data.mongodbatlas_advanced_cluster.test" - dataSourceClustersName = "data.mongodbatlas_advanced_clusters.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - rNameUpdated = acctest.RandomWithPrefix("test-acc") + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acctest.RandomWithPrefix("test-acc") + rName = acctest.RandomWithPrefix("test-acc") + rNameUpdated = acctest.RandomWithPrefix("test-acc") ) resource.ParallelTest(t, resource.TestCase{ @@ -190,9 +186,9 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.replication_specs.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.name"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), resource.TestCheckResourceAttr(dataSourceName, "name", rName), ), }, @@ -205,9 +201,9 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.replication_specs.#"), - resource.TestCheckResourceAttrSet(dataSourceClustersName, "results.0.name"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), resource.TestCheckResourceAttr(dataSourceName, "name", rNameUpdated), ), }, @@ -225,7 +221,6 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") rName = acctest.RandomWithPrefix("test-acc") @@ -271,7 +266,6 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") rName = acctest.RandomWithPrefix("test-acc") @@ -324,7 +318,6 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") rName = acctest.RandomWithPrefix("test-acc") @@ -379,14 +372,11 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" - dataSourceName = "data.mongodbatlas_advanced_cluster.test" - dataSourceNameClusters = "data.mongodbatlas_advanced_clusters.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - rNameUpdated = acctest.RandomWithPrefix("test-acc") - processArgs = &matlas.ProcessArgs{ + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acctest.RandomWithPrefix("test-acc") + rName = acctest.RandomWithPrefix("test-acc") + rNameUpdated = acctest.RandomWithPrefix("test-acc") + processArgs = &matlas.ProcessArgs{ DefaultReadConcern: "available", DefaultWriteConcern: "1", FailIndexKeyTooLong: pointy.Bool(false), @@ -431,9 +421,9 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.sample_size_bi_connector", "110"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.transaction_lifetime_limit_seconds", "300"), resource.TestCheckResourceAttr(dataSourceName, "name", rName), - resource.TestCheckResourceAttrSet(dataSourceNameClusters, "results.#"), - resource.TestCheckResourceAttrSet(dataSourceNameClusters, "results.0.replication_specs.#"), - resource.TestCheckResourceAttrSet(dataSourceNameClusters, "results.0.name"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), ), }, { @@ -450,9 +440,9 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.sample_size_bi_connector", "110"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.transaction_lifetime_limit_seconds", "300"), resource.TestCheckResourceAttr(dataSourceName, "name", rNameUpdated), - resource.TestCheckResourceAttrSet(dataSourceNameClusters, "results.#"), - resource.TestCheckResourceAttrSet(dataSourceNameClusters, "results.0.replication_specs.#"), - resource.TestCheckResourceAttrSet(dataSourceNameClusters, "results.0.name"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), + resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), ), }, }, @@ -462,7 +452,6 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") rName = acctest.RandomWithPrefix("test-acc") @@ -534,7 +523,6 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") rName = acctest.RandomWithPrefix("test-acc") @@ -579,7 +567,6 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") rName = acctest.RandomWithPrefix("test-acc") @@ -624,7 +611,6 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acctest.RandomWithPrefix("test-acc") rName = acctest.RandomWithPrefix("test-acc") @@ -662,12 +648,9 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes func TestAccClusterAdvancedCluster_withTags(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - resourceName = "mongodbatlas_advanced_cluster.test" - dataSourceName = "data.mongodbatlas_advanced_cluster.test" - dataSourceClustersName = "data.mongodbatlas_advanced_clusters.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acctest.RandomWithPrefix("test-acc") + rName = acctest.RandomWithPrefix("test-acc") ) resource.ParallelTest(t, resource.TestCase{ @@ -684,7 +667,7 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "tags.#", "0"), resource.TestCheckResourceAttr(dataSourceName, "tags.#", "0"), - resource.TestCheckResourceAttr(dataSourceClustersName, "results.0.tags.#", "0"), + resource.TestCheckResourceAttr(dataSourcePluralName, "results.0.tags.#", "0"), ), }, { @@ -709,9 +692,9 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { resource.TestCheckResourceAttr(dataSourceName, "tags.#", "2"), resource.TestCheckTypeSetElemNestedAttrs(dataSourceName, "tags.*", acc.ClusterTagsMap1), resource.TestCheckTypeSetElemNestedAttrs(dataSourceName, "tags.*", acc.ClusterTagsMap2), - resource.TestCheckResourceAttr(dataSourceClustersName, "results.0.tags.#", "2"), - resource.TestCheckTypeSetElemNestedAttrs(dataSourceClustersName, "results.0.tags.*", acc.ClusterTagsMap1), - resource.TestCheckTypeSetElemNestedAttrs(dataSourceClustersName, "results.0.tags.*", acc.ClusterTagsMap2), + resource.TestCheckResourceAttr(dataSourcePluralName, "results.0.tags.#", "2"), + resource.TestCheckTypeSetElemNestedAttrs(dataSourcePluralName, "results.0.tags.*", acc.ClusterTagsMap1), + resource.TestCheckTypeSetElemNestedAttrs(dataSourcePluralName, "results.0.tags.*", acc.ClusterTagsMap2), ), }, { @@ -730,8 +713,8 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tags.*", acc.ClusterTagsMap3), resource.TestCheckResourceAttr(dataSourceName, "tags.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(dataSourceName, "tags.*", acc.ClusterTagsMap3), - resource.TestCheckResourceAttr(dataSourceClustersName, "results.0.tags.#", "1"), - resource.TestCheckTypeSetElemNestedAttrs(dataSourceClustersName, "results.0.tags.*", acc.ClusterTagsMap3), + resource.TestCheckResourceAttr(dataSourcePluralName, "results.0.tags.#", "1"), + resource.TestCheckTypeSetElemNestedAttrs(dataSourcePluralName, "results.0.tags.*", acc.ClusterTagsMap3), ), }, }, From f62a76d5164393794b0ec16f17d650aec135a3d0 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 09:49:18 +0100 Subject: [PATCH 16/52] read & ds in new sdk still using some old sdk --- .../data_source_advanced_cluster.go | 56 +++++++++--------- .../resource_advanced_cluster.go | 57 +++++++++---------- 2 files changed, 53 insertions(+), 60 deletions(-) diff --git a/internal/service/advancedcluster/data_source_advanced_cluster.go b/internal/service/advancedcluster/data_source_advanced_cluster.go index 3f303dfce6..29a2c4eed7 100644 --- a/internal/service/advancedcluster/data_source_advanced_cluster.go +++ b/internal/service/advancedcluster/data_source_advanced_cluster.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/constant" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" ) @@ -230,77 +231,78 @@ func DataSource() *schema.Resource { } func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - // Get client connection. conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) clusterName := d.Get("name").(string) - cluster, resp, err := conn.AdvancedClusters.Get(ctx, projectID, clusterName) + cluster, resp, err := connV2.ClustersApi.GetCluster(ctx, projectID, clusterName).Execute() + clusterOld, _, _ := conn.AdvancedClusters.Get(ctx, projectID, clusterName) + if err != nil { if resp != nil && resp.StatusCode == http.StatusNotFound { return nil } - return diag.FromErr(fmt.Errorf(errorRead, clusterName, err)) } - if err := d.Set("backup_enabled", cluster.BackupEnabled); err != nil { + if err := d.Set("backup_enabled", cluster.GetBackupEnabled()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "backup_enabled", clusterName, err)) } - if err := d.Set("bi_connector_config", FlattenBiConnectorConfig(cluster.BiConnector)); err != nil { + if err := d.Set("bi_connector_config", FlattenBiConnectorConfig(clusterOld.BiConnector)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "bi_connector_config", clusterName, err)) } - if err := d.Set("cluster_type", cluster.ClusterType); err != nil { + if err := d.Set("cluster_type", cluster.GetClusterType()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "cluster_type", clusterName, err)) } - if err := d.Set("connection_strings", FlattenConnectionStrings(cluster.ConnectionStrings)); err != nil { + if err := d.Set("connection_strings", FlattenConnectionStrings(clusterOld.ConnectionStrings)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "connection_strings", clusterName, err)) } - if err := d.Set("create_date", cluster.CreateDate); err != nil { + if err := d.Set("create_date", conversion.TimePtrToStringPtr(cluster.CreateDate)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "create_date", clusterName, err)) } - if err := d.Set("disk_size_gb", cluster.DiskSizeGB); err != nil { + if err := d.Set("disk_size_gb", cluster.GetDiskSizeGB()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "disk_size_gb", clusterName, err)) } - if err := d.Set("encryption_at_rest_provider", cluster.EncryptionAtRestProvider); err != nil { + if err := d.Set("encryption_at_rest_provider", cluster.GetEncryptionAtRestProvider()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "encryption_at_rest_provider", clusterName, err)) } - if err := d.Set("labels", FlattenLabels(RemoveLabel(cluster.Labels, DefaultLabel))); err != nil { + if err := d.Set("labels", FlattenLabels(RemoveLabel(clusterOld.Labels, DefaultLabel))); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "labels", clusterName, err)) } - if err := d.Set("tags", FlattenTags(&cluster.Tags)); err != nil { + if err := d.Set("tags", FlattenTags(&clusterOld.Tags)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "tags", clusterName, err)) } - if err := d.Set("mongo_db_major_version", cluster.MongoDBMajorVersion); err != nil { + if err := d.Set("mongo_db_major_version", cluster.GetMongoDBMajorVersion()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "mongo_db_major_version", clusterName, err)) } - if err := d.Set("mongo_db_version", cluster.MongoDBVersion); err != nil { + if err := d.Set("mongo_db_version", cluster.GetMongoDBVersion()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "mongo_db_version", clusterName, err)) } - if err := d.Set("name", cluster.Name); err != nil { + if err := d.Set("name", cluster.GetName()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "name", clusterName, err)) } - if err := d.Set("paused", cluster.Paused); err != nil { + if err := d.Set("paused", cluster.GetPaused()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "paused", clusterName, err)) } - if err := d.Set("pit_enabled", cluster.PitEnabled); err != nil { + if err := d.Set("pit_enabled", cluster.GetPitEnabled()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "pit_enabled", clusterName, err)) } - replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, cluster.ReplicationSpecs, d.Get("replication_specs").(*schema.Set).List(), d, conn) + replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, clusterOld.ReplicationSpecs, d.Get("replication_specs").(*schema.Set).List(), d, conn) if err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "replication_specs", clusterName, err)) } @@ -309,33 +311,29 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "replication_specs", clusterName, err)) } - if err := d.Set("root_cert_type", cluster.RootCertType); err != nil { + if err := d.Set("root_cert_type", cluster.GetRootCertType()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "state_name", clusterName, err)) } - if err := d.Set("state_name", cluster.StateName); err != nil { + if err := d.Set("state_name", cluster.GetStateName()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "state_name", clusterName, err)) } - if err := d.Set("termination_protection_enabled", cluster.TerminationProtectionEnabled); err != nil { + if err := d.Set("termination_protection_enabled", cluster.GetTerminationProtectionEnabled()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "termination_protection_enabled", clusterName, err)) } - if err := d.Set("version_release_system", cluster.VersionReleaseSystem); err != nil { + if err := d.Set("version_release_system", cluster.GetVersionReleaseSystem()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "version_release_system", clusterName, err)) } - /* - Get the advaced configuration options and set up to the terraform state - */ - processArgs, _, err := conn.Clusters.GetProcessArgs(ctx, projectID, clusterName) + processArgsOld, _, err := conn.Clusters.GetProcessArgs(ctx, projectID, clusterName) if err != nil { return diag.FromErr(fmt.Errorf(ErrorAdvancedConfRead, clusterName, err)) } - if err := d.Set("advanced_configuration", FlattenProcessArgs(processArgs)); err != nil { + if err := d.Set("advanced_configuration", FlattenProcessArgs(processArgsOld)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "advanced_configuration", clusterName, err)) } - d.SetId(cluster.ID) - + d.SetId(cluster.GetId()) return nil } diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 49a1b2e283..ff9c83288d 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -477,13 +477,14 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. } func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - // Get client connection. conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) projectID := ids["project_id"] clusterName := ids["cluster_name"] - cluster, resp, err := conn.AdvancedClusters.Get(ctx, projectID, clusterName) + cluster, resp, err := connV2.ClustersApi.GetCluster(ctx, projectID, clusterName).Execute() + clusterOld, _, _ := conn.AdvancedClusters.Get(ctx, projectID, clusterName) if err != nil { if resp != nil && resp.StatusCode == http.StatusNotFound { d.SetId("") @@ -493,69 +494,67 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di return diag.FromErr(fmt.Errorf(errorRead, clusterName, err)) } - log.Printf("[DEBUG] GET ClusterAdvanced %+v", cluster) - - if err := d.Set("cluster_id", cluster.ID); err != nil { + if err := d.Set("cluster_id", cluster.GetId()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "cluster_id", clusterName, err)) } - if err := d.Set("backup_enabled", cluster.BackupEnabled); err != nil { + if err := d.Set("backup_enabled", cluster.GetBackupEnabled()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "backup_enabled", clusterName, err)) } - if err := d.Set("bi_connector_config", FlattenBiConnectorConfig(cluster.BiConnector)); err != nil { + if err := d.Set("bi_connector_config", FlattenBiConnectorConfig(clusterOld.BiConnector)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "bi_connector_config", clusterName, err)) } - if err := d.Set("cluster_type", cluster.ClusterType); err != nil { + if err := d.Set("cluster_type", cluster.GetClusterType()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "cluster_type", clusterName, err)) } - if err := d.Set("connection_strings", FlattenConnectionStrings(cluster.ConnectionStrings)); err != nil { + if err := d.Set("connection_strings", FlattenConnectionStrings(clusterOld.ConnectionStrings)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "connection_strings", clusterName, err)) } - if err := d.Set("create_date", cluster.CreateDate); err != nil { + if err := d.Set("create_date", conversion.TimePtrToStringPtr(cluster.CreateDate)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "create_date", clusterName, err)) } - if err := d.Set("disk_size_gb", cluster.DiskSizeGB); err != nil { + if err := d.Set("disk_size_gb", cluster.GetDiskSizeGB()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "disk_size_gb", clusterName, err)) } - if err := d.Set("encryption_at_rest_provider", cluster.EncryptionAtRestProvider); err != nil { + if err := d.Set("encryption_at_rest_provider", cluster.GetEncryptionAtRestProvider()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "encryption_at_rest_provider", clusterName, err)) } - if err := d.Set("labels", FlattenLabels(RemoveLabel(cluster.Labels, DefaultLabel))); err != nil { + if err := d.Set("labels", FlattenLabels(RemoveLabel(clusterOld.Labels, DefaultLabel))); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "labels", clusterName, err)) } - if err := d.Set("tags", FlattenTags(&cluster.Tags)); err != nil { + if err := d.Set("tags", FlattenTags(&clusterOld.Tags)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "tags", clusterName, err)) } - if err := d.Set("mongo_db_major_version", cluster.MongoDBMajorVersion); err != nil { + if err := d.Set("mongo_db_major_version", cluster.GetMongoDBMajorVersion()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "mongo_db_major_version", clusterName, err)) } - if err := d.Set("mongo_db_version", cluster.MongoDBVersion); err != nil { + if err := d.Set("mongo_db_version", cluster.GetMongoDBVersion()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "mongo_db_version", clusterName, err)) } - if err := d.Set("name", cluster.Name); err != nil { + if err := d.Set("name", cluster.GetName()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "name", clusterName, err)) } - if err := d.Set("paused", cluster.Paused); err != nil { + if err := d.Set("paused", cluster.GetPaused()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "paused", clusterName, err)) } - if err := d.Set("pit_enabled", cluster.PitEnabled); err != nil { + if err := d.Set("pit_enabled", cluster.GetPitEnabled()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "pit_enabled", clusterName, err)) } - replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, cluster.ReplicationSpecs, d.Get("replication_specs").([]any), d, conn) + replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, clusterOld.ReplicationSpecs, d.Get("replication_specs").([]any), d, conn) if err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "replication_specs", clusterName, err)) } @@ -564,38 +563,34 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "replication_specs", clusterName, err)) } - if err := d.Set("root_cert_type", cluster.RootCertType); err != nil { + if err := d.Set("root_cert_type", cluster.GetRootCertType()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "state_name", clusterName, err)) } - if err := d.Set("state_name", cluster.StateName); err != nil { + if err := d.Set("state_name", cluster.GetStateName()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "state_name", clusterName, err)) } - if err := d.Set("termination_protection_enabled", cluster.TerminationProtectionEnabled); err != nil { + if err := d.Set("termination_protection_enabled", cluster.GetTerminationProtectionEnabled()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "termination_protection_enabled", clusterName, err)) } - if err := d.Set("version_release_system", cluster.VersionReleaseSystem); err != nil { + if err := d.Set("version_release_system", cluster.GetVersionReleaseSystem()); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "version_release_system", clusterName, err)) } - if err := d.Set("accept_data_risks_and_force_replica_set_reconfig", cluster.AcceptDataRisksAndForceReplicaSetReconfig); err != nil { + if err := d.Set("accept_data_risks_and_force_replica_set_reconfig", conversion.TimePtrToStringPtr(cluster.AcceptDataRisksAndForceReplicaSetReconfig)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "accept_data_risks_and_force_replica_set_reconfig", clusterName, err)) } - /* - Get the advaced configuration options and set up to the terraform state - */ - processArgs, _, err := conn.Clusters.GetProcessArgs(ctx, projectID, clusterName) + processArgsOld, _, err := conn.Clusters.GetProcessArgs(ctx, projectID, clusterName) if err != nil { return diag.FromErr(fmt.Errorf(errorConfigRead, clusterName, err)) } - if err := d.Set("advanced_configuration", FlattenProcessArgs(processArgs)); err != nil { + if err := d.Set("advanced_configuration", FlattenProcessArgs(processArgsOld)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "advanced_configuration", clusterName, err)) } - return nil } From 924312b509b95da66b27da4743698de2799ffbe7 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 10:13:13 +0100 Subject: [PATCH 17/52] fix mig test --- .../resource_advanced_cluster_migration_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go index b817ecfa5b..0e3d5f71af 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go @@ -24,7 +24,8 @@ func TestAccMigrationAdvancedCluster_basic(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: config, + ExternalProviders: mig.ExternalProviders(), + Config: config, Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), From 07a8f83593d9fcc9e07eeae750f71f09c584313b Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 11:27:22 +0100 Subject: [PATCH 18/52] flattenProcessArgs --- .../common_advanced_cluster.go | 32 +++++++++++-------- .../data_source_advanced_cluster.go | 4 +-- .../data_source_advanced_clusters.go | 11 ++++--- .../resource_advanced_cluster.go | 4 +-- .../service/cluster/data_source_cluster.go | 2 +- .../service/cluster/data_source_clusters.go | 2 +- internal/service/cluster/resource_cluster.go | 20 +++++++++++- 7 files changed, 49 insertions(+), 26 deletions(-) diff --git a/internal/service/advancedcluster/common_advanced_cluster.go b/internal/service/advancedcluster/common_advanced_cluster.go index 87528f3049..1dbf30d034 100644 --- a/internal/service/advancedcluster/common_advanced_cluster.go +++ b/internal/service/advancedcluster/common_advanced_cluster.go @@ -16,6 +16,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mwielbut/pointy" "github.com/spf13/cast" + "go.mongodb.org/atlas-sdk/v20231115006/admin" matlas "go.mongodb.org/atlas/mongodbatlas" ) @@ -296,20 +297,23 @@ func ExpandTagSliceFromSetSchema(d *schema.ResourceData) []*matlas.Tag { return res } -func FlattenProcessArgs(p *matlas.ProcessArgs) []any { - return []any{ - map[string]any{ - "default_read_concern": p.DefaultReadConcern, - "default_write_concern": p.DefaultWriteConcern, - "fail_index_key_too_long": cast.ToBool(p.FailIndexKeyTooLong), - "javascript_enabled": cast.ToBool(p.JavascriptEnabled), - "minimum_enabled_tls_protocol": p.MinimumEnabledTLSProtocol, - "no_table_scan": cast.ToBool(p.NoTableScan), - "oplog_size_mb": p.OplogSizeMB, - "oplog_min_retention_hours": p.OplogMinRetentionHours, - "sample_size_bi_connector": p.SampleSizeBIConnector, - "sample_refresh_interval_bi_connector": p.SampleRefreshIntervalBIConnector, - "transaction_lifetime_limit_seconds": p.TransactionLifetimeLimitSeconds, +func flattenProcessArgs(p *admin.ClusterDescriptionProcessArgs) []map[string]any { + if p == nil { + return nil + } + return []map[string]any{ + { + "default_read_concern": p.GetDefaultReadConcern(), + "default_write_concern": p.GetDefaultWriteConcern(), + "fail_index_key_too_long": p.GetFailIndexKeyTooLong(), + "javascript_enabled": p.GetJavascriptEnabled(), + "minimum_enabled_tls_protocol": p.GetMinimumEnabledTlsProtocol(), + "no_table_scan": p.GetNoTableScan(), + "oplog_size_mb": p.GetOplogSizeMB(), + "oplog_min_retention_hours": p.GetOplogMinRetentionHours(), + "sample_size_bi_connector": p.GetSampleSizeBIConnector(), + "sample_refresh_interval_bi_connector": p.GetSampleRefreshIntervalBIConnector(), + "transaction_lifetime_limit_seconds": p.GetTransactionLifetimeLimitSeconds(), }, } } diff --git a/internal/service/advancedcluster/data_source_advanced_cluster.go b/internal/service/advancedcluster/data_source_advanced_cluster.go index 29a2c4eed7..ee27740799 100644 --- a/internal/service/advancedcluster/data_source_advanced_cluster.go +++ b/internal/service/advancedcluster/data_source_advanced_cluster.go @@ -325,12 +325,12 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "version_release_system", clusterName, err)) } - processArgsOld, _, err := conn.Clusters.GetProcessArgs(ctx, projectID, clusterName) + processArgs, _, err := connV2.ClustersApi.GetClusterAdvancedConfiguration(ctx, projectID, clusterName).Execute() if err != nil { return diag.FromErr(fmt.Errorf(ErrorAdvancedConfRead, clusterName, err)) } - if err := d.Set("advanced_configuration", FlattenProcessArgs(processArgsOld)); err != nil { + if err := d.Set("advanced_configuration", flattenProcessArgs(processArgs)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "advanced_configuration", clusterName, err)) } diff --git a/internal/service/advancedcluster/data_source_advanced_clusters.go b/internal/service/advancedcluster/data_source_advanced_clusters.go index 884d20f1e5..17565a90a4 100644 --- a/internal/service/advancedcluster/data_source_advanced_clusters.go +++ b/internal/service/advancedcluster/data_source_advanced_clusters.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/constant" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" + "go.mongodb.org/atlas-sdk/v20231115006/admin" matlas "go.mongodb.org/atlas/mongodbatlas" ) @@ -241,8 +242,8 @@ func PluralDataSource() *schema.Resource { } func dataSourcePluralRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - // Get client connection. conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) d.SetId(id.UniqueId()) @@ -255,18 +256,18 @@ func dataSourcePluralRead(ctx context.Context, d *schema.ResourceData, meta any) return diag.FromErr(fmt.Errorf("error reading advanced cluster list for project(%s): %s", projectID, err)) } - if err := d.Set("results", flattenAdvancedClusters(ctx, conn, clusters.Results, d)); err != nil { + if err := d.Set("results", flattenAdvancedClusters(ctx, conn, connV2, clusters.Results, d)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "results", d.Id(), err)) } return nil } -func flattenAdvancedClusters(ctx context.Context, conn *matlas.Client, clusters []*matlas.AdvancedCluster, d *schema.ResourceData) []map[string]any { +func flattenAdvancedClusters(ctx context.Context, conn *matlas.Client, connV2 *admin.APIClient, clusters []*matlas.AdvancedCluster, d *schema.ResourceData) []map[string]any { results := make([]map[string]any, 0) for i := range clusters { - processArgs, _, err := conn.Clusters.GetProcessArgs(ctx, clusters[i].GroupID, clusters[i].Name) + processArgs, _, err := connV2.ClustersApi.GetClusterAdvancedConfiguration(ctx, clusters[i].GroupID, clusters[i].Name).Execute() if err != nil { log.Printf("[WARN] Error setting `advanced_configuration` for the cluster(%s): %s", clusters[i].ID, err) } @@ -276,7 +277,7 @@ func flattenAdvancedClusters(ctx context.Context, conn *matlas.Client, clusters } result := map[string]any{ - "advanced_configuration": FlattenProcessArgs(processArgs), + "advanced_configuration": flattenProcessArgs(processArgs), "backup_enabled": clusters[i].BackupEnabled, "bi_connector_config": FlattenBiConnectorConfig(clusters[i].BiConnector), "cluster_type": clusters[i].ClusterType, diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index ff9c83288d..119de90f34 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -583,12 +583,12 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "accept_data_risks_and_force_replica_set_reconfig", clusterName, err)) } - processArgsOld, _, err := conn.Clusters.GetProcessArgs(ctx, projectID, clusterName) + processArgs, _, err := connV2.ClustersApi.GetClusterAdvancedConfiguration(ctx, projectID, clusterName).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorConfigRead, clusterName, err)) } - if err := d.Set("advanced_configuration", FlattenProcessArgs(processArgsOld)); err != nil { + if err := d.Set("advanced_configuration", flattenProcessArgs(processArgs)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "advanced_configuration", clusterName, err)) } return nil diff --git a/internal/service/cluster/data_source_cluster.go b/internal/service/cluster/data_source_cluster.go index 535326abdc..d09815af7c 100644 --- a/internal/service/cluster/data_source_cluster.go +++ b/internal/service/cluster/data_source_cluster.go @@ -475,7 +475,7 @@ func dataSourceMongoDBAtlasClusterRead(ctx context.Context, d *schema.ResourceDa return diag.FromErr(fmt.Errorf(advancedcluster.ErrorAdvancedConfRead, clusterName, err)) } - if err := d.Set("advanced_configuration", advancedcluster.FlattenProcessArgs(processArgs)); err != nil { + if err := d.Set("advanced_configuration", flattenProcessArgs(processArgs)); err != nil { return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "advanced_configuration", clusterName, err)) } diff --git a/internal/service/cluster/data_source_clusters.go b/internal/service/cluster/data_source_clusters.go index 8a4ad60c4d..a8b29b5bf8 100644 --- a/internal/service/cluster/data_source_clusters.go +++ b/internal/service/cluster/data_source_clusters.go @@ -372,7 +372,7 @@ func flattenClusters(ctx context.Context, d *schema.ResourceData, conn *matlas.C containerID = getContainerID(containers, &clusters[i]) } result := map[string]any{ - "advanced_configuration": advancedcluster.FlattenProcessArgs(processArgs), + "advanced_configuration": flattenProcessArgs(processArgs), "auto_scaling_compute_enabled": clusters[i].AutoScaling.Compute.Enabled, "auto_scaling_compute_scale_down_enabled": clusters[i].AutoScaling.Compute.ScaleDownEnabled, "auto_scaling_disk_gb_enabled": clusters[i].AutoScaling.DiskGBEnabled, diff --git a/internal/service/cluster/resource_cluster.go b/internal/service/cluster/resource_cluster.go index a6f73f5b82..1609f3b5a3 100644 --- a/internal/service/cluster/resource_cluster.go +++ b/internal/service/cluster/resource_cluster.go @@ -757,7 +757,7 @@ func resourceMongoDBAtlasClusterRead(ctx context.Context, d *schema.ResourceData return diag.FromErr(fmt.Errorf(advancedcluster.ErrorAdvancedConfRead, clusterName, err)) } - if err := d.Set("advanced_configuration", advancedcluster.FlattenProcessArgs(processArgs)); err != nil { + if err := d.Set("advanced_configuration", flattenProcessArgs(processArgs)); err != nil { return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "advanced_configuration", clusterName, err)) } @@ -1563,3 +1563,21 @@ func flattenPolicyItems(items []matlas.PolicyItem) []map[string]any { return policyItems } + +func flattenProcessArgs(p *matlas.ProcessArgs) []map[string]any { + return []map[string]any{ + { + "default_read_concern": p.DefaultReadConcern, + "default_write_concern": p.DefaultWriteConcern, + "fail_index_key_too_long": cast.ToBool(p.FailIndexKeyTooLong), + "javascript_enabled": cast.ToBool(p.JavascriptEnabled), + "minimum_enabled_tls_protocol": p.MinimumEnabledTLSProtocol, + "no_table_scan": cast.ToBool(p.NoTableScan), + "oplog_size_mb": p.OplogSizeMB, + "oplog_min_retention_hours": p.OplogMinRetentionHours, + "sample_size_bi_connector": p.SampleSizeBIConnector, + "sample_refresh_interval_bi_connector": p.SampleRefreshIntervalBIConnector, + "transaction_lifetime_limit_seconds": p.TransactionLifetimeLimitSeconds, + }, + } +} From edd51274de961c570648839cba5e0a218eeec19b Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 12:44:53 +0100 Subject: [PATCH 19/52] TEMPORARY don't run network tests --- .github/workflows/acceptance-tests-runner.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/acceptance-tests-runner.yml b/.github/workflows/acceptance-tests-runner.yml index 1b28dc8b5c..097f30e412 100644 --- a/.github/workflows/acceptance-tests-runner.yml +++ b/.github/workflows/acceptance-tests-runner.yml @@ -130,7 +130,7 @@ jobs: backup: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE project: ${{ steps.filter.outputs.project == 'true' || env.mustTrigger == 'true' }} serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} - network: ${{ steps.filter.outputs.network == 'true' || env.mustTrigger == 'true' }} + network: # TEMPORARY, WILL BE REVERTED BEFORE MERGE config: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE assume_role: ${{ steps.filter.outputs.assume_role == 'true' || env.mustTrigger == 'true' }} event_trigger: ${{ steps.filter.outputs.event_trigger == 'true' || env.mustTrigger == 'true' }} From b45ae6b250455eb616e48ded71cdabb92cbe27e3 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 12:46:19 +0100 Subject: [PATCH 20/52] split cluster and advanced cluster common methods that will diverge --- .../data_source_advanced_cluster.go | 8 +- .../data_source_advanced_clusters.go | 8 +- ...d_cluster.go => model_advanced_cluster.go} | 19 +- ...test.go => model_advanced_cluster_test.go} | 0 .../resource_advanced_cluster.go | 28 +- .../service/cluster/data_source_cluster.go | 8 +- .../service/cluster/data_source_clusters.go | 8 +- internal/service/cluster/model_cluster.go | 519 ++++++++++++++++++ internal/service/cluster/resource_cluster.go | 330 +---------- ...rce_private_endpoint_regional_mode_test.go | 3 - 10 files changed, 574 insertions(+), 357 deletions(-) rename internal/service/advancedcluster/{common_advanced_cluster.go => model_advanced_cluster.go} (96%) rename internal/service/advancedcluster/{common_advanced_cluster_test.go => model_advanced_cluster_test.go} (100%) create mode 100644 internal/service/cluster/model_cluster.go diff --git a/internal/service/advancedcluster/data_source_advanced_cluster.go b/internal/service/advancedcluster/data_source_advanced_cluster.go index ee27740799..366c744b0c 100644 --- a/internal/service/advancedcluster/data_source_advanced_cluster.go +++ b/internal/service/advancedcluster/data_source_advanced_cluster.go @@ -250,7 +250,7 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "backup_enabled", clusterName, err)) } - if err := d.Set("bi_connector_config", FlattenBiConnectorConfig(clusterOld.BiConnector)); err != nil { + if err := d.Set("bi_connector_config", flattenBiConnectorConfig(clusterOld.BiConnector)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "bi_connector_config", clusterName, err)) } @@ -258,7 +258,7 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "cluster_type", clusterName, err)) } - if err := d.Set("connection_strings", FlattenConnectionStrings(clusterOld.ConnectionStrings)); err != nil { + if err := d.Set("connection_strings", flattenConnectionStrings(clusterOld.ConnectionStrings)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "connection_strings", clusterName, err)) } @@ -274,11 +274,11 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "encryption_at_rest_provider", clusterName, err)) } - if err := d.Set("labels", FlattenLabels(RemoveLabel(clusterOld.Labels, DefaultLabel))); err != nil { + if err := d.Set("labels", flattenLabels(RemoveLabel(clusterOld.Labels, defaultLabel))); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "labels", clusterName, err)) } - if err := d.Set("tags", FlattenTags(&clusterOld.Tags)); err != nil { + if err := d.Set("tags", flattenTags(&clusterOld.Tags)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "tags", clusterName, err)) } diff --git a/internal/service/advancedcluster/data_source_advanced_clusters.go b/internal/service/advancedcluster/data_source_advanced_clusters.go index 17565a90a4..3ef5cf60bf 100644 --- a/internal/service/advancedcluster/data_source_advanced_clusters.go +++ b/internal/service/advancedcluster/data_source_advanced_clusters.go @@ -279,14 +279,14 @@ func flattenAdvancedClusters(ctx context.Context, conn *matlas.Client, connV2 *a result := map[string]any{ "advanced_configuration": flattenProcessArgs(processArgs), "backup_enabled": clusters[i].BackupEnabled, - "bi_connector_config": FlattenBiConnectorConfig(clusters[i].BiConnector), + "bi_connector_config": flattenBiConnectorConfig(clusters[i].BiConnector), "cluster_type": clusters[i].ClusterType, "create_date": clusters[i].CreateDate, - "connection_strings": FlattenConnectionStrings(clusters[i].ConnectionStrings), + "connection_strings": flattenConnectionStrings(clusters[i].ConnectionStrings), "disk_size_gb": clusters[i].DiskSizeGB, "encryption_at_rest_provider": clusters[i].EncryptionAtRestProvider, - "labels": FlattenLabels(clusters[i].Labels), - "tags": FlattenTags(&clusters[i].Tags), + "labels": flattenLabels(clusters[i].Labels), + "tags": flattenTags(&clusters[i].Tags), "mongo_db_major_version": clusters[i].MongoDBMajorVersion, "mongo_db_version": clusters[i].MongoDBVersion, "name": clusters[i].Name, diff --git a/internal/service/advancedcluster/common_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go similarity index 96% rename from internal/service/advancedcluster/common_advanced_cluster.go rename to internal/service/advancedcluster/model_advanced_cluster.go index 1dbf30d034..60fa053525 100644 --- a/internal/service/advancedcluster/common_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -28,7 +28,7 @@ const ( ) var ( - DefaultLabel = matlas.Label{Key: "Infrastructure Tool", Value: "MongoDB Atlas Terraform Provider"} + defaultLabel = matlas.Label{Key: "Infrastructure Tool", Value: "MongoDB Atlas Terraform Provider"} DSTagsSchema = schema.Schema{ Type: schema.TypeSet, Computed: true, @@ -215,7 +215,7 @@ func FormatMongoDBMajorVersion(val any) string { return fmt.Sprintf("%.1f", cast.ToFloat32(val)) } -func FlattenLabels(l []matlas.Label) []map[string]any { +func flattenLabels(l []matlas.Label) []map[string]any { labels := make([]map[string]any, len(l)) for i, v := range l { labels[i] = map[string]any{ @@ -223,11 +223,10 @@ func FlattenLabels(l []matlas.Label) []map[string]any { "value": v.Value, } } - return labels } -func FlattenTags(l *[]*matlas.Tag) []map[string]any { +func flattenTags(l *[]*matlas.Tag) []map[string]any { if l == nil { return []map[string]any{} } @@ -241,7 +240,7 @@ func FlattenTags(l *[]*matlas.Tag) []map[string]any { return tags } -func FlattenConnectionStrings(connectionStrings *matlas.ConnectionStrings) []map[string]any { +func flattenConnectionStrings(connectionStrings *matlas.ConnectionStrings) []map[string]any { connections := make([]map[string]any, 0) connections = append(connections, map[string]any{ @@ -255,7 +254,7 @@ func FlattenConnectionStrings(connectionStrings *matlas.ConnectionStrings) []map return connections } -func FlattenBiConnectorConfig(biConnector *matlas.BiConnector) []any { +func flattenBiConnectorConfig(biConnector *matlas.BiConnector) []any { return []any{ map[string]any{ "enabled": *biConnector.Enabled, @@ -264,7 +263,7 @@ func FlattenBiConnectorConfig(biConnector *matlas.BiConnector) []any { } } -func ExpandBiConnectorConfig(d *schema.ResourceData) (*matlas.BiConnector, error) { +func expandBiConnectorConfig(d *schema.ResourceData) (*matlas.BiConnector, error) { var biConnector matlas.BiConnector if v, ok := d.GetOk("bi_connector_config"); ok { @@ -284,7 +283,7 @@ func ExpandBiConnectorConfig(d *schema.ResourceData) (*matlas.BiConnector, error return &biConnector, nil } -func ExpandTagSliceFromSetSchema(d *schema.ResourceData) []*matlas.Tag { +func expandTagSliceFromSetSchema(d *schema.ResourceData) []*matlas.Tag { list := d.Get("tags").(*schema.Set) res := make([]*matlas.Tag, list.Len()) for i, val := range list.List() { @@ -318,7 +317,7 @@ func flattenProcessArgs(p *admin.ClusterDescriptionProcessArgs) []map[string]any } } -func ExpandProcessArgs(d *schema.ResourceData, p map[string]any) *matlas.ProcessArgs { +func expandProcessArgs(d *schema.ResourceData, p map[string]any) *matlas.ProcessArgs { res := &matlas.ProcessArgs{} if _, ok := d.GetOkExists("advanced_configuration.0.default_read_concern"); ok { @@ -380,7 +379,7 @@ func ExpandProcessArgs(d *schema.ResourceData, p map[string]any) *matlas.Process return res } -func ExpandLabelSliceFromSetSchema(d *schema.ResourceData) []matlas.Label { +func expandLabelSliceFromSetSchema(d *schema.ResourceData) []matlas.Label { list := d.Get("labels").(*schema.Set) res := make([]matlas.Label, list.Len()) diff --git a/internal/service/advancedcluster/common_advanced_cluster_test.go b/internal/service/advancedcluster/model_advanced_cluster_test.go similarity index 100% rename from internal/service/advancedcluster/common_advanced_cluster_test.go rename to internal/service/advancedcluster/model_advanced_cluster_test.go diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 119de90f34..6e6f223454 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -373,7 +373,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. request.BackupEnabled = pointy.Bool(v.(bool)) } if _, ok := d.GetOk("bi_connector_config"); ok { - biConnector, err := ExpandBiConnectorConfig(d) + biConnector, err := expandBiConnectorConfig(d) if err != nil { return diag.FromErr(fmt.Errorf(errorCreate, err)) } @@ -386,13 +386,13 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. request.EncryptionAtRestProvider = v.(string) } - if _, ok := d.GetOk("labels"); ok && ContainsLabelOrKey(ExpandLabelSliceFromSetSchema(d), DefaultLabel) { + if _, ok := d.GetOk("labels"); ok && ContainsLabelOrKey(expandLabelSliceFromSetSchema(d), defaultLabel) { return diag.FromErr(fmt.Errorf("you should not set `Infrastructure Tool` label, it is used for internal purposes")) } - request.Labels = append(ExpandLabelSliceFromSetSchema(d), DefaultLabel) + request.Labels = append(expandLabelSliceFromSetSchema(d), defaultLabel) if _, ok := d.GetOk("tags"); ok { - request.Tags = ExpandTagSliceFromSetSchema(d) + request.Tags = expandTagSliceFromSetSchema(d) } if v, ok := d.GetOk("mongo_db_major_version"); ok { request.MongoDBMajorVersion = FormatMongoDBMajorVersion(v.(string)) @@ -445,7 +445,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. */ ac, ok := d.GetOk("advanced_configuration") if aclist, ok1 := ac.([]any); ok1 && len(aclist) > 0 { - advancedConfReq := ExpandProcessArgs(d, aclist[0].(map[string]any)) + advancedConfReq := expandProcessArgs(d, aclist[0].(map[string]any)) if ok { _, _, err := conn.Clusters.UpdateProcessArgs(ctx, projectID, cluster.Name, advancedConfReq) @@ -502,7 +502,7 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "backup_enabled", clusterName, err)) } - if err := d.Set("bi_connector_config", FlattenBiConnectorConfig(clusterOld.BiConnector)); err != nil { + if err := d.Set("bi_connector_config", flattenBiConnectorConfig(clusterOld.BiConnector)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "bi_connector_config", clusterName, err)) } @@ -510,7 +510,7 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "cluster_type", clusterName, err)) } - if err := d.Set("connection_strings", FlattenConnectionStrings(clusterOld.ConnectionStrings)); err != nil { + if err := d.Set("connection_strings", flattenConnectionStrings(clusterOld.ConnectionStrings)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "connection_strings", clusterName, err)) } @@ -526,11 +526,11 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "encryption_at_rest_provider", clusterName, err)) } - if err := d.Set("labels", FlattenLabels(RemoveLabel(clusterOld.Labels, DefaultLabel))); err != nil { + if err := d.Set("labels", flattenLabels(RemoveLabel(clusterOld.Labels, defaultLabel))); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "labels", clusterName, err)) } - if err := d.Set("tags", FlattenTags(&clusterOld.Tags)); err != nil { + if err := d.Set("tags", flattenTags(&clusterOld.Tags)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "tags", clusterName, err)) } @@ -645,7 +645,7 @@ func resourceMongoDBAtlasAdvancedClusterUpdate(ctx context.Context, d *schema.Re } if d.HasChange("bi_connector_config") { - cluster.BiConnector, _ = ExpandBiConnectorConfig(d) + cluster.BiConnector, _ = expandBiConnectorConfig(d) } if d.HasChange("cluster_type") { @@ -661,15 +661,15 @@ func resourceMongoDBAtlasAdvancedClusterUpdate(ctx context.Context, d *schema.Re } if d.HasChange("labels") { - if ContainsLabelOrKey(ExpandLabelSliceFromSetSchema(d), DefaultLabel) { + if ContainsLabelOrKey(expandLabelSliceFromSetSchema(d), defaultLabel) { return diag.FromErr(fmt.Errorf("you should not set `Infrastructure Tool` label, it is used for internal purposes")) } - cluster.Labels = append(ExpandLabelSliceFromSetSchema(d), DefaultLabel) + cluster.Labels = append(expandLabelSliceFromSetSchema(d), defaultLabel) } if d.HasChange("tags") { - cluster.Tags = ExpandTagSliceFromSetSchema(d) + cluster.Tags = expandTagSliceFromSetSchema(d) } if d.HasChange("mongo_db_major_version") { @@ -709,7 +709,7 @@ func resourceMongoDBAtlasAdvancedClusterUpdate(ctx context.Context, d *schema.Re if d.HasChange("advanced_configuration") { ac := d.Get("advanced_configuration") if aclist, ok := ac.([]any); ok && len(aclist) > 0 { - advancedConfReq := ExpandProcessArgs(d, aclist[0].(map[string]any)) + advancedConfReq := expandProcessArgs(d, aclist[0].(map[string]any)) if !reflect.DeepEqual(advancedConfReq, matlas.ProcessArgs{}) { _, _, err := conn.Clusters.UpdateProcessArgs(ctx, projectID, clusterName, advancedConfReq) if err != nil { diff --git a/internal/service/cluster/data_source_cluster.go b/internal/service/cluster/data_source_cluster.go index d09815af7c..82026a53aa 100644 --- a/internal/service/cluster/data_source_cluster.go +++ b/internal/service/cluster/data_source_cluster.go @@ -372,7 +372,7 @@ func dataSourceMongoDBAtlasClusterRead(ctx context.Context, d *schema.ResourceDa return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "cluster_type", clusterName, err)) } - if err := d.Set("connection_strings", advancedcluster.FlattenConnectionStrings(cluster.ConnectionStrings)); err != nil { + if err := d.Set("connection_strings", flattenConnectionStrings(cluster.ConnectionStrings)); err != nil { return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "connection_strings", clusterName, err)) } @@ -423,7 +423,7 @@ func dataSourceMongoDBAtlasClusterRead(ctx context.Context, d *schema.ResourceDa return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "state_name", clusterName, err)) } - if err := d.Set("bi_connector_config", advancedcluster.FlattenBiConnectorConfig(cluster.BiConnector)); err != nil { + if err := d.Set("bi_connector_config", flattenBiConnectorConfig(cluster.BiConnector)); err != nil { return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "bi_connector_config", clusterName, err)) } @@ -439,11 +439,11 @@ func dataSourceMongoDBAtlasClusterRead(ctx context.Context, d *schema.ResourceDa return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "replication_factor", clusterName, err)) } - if err := d.Set("labels", advancedcluster.FlattenLabels(cluster.Labels)); err != nil { + if err := d.Set("labels", flattenLabels(cluster.Labels)); err != nil { return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "labels", clusterName, err)) } - if err := d.Set("tags", advancedcluster.FlattenTags(cluster.Tags)); err != nil { + if err := d.Set("tags", flattenTags(cluster.Tags)); err != nil { return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "tags", clusterName, err)) } diff --git a/internal/service/cluster/data_source_clusters.go b/internal/service/cluster/data_source_clusters.go index a8b29b5bf8..ac63ed3e27 100644 --- a/internal/service/cluster/data_source_clusters.go +++ b/internal/service/cluster/data_source_clusters.go @@ -379,7 +379,7 @@ func flattenClusters(ctx context.Context, d *schema.ResourceData, conn *matlas.C "backup_enabled": clusters[i].BackupEnabled, "provider_backup_enabled": clusters[i].ProviderBackupEnabled, "cluster_type": clusters[i].ClusterType, - "connection_strings": advancedcluster.FlattenConnectionStrings(clusters[i].ConnectionStrings), + "connection_strings": flattenConnectionStrings(clusters[i].ConnectionStrings), "disk_size_gb": clusters[i].DiskSizeGB, "encryption_at_rest_provider": clusters[i].EncryptionAtRestProvider, "mongo_db_major_version": clusters[i].MongoDBMajorVersion, @@ -403,10 +403,10 @@ func flattenClusters(ctx context.Context, d *schema.ResourceData, conn *matlas.C "provider_instance_size_name": clusters[i].ProviderSettings.InstanceSizeName, "provider_name": clusters[i].ProviderSettings.ProviderName, "provider_region_name": clusters[i].ProviderSettings.RegionName, - "bi_connector_config": advancedcluster.FlattenBiConnectorConfig(clusters[i].BiConnector), + "bi_connector_config": flattenBiConnectorConfig(clusters[i].BiConnector), "replication_specs": flattenReplicationSpecs(clusters[i].ReplicationSpecs), - "labels": advancedcluster.FlattenLabels(clusters[i].Labels), - "tags": advancedcluster.FlattenTags(clusters[i].Tags), + "labels": flattenLabels(clusters[i].Labels), + "tags": flattenTags(clusters[i].Tags), "snapshot_backup_policy": snapshotBackupPolicy, "termination_protection_enabled": clusters[i].TerminationProtectionEnabled, "version_release_system": clusters[i].VersionReleaseSystem, diff --git a/internal/service/cluster/model_cluster.go b/internal/service/cluster/model_cluster.go new file mode 100644 index 0000000000..738f4d5360 --- /dev/null +++ b/internal/service/cluster/model_cluster.go @@ -0,0 +1,519 @@ +package cluster + +import ( + "context" + "fmt" + "log" + "net/http" + "reflect" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/advancedcluster" + "github.com/mwielbut/pointy" + "github.com/spf13/cast" + matlas "go.mongodb.org/atlas/mongodbatlas" +) + +func flattenCloudProviderSnapshotBackupPolicy(ctx context.Context, d *schema.ResourceData, conn *matlas.Client, projectID, clusterName string) ([]map[string]any, error) { + backupPolicy, res, err := conn.CloudProviderSnapshotBackupPolicies.Get(ctx, projectID, clusterName) + if err != nil { + if res.StatusCode == http.StatusNotFound || + strings.Contains(err.Error(), "BACKUP_CONFIG_NOT_FOUND") || + strings.Contains(err.Error(), "Not Found") || + strings.Contains(err.Error(), "404") { + return []map[string]any{}, nil + } + + return []map[string]any{}, fmt.Errorf(ErrorSnapshotBackupPolicyRead, clusterName, err) + } + + return []map[string]any{ + { + "cluster_id": backupPolicy.ClusterID, + "cluster_name": backupPolicy.ClusterName, + "next_snapshot": backupPolicy.NextSnapshot, + "reference_hour_of_day": backupPolicy.ReferenceHourOfDay, + "reference_minute_of_hour": backupPolicy.ReferenceMinuteOfHour, + "restore_window_days": backupPolicy.RestoreWindowDays, + "update_snapshots": cast.ToBool(backupPolicy.UpdateSnapshots), + "policies": flattenPolicies(backupPolicy.Policies), + }, + }, nil +} + +func flattenPolicies(policies []matlas.Policy) []map[string]any { + actionList := make([]map[string]any, 0) + for _, v := range policies { + actionList = append(actionList, map[string]any{ + "id": v.ID, + "policy_item": flattenPolicyItems(v.PolicyItems), + }) + } + + return actionList +} + +func flattenPolicyItems(items []matlas.PolicyItem) []map[string]any { + policyItems := make([]map[string]any, 0) + for _, v := range items { + policyItems = append(policyItems, map[string]any{ + "id": v.ID, + "frequency_interval": v.FrequencyInterval, + "frequency_type": v.FrequencyType, + "retention_unit": v.RetentionUnit, + "retention_value": v.RetentionValue, + }) + } + + return policyItems +} + +func flattenProcessArgs(p *matlas.ProcessArgs) []map[string]any { + return []map[string]any{ + { + "default_read_concern": p.DefaultReadConcern, + "default_write_concern": p.DefaultWriteConcern, + "fail_index_key_too_long": cast.ToBool(p.FailIndexKeyTooLong), + "javascript_enabled": cast.ToBool(p.JavascriptEnabled), + "minimum_enabled_tls_protocol": p.MinimumEnabledTLSProtocol, + "no_table_scan": cast.ToBool(p.NoTableScan), + "oplog_size_mb": p.OplogSizeMB, + "oplog_min_retention_hours": p.OplogMinRetentionHours, + "sample_size_bi_connector": p.SampleSizeBIConnector, + "sample_refresh_interval_bi_connector": p.SampleRefreshIntervalBIConnector, + "transaction_lifetime_limit_seconds": p.TransactionLifetimeLimitSeconds, + }, + } +} + +func flattenLabels(l []matlas.Label) []map[string]any { + labels := make([]map[string]any, len(l)) + for i, v := range l { + labels[i] = map[string]any{ + "key": v.Key, + "value": v.Value, + } + } + return labels +} + +func removeLabel(list []matlas.Label, item matlas.Label) []matlas.Label { + var pos int + + for _, v := range list { + if reflect.DeepEqual(v, item) { + list = append(list[:pos], list[pos+1:]...) + + if pos > 0 { + pos-- + } + + continue + } + pos++ + } + + return list +} + +func flattenTags(l *[]*matlas.Tag) []map[string]any { + if l == nil { + return []map[string]any{} + } + tags := make([]map[string]any, len(*l)) + for i, v := range *l { + tags[i] = map[string]any{ + "key": v.Key, + "value": v.Value, + } + } + return tags +} + +func flattenConnectionStrings(connectionStrings *matlas.ConnectionStrings) []map[string]any { + connections := make([]map[string]any, 0) + + connections = append(connections, map[string]any{ + "standard": connectionStrings.Standard, + "standard_srv": connectionStrings.StandardSrv, + "private": connectionStrings.Private, + "private_srv": connectionStrings.PrivateSrv, + "private_endpoint": flattenPrivateEndpoint(connectionStrings.PrivateEndpoint), + }) + + return connections +} + +func flattenPrivateEndpoint(privateEndpoints []matlas.PrivateEndpoint) []map[string]any { + endpoints := make([]map[string]any, 0) + for _, endpoint := range privateEndpoints { + endpoints = append(endpoints, map[string]any{ + "connection_string": endpoint.ConnectionString, + "srv_connection_string": endpoint.SRVConnectionString, + "srv_shard_optimized_connection_string": endpoint.SRVShardOptimizedConnectionString, + "endpoints": flattenEndpoints(endpoint.Endpoints), + "type": endpoint.Type, + }) + } + return endpoints +} + +func flattenEndpoints(listEndpoints []matlas.Endpoint) []map[string]any { + endpoints := make([]map[string]any, 0) + for _, endpoint := range listEndpoints { + endpoints = append(endpoints, map[string]any{ + "region": endpoint.Region, + "provider_name": endpoint.ProviderName, + "endpoint_id": endpoint.EndpointID, + }) + } + return endpoints +} + +func flattenBiConnectorConfig(biConnector *matlas.BiConnector) []any { + return []any{ + map[string]any{ + "enabled": *biConnector.Enabled, + "read_preference": biConnector.ReadPreference, + }, + } +} + +func expandBiConnectorConfig(d *schema.ResourceData) (*matlas.BiConnector, error) { + var biConnector matlas.BiConnector + + if v, ok := d.GetOk("bi_connector_config"); ok { + biConn := v.([]any) + if len(biConn) > 0 { + biConnMap := biConn[0].(map[string]any) + + enabled := cast.ToBool(biConnMap["enabled"]) + + biConnector = matlas.BiConnector{ + Enabled: &enabled, + ReadPreference: cast.ToString(biConnMap["read_preference"]), + } + } + } + + return &biConnector, nil +} + +func expandTagSliceFromSetSchema(d *schema.ResourceData) []*matlas.Tag { + list := d.Get("tags").(*schema.Set) + res := make([]*matlas.Tag, list.Len()) + for i, val := range list.List() { + v := val.(map[string]any) + res[i] = &matlas.Tag{ + Key: v["key"].(string), + Value: v["value"].(string), + } + } + return res +} + +func expandProcessArgs(d *schema.ResourceData, p map[string]any) *matlas.ProcessArgs { + res := &matlas.ProcessArgs{} + + if _, ok := d.GetOkExists("advanced_configuration.0.default_read_concern"); ok { + res.DefaultReadConcern = cast.ToString(p["default_read_concern"]) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.default_write_concern"); ok { + res.DefaultWriteConcern = cast.ToString(p["default_write_concern"]) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.fail_index_key_too_long"); ok { + res.FailIndexKeyTooLong = pointy.Bool(cast.ToBool(p["fail_index_key_too_long"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.javascript_enabled"); ok { + res.JavascriptEnabled = pointy.Bool(cast.ToBool(p["javascript_enabled"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.minimum_enabled_tls_protocol"); ok { + res.MinimumEnabledTLSProtocol = cast.ToString(p["minimum_enabled_tls_protocol"]) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.no_table_scan"); ok { + res.NoTableScan = pointy.Bool(cast.ToBool(p["no_table_scan"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.sample_size_bi_connector"); ok { + res.SampleSizeBIConnector = pointy.Int64(cast.ToInt64(p["sample_size_bi_connector"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.sample_refresh_interval_bi_connector"); ok { + res.SampleRefreshIntervalBIConnector = pointy.Int64(cast.ToInt64(p["sample_refresh_interval_bi_connector"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.oplog_size_mb"); ok { + if sizeMB := cast.ToInt64(p["oplog_size_mb"]); sizeMB != 0 { + res.OplogSizeMB = pointy.Int64(cast.ToInt64(p["oplog_size_mb"])) + } else { + log.Printf(advancedcluster.ErrorClusterSetting, `oplog_size_mb`, "", cast.ToString(sizeMB)) + } + } + + if _, ok := d.GetOkExists("advanced_configuration.0.oplog_min_retention_hours"); ok { + if minRetentionHours := cast.ToFloat64(p["oplog_min_retention_hours"]); minRetentionHours >= 0 { + res.OplogMinRetentionHours = pointy.Float64(cast.ToFloat64(p["oplog_min_retention_hours"])) + } else { + log.Printf(advancedcluster.ErrorClusterSetting, `oplog_min_retention_hours`, "", cast.ToString(minRetentionHours)) + } + } + + if _, ok := d.GetOkExists("advanced_configuration.0.transaction_lifetime_limit_seconds"); ok { + if transactionLifetimeLimitSeconds := cast.ToInt64(p["transaction_lifetime_limit_seconds"]); transactionLifetimeLimitSeconds > 0 { + res.TransactionLifetimeLimitSeconds = pointy.Int64(cast.ToInt64(p["transaction_lifetime_limit_seconds"])) + } else { + log.Printf(advancedcluster.ErrorClusterSetting, `transaction_lifetime_limit_seconds`, "", cast.ToString(transactionLifetimeLimitSeconds)) + } + } + + return res +} + +func expandLabelSliceFromSetSchema(d *schema.ResourceData) []matlas.Label { + list := d.Get("labels").(*schema.Set) + res := make([]matlas.Label, list.Len()) + + for i, val := range list.List() { + v := val.(map[string]any) + res[i] = matlas.Label{ + Key: v["key"].(string), + Value: v["value"].(string), + } + } + + return res +} + +func expandReplicationSpecs(d *schema.ResourceData) ([]matlas.ReplicationSpec, error) { + rSpecs := make([]matlas.ReplicationSpec, 0) + + vRSpecs, okRSpecs := d.GetOk("replication_specs") + vPRName, okPRName := d.GetOk("provider_region_name") + + if okRSpecs { + for _, s := range vRSpecs.(*schema.Set).List() { + spec := s.(map[string]any) + + replaceRegion := "" + originalRegion := "" + id := "" + + if okPRName && d.Get("provider_name").(string) == "GCP" && cast.ToString(d.Get("cluster_type")) == "REPLICASET" { + if d.HasChange("provider_region_name") { + replaceRegion = vPRName.(string) + original, _ := d.GetChange("provider_region_name") + originalRegion = original.(string) + } + } + + if d.HasChange("replication_specs") { + // Get original and new object + var oldSpecs map[string]any + original, _ := d.GetChange("replication_specs") + for _, s := range original.(*schema.Set).List() { + oldSpecs = s.(map[string]any) + if spec["zone_name"].(string) == cast.ToString(oldSpecs["zone_name"]) { + id = oldSpecs["id"].(string) + break + } + } + // If there was an item before and after then use the same id assuming it's the same replication spec + if id == "" && oldSpecs != nil && len(vRSpecs.(*schema.Set).List()) == 1 && len(original.(*schema.Set).List()) == 1 { + id = oldSpecs["id"].(string) + } + } + + regionsConfig, err := expandRegionsConfig(spec["regions_config"].(*schema.Set).List(), originalRegion, replaceRegion) + if err != nil { + return rSpecs, err + } + + rSpec := matlas.ReplicationSpec{ + ID: id, + NumShards: pointy.Int64(cast.ToInt64(spec["num_shards"])), + ZoneName: cast.ToString(spec["zone_name"]), + RegionsConfig: regionsConfig, + } + rSpecs = append(rSpecs, rSpec) + } + } + + return rSpecs, nil +} + +func flattenReplicationSpecs(rSpecs []matlas.ReplicationSpec) []map[string]any { + specs := make([]map[string]any, 0) + + for _, rSpec := range rSpecs { + spec := map[string]any{ + "id": rSpec.ID, + "num_shards": rSpec.NumShards, + "zone_name": cast.ToString(rSpec.ZoneName), + "regions_config": flattenRegionsConfig(rSpec.RegionsConfig), + } + specs = append(specs, spec) + } + + return specs +} + +func expandRegionsConfig(regions []any, originalRegion, replaceRegion string) (map[string]matlas.RegionsConfig, error) { + regionsConfig := make(map[string]matlas.RegionsConfig) + + for _, r := range regions { + region := r.(map[string]any) + + r, err := conversion.ValRegion(region["region_name"]) + if err != nil { + return regionsConfig, err + } + + if replaceRegion != "" && r == originalRegion { + r, err = conversion.ValRegion(replaceRegion) + } + if err != nil { + return regionsConfig, err + } + + regionsConfig[r] = matlas.RegionsConfig{ + AnalyticsNodes: pointy.Int64(cast.ToInt64(region["analytics_nodes"])), + ElectableNodes: pointy.Int64(cast.ToInt64(region["electable_nodes"])), + Priority: pointy.Int64(cast.ToInt64(region["priority"])), + ReadOnlyNodes: pointy.Int64(cast.ToInt64(region["read_only_nodes"])), + } + } + + return regionsConfig, nil +} + +func flattenRegionsConfig(regionsConfig map[string]matlas.RegionsConfig) []map[string]any { + regions := make([]map[string]any, 0) + + for regionName, regionConfig := range regionsConfig { + region := map[string]any{ + "region_name": regionName, + "priority": regionConfig.Priority, + "analytics_nodes": regionConfig.AnalyticsNodes, + "electable_nodes": regionConfig.ElectableNodes, + "read_only_nodes": regionConfig.ReadOnlyNodes, + } + regions = append(regions, region) + } + + return regions +} + +func expandProviderSetting(d *schema.ResourceData) (*matlas.ProviderSettings, error) { + var ( + region, _ = conversion.ValRegion(d.Get("provider_region_name")) + minInstanceSize = getInstanceSizeToInt(d.Get("provider_auto_scaling_compute_min_instance_size").(string)) + maxInstanceSize = getInstanceSizeToInt(d.Get("provider_auto_scaling_compute_max_instance_size").(string)) + instanceSize = getInstanceSizeToInt(d.Get("provider_instance_size_name").(string)) + compute *matlas.Compute + autoScalingEnabled = d.Get("auto_scaling_compute_enabled").(bool) + providerName = cast.ToString(d.Get("provider_name")) + ) + + if minInstanceSize != 0 && autoScalingEnabled { + if instanceSize < minInstanceSize { + return nil, fmt.Errorf("`provider_auto_scaling_compute_min_instance_size` must be lower than `provider_instance_size_name`") + } + + compute = &matlas.Compute{ + MinInstanceSize: d.Get("provider_auto_scaling_compute_min_instance_size").(string), + } + } + + if maxInstanceSize != 0 && autoScalingEnabled { + if instanceSize > maxInstanceSize { + return nil, fmt.Errorf("`provider_auto_scaling_compute_max_instance_size` must be higher than `provider_instance_size_name`") + } + + if compute == nil { + compute = &matlas.Compute{} + } + compute.MaxInstanceSize = d.Get("provider_auto_scaling_compute_max_instance_size").(string) + } + + providerSettings := &matlas.ProviderSettings{ + InstanceSizeName: cast.ToString(d.Get("provider_instance_size_name")), + ProviderName: providerName, + RegionName: region, + VolumeType: cast.ToString(d.Get("provider_volume_type")), + } + + if d.HasChange("provider_disk_type_name") { + _, newdiskTypeName := d.GetChange("provider_disk_type_name") + diskTypeName := cast.ToString(newdiskTypeName) + if diskTypeName != "" { // ensure disk type is not included in request if attribute is removed, prevents errors in NVME intances + providerSettings.DiskTypeName = diskTypeName + } + } + + if providerName == "TENANT" { + providerSettings.BackingProviderName = cast.ToString(d.Get("backing_provider_name")) + } + + if autoScalingEnabled { + providerSettings.AutoScaling = &matlas.AutoScaling{Compute: compute} + } + + if d.Get("provider_name") == "AWS" { + // Check if the Provider Disk IOS sets in the Terraform configuration and if the instance size name is not NVME. + // If it didn't, the MongoDB Atlas server would set it to the default for the amount of storage. + if v, ok := d.GetOk("provider_disk_iops"); ok && !strings.Contains(providerSettings.InstanceSizeName, "NVME") { + providerSettings.DiskIOPS = pointy.Int64(cast.ToInt64(v)) + } + + providerSettings.EncryptEBSVolume = pointy.Bool(true) + } + + return providerSettings, nil +} + +func flattenProviderSettings(d *schema.ResourceData, settings *matlas.ProviderSettings, clusterName string) { + if settings.ProviderName == "TENANT" { + if err := d.Set("backing_provider_name", settings.BackingProviderName); err != nil { + log.Printf(advancedcluster.ErrorClusterSetting, "backing_provider_name", clusterName, err) + } + } + + if settings.DiskIOPS != nil && *settings.DiskIOPS != 0 { + if err := d.Set("provider_disk_iops", *settings.DiskIOPS); err != nil { + log.Printf(advancedcluster.ErrorClusterSetting, "provider_disk_iops", clusterName, err) + } + } + + if err := d.Set("provider_disk_type_name", settings.DiskTypeName); err != nil { + log.Printf(advancedcluster.ErrorClusterSetting, "provider_disk_type_name", clusterName, err) + } + + if settings.EncryptEBSVolume != nil { + if err := d.Set("provider_encrypt_ebs_volume_flag", *settings.EncryptEBSVolume); err != nil { + log.Printf(advancedcluster.ErrorClusterSetting, "provider_encrypt_ebs_volume_flag", clusterName, err) + } + } + + if err := d.Set("provider_instance_size_name", settings.InstanceSizeName); err != nil { + log.Printf(advancedcluster.ErrorClusterSetting, "provider_instance_size_name", clusterName, err) + } + + if err := d.Set("provider_name", settings.ProviderName); err != nil { + log.Printf(advancedcluster.ErrorClusterSetting, "provider_name", clusterName, err) + } + + if err := d.Set("provider_region_name", settings.RegionName); err != nil { + log.Printf(advancedcluster.ErrorClusterSetting, "provider_region_name", clusterName, err) + } + + if err := d.Set("provider_volume_type", settings.VolumeType); err != nil { + log.Printf(advancedcluster.ErrorClusterSetting, "provider_volume_type", clusterName, err) + } +} diff --git a/internal/service/cluster/resource_cluster.go b/internal/service/cluster/resource_cluster.go index 1609f3b5a3..379af0747a 100644 --- a/internal/service/cluster/resource_cluster.go +++ b/internal/service/cluster/resource_cluster.go @@ -9,7 +9,6 @@ import ( "net/http" "reflect" "regexp" - "strings" "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -34,6 +33,8 @@ const ( ErrorSnapshotBackupPolicyRead = "error getting a Cloud Provider Snapshot Backup Policy for the cluster(%s): %s" ) +var defaultLabel = matlas.Label{Key: "Infrastructure Tool", Value: "MongoDB Atlas Terraform Provider"} + func Resource() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceMongoDBAtlasClusterCreate, @@ -485,21 +486,21 @@ func resourceMongoDBAtlasClusterCreate(ctx context.Context, d *schema.ResourceDa } if _, ok := d.GetOk("bi_connector_config"); ok { - biConnector, err := advancedcluster.ExpandBiConnectorConfig(d) + biConnector, err := expandBiConnectorConfig(d) if err != nil { return diag.FromErr(fmt.Errorf(errorClusterCreate, err)) } clusterRequest.BiConnector = biConnector } - if advancedcluster.ContainsLabelOrKey(advancedcluster.ExpandLabelSliceFromSetSchema(d), advancedcluster.DefaultLabel) { + if advancedcluster.ContainsLabelOrKey(expandLabelSliceFromSetSchema(d), defaultLabel) { return diag.FromErr(fmt.Errorf("you should not set `Infrastructure Tool` label, it is used for internal purposes")) } - clusterRequest.Labels = append(advancedcluster.ExpandLabelSliceFromSetSchema(d), advancedcluster.DefaultLabel) + clusterRequest.Labels = append(expandLabelSliceFromSetSchema(d), defaultLabel) if _, ok := d.GetOk("tags"); ok { - tagsSlice := advancedcluster.ExpandTagSliceFromSetSchema(d) + tagsSlice := expandTagSliceFromSetSchema(d) clusterRequest.Tags = &tagsSlice } @@ -556,7 +557,7 @@ func resourceMongoDBAtlasClusterCreate(ctx context.Context, d *schema.ResourceDa */ ac, ok := d.GetOk("advanced_configuration") if aclist, ok1 := ac.([]any); ok1 && len(aclist) > 0 { - advancedConfReq := advancedcluster.ExpandProcessArgs(d, aclist[0].(map[string]any)) + advancedConfReq := expandProcessArgs(d, aclist[0].(map[string]any)) if ok { _, _, err := conn.Clusters.UpdateProcessArgs(ctx, projectID, cluster.Name, advancedConfReq) @@ -642,7 +643,7 @@ func resourceMongoDBAtlasClusterRead(ctx context.Context, d *schema.ResourceData return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "cluster_type", clusterName, err)) } - if err := d.Set("connection_strings", advancedcluster.FlattenConnectionStrings(cluster.ConnectionStrings)); err != nil { + if err := d.Set("connection_strings", flattenConnectionStrings(cluster.ConnectionStrings)); err != nil { return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "connection_strings", clusterName, err)) } @@ -701,7 +702,7 @@ func resourceMongoDBAtlasClusterRead(ctx context.Context, d *schema.ResourceData return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "termination_protection_enabled", clusterName, err)) } - if err := d.Set("bi_connector_config", advancedcluster.FlattenBiConnectorConfig(cluster.BiConnector)); err != nil { + if err := d.Set("bi_connector_config", flattenBiConnectorConfig(cluster.BiConnector)); err != nil { return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "bi_connector_config", clusterName, err)) } @@ -717,11 +718,11 @@ func resourceMongoDBAtlasClusterRead(ctx context.Context, d *schema.ResourceData return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "replication_factor", clusterName, err)) } - if err := d.Set("labels", advancedcluster.FlattenLabels(advancedcluster.RemoveLabel(cluster.Labels, advancedcluster.DefaultLabel))); err != nil { + if err := d.Set("labels", flattenLabels(removeLabel(cluster.Labels, defaultLabel))); err != nil { return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "labels", clusterName, err)) } - if err := d.Set("tags", advancedcluster.FlattenTags(cluster.Tags)); err != nil { + if err := d.Set("tags", flattenTags(cluster.Tags)); err != nil { return diag.FromErr(fmt.Errorf(advancedcluster.ErrorClusterSetting, "tags", clusterName, err)) } @@ -790,7 +791,7 @@ func resourceMongoDBAtlasClusterUpdate(ctx context.Context, d *schema.ResourceDa } if d.HasChange("bi_connector_config") { - cluster.BiConnector, _ = advancedcluster.ExpandBiConnectorConfig(d) + cluster.BiConnector, _ = expandBiConnectorConfig(d) } // If at least one of the provider settings argument has changed, expand all provider settings @@ -892,15 +893,15 @@ func resourceMongoDBAtlasClusterUpdate(ctx context.Context, d *schema.ResourceDa } if d.HasChange("labels") { - if advancedcluster.ContainsLabelOrKey(advancedcluster.ExpandLabelSliceFromSetSchema(d), advancedcluster.DefaultLabel) { + if advancedcluster.ContainsLabelOrKey(expandLabelSliceFromSetSchema(d), defaultLabel) { return diag.FromErr(fmt.Errorf("you should not set `Infrastructure Tool` label, it is used for internal purposes")) } - cluster.Labels = append(advancedcluster.ExpandLabelSliceFromSetSchema(d), advancedcluster.DefaultLabel) + cluster.Labels = append(expandLabelSliceFromSetSchema(d), defaultLabel) } if d.HasChange("tags") { - tagsSlice := advancedcluster.ExpandTagSliceFromSetSchema(d) + tagsSlice := expandTagSliceFromSetSchema(d) cluster.Tags = &tagsSlice } @@ -923,7 +924,7 @@ func resourceMongoDBAtlasClusterUpdate(ctx context.Context, d *schema.ResourceDa if d.HasChange("advanced_configuration") { ac := d.Get("advanced_configuration") if aclist, ok1 := ac.([]any); ok1 && len(aclist) > 0 { - advancedConfReq := advancedcluster.ExpandProcessArgs(d, aclist[0].(map[string]any)) + advancedConfReq := expandProcessArgs(d, aclist[0].(map[string]any)) if !reflect.DeepEqual(advancedConfReq, matlas.ProcessArgs{}) { argResp, _, err := conn.Clusters.UpdateProcessArgs(ctx, projectID, clusterName, advancedConfReq) if err != nil { @@ -1111,239 +1112,12 @@ func getInstanceSizeToInt(instanceSize string) int { return cast.ToInt(num) // if the string is empty it always return 0 } -func expandProviderSetting(d *schema.ResourceData) (*matlas.ProviderSettings, error) { - var ( - region, _ = conversion.ValRegion(d.Get("provider_region_name")) - minInstanceSize = getInstanceSizeToInt(d.Get("provider_auto_scaling_compute_min_instance_size").(string)) - maxInstanceSize = getInstanceSizeToInt(d.Get("provider_auto_scaling_compute_max_instance_size").(string)) - instanceSize = getInstanceSizeToInt(d.Get("provider_instance_size_name").(string)) - compute *matlas.Compute - autoScalingEnabled = d.Get("auto_scaling_compute_enabled").(bool) - providerName = cast.ToString(d.Get("provider_name")) - ) - - if minInstanceSize != 0 && autoScalingEnabled { - if instanceSize < minInstanceSize { - return nil, fmt.Errorf("`provider_auto_scaling_compute_min_instance_size` must be lower than `provider_instance_size_name`") - } - - compute = &matlas.Compute{ - MinInstanceSize: d.Get("provider_auto_scaling_compute_min_instance_size").(string), - } - } - - if maxInstanceSize != 0 && autoScalingEnabled { - if instanceSize > maxInstanceSize { - return nil, fmt.Errorf("`provider_auto_scaling_compute_max_instance_size` must be higher than `provider_instance_size_name`") - } - - if compute == nil { - compute = &matlas.Compute{} - } - compute.MaxInstanceSize = d.Get("provider_auto_scaling_compute_max_instance_size").(string) - } - - providerSettings := &matlas.ProviderSettings{ - InstanceSizeName: cast.ToString(d.Get("provider_instance_size_name")), - ProviderName: providerName, - RegionName: region, - VolumeType: cast.ToString(d.Get("provider_volume_type")), - } - - if d.HasChange("provider_disk_type_name") { - _, newdiskTypeName := d.GetChange("provider_disk_type_name") - diskTypeName := cast.ToString(newdiskTypeName) - if diskTypeName != "" { // ensure disk type is not included in request if attribute is removed, prevents errors in NVME intances - providerSettings.DiskTypeName = diskTypeName - } - } - - if providerName == "TENANT" { - providerSettings.BackingProviderName = cast.ToString(d.Get("backing_provider_name")) - } - - if autoScalingEnabled { - providerSettings.AutoScaling = &matlas.AutoScaling{Compute: compute} - } - - if d.Get("provider_name") == "AWS" { - // Check if the Provider Disk IOS sets in the Terraform configuration and if the instance size name is not NVME. - // If it didn't, the MongoDB Atlas server would set it to the default for the amount of storage. - if v, ok := d.GetOk("provider_disk_iops"); ok && !strings.Contains(providerSettings.InstanceSizeName, "NVME") { - providerSettings.DiskIOPS = pointy.Int64(cast.ToInt64(v)) - } - - providerSettings.EncryptEBSVolume = pointy.Bool(true) - } - - return providerSettings, nil -} - -func flattenProviderSettings(d *schema.ResourceData, settings *matlas.ProviderSettings, clusterName string) { - if settings.ProviderName == "TENANT" { - if err := d.Set("backing_provider_name", settings.BackingProviderName); err != nil { - log.Printf(advancedcluster.ErrorClusterSetting, "backing_provider_name", clusterName, err) - } - } - - if settings.DiskIOPS != nil && *settings.DiskIOPS != 0 { - if err := d.Set("provider_disk_iops", *settings.DiskIOPS); err != nil { - log.Printf(advancedcluster.ErrorClusterSetting, "provider_disk_iops", clusterName, err) - } - } - - if err := d.Set("provider_disk_type_name", settings.DiskTypeName); err != nil { - log.Printf(advancedcluster.ErrorClusterSetting, "provider_disk_type_name", clusterName, err) - } - - if settings.EncryptEBSVolume != nil { - if err := d.Set("provider_encrypt_ebs_volume_flag", *settings.EncryptEBSVolume); err != nil { - log.Printf(advancedcluster.ErrorClusterSetting, "provider_encrypt_ebs_volume_flag", clusterName, err) - } - } - - if err := d.Set("provider_instance_size_name", settings.InstanceSizeName); err != nil { - log.Printf(advancedcluster.ErrorClusterSetting, "provider_instance_size_name", clusterName, err) - } - - if err := d.Set("provider_name", settings.ProviderName); err != nil { - log.Printf(advancedcluster.ErrorClusterSetting, "provider_name", clusterName, err) - } - - if err := d.Set("provider_region_name", settings.RegionName); err != nil { - log.Printf(advancedcluster.ErrorClusterSetting, "provider_region_name", clusterName, err) - } - - if err := d.Set("provider_volume_type", settings.VolumeType); err != nil { - log.Printf(advancedcluster.ErrorClusterSetting, "provider_volume_type", clusterName, err) - } -} - func isUpgradeRequired(d *schema.ResourceData) bool { currentSize, updatedSize := d.GetChange("provider_instance_size_name") return currentSize != updatedSize && advancedcluster.IsSharedTier(currentSize.(string)) } -func expandReplicationSpecs(d *schema.ResourceData) ([]matlas.ReplicationSpec, error) { - rSpecs := make([]matlas.ReplicationSpec, 0) - - vRSpecs, okRSpecs := d.GetOk("replication_specs") - vPRName, okPRName := d.GetOk("provider_region_name") - - if okRSpecs { - for _, s := range vRSpecs.(*schema.Set).List() { - spec := s.(map[string]any) - - replaceRegion := "" - originalRegion := "" - id := "" - - if okPRName && d.Get("provider_name").(string) == "GCP" && cast.ToString(d.Get("cluster_type")) == "REPLICASET" { - if d.HasChange("provider_region_name") { - replaceRegion = vPRName.(string) - original, _ := d.GetChange("provider_region_name") - originalRegion = original.(string) - } - } - - if d.HasChange("replication_specs") { - // Get original and new object - var oldSpecs map[string]any - original, _ := d.GetChange("replication_specs") - for _, s := range original.(*schema.Set).List() { - oldSpecs = s.(map[string]any) - if spec["zone_name"].(string) == cast.ToString(oldSpecs["zone_name"]) { - id = oldSpecs["id"].(string) - break - } - } - // If there was an item before and after then use the same id assuming it's the same replication spec - if id == "" && oldSpecs != nil && len(vRSpecs.(*schema.Set).List()) == 1 && len(original.(*schema.Set).List()) == 1 { - id = oldSpecs["id"].(string) - } - } - - regionsConfig, err := expandRegionsConfig(spec["regions_config"].(*schema.Set).List(), originalRegion, replaceRegion) - if err != nil { - return rSpecs, err - } - - rSpec := matlas.ReplicationSpec{ - ID: id, - NumShards: pointy.Int64(cast.ToInt64(spec["num_shards"])), - ZoneName: cast.ToString(spec["zone_name"]), - RegionsConfig: regionsConfig, - } - rSpecs = append(rSpecs, rSpec) - } - } - - return rSpecs, nil -} - -func flattenReplicationSpecs(rSpecs []matlas.ReplicationSpec) []map[string]any { - specs := make([]map[string]any, 0) - - for _, rSpec := range rSpecs { - spec := map[string]any{ - "id": rSpec.ID, - "num_shards": rSpec.NumShards, - "zone_name": cast.ToString(rSpec.ZoneName), - "regions_config": flattenRegionsConfig(rSpec.RegionsConfig), - } - specs = append(specs, spec) - } - - return specs -} - -func expandRegionsConfig(regions []any, originalRegion, replaceRegion string) (map[string]matlas.RegionsConfig, error) { - regionsConfig := make(map[string]matlas.RegionsConfig) - - for _, r := range regions { - region := r.(map[string]any) - - r, err := conversion.ValRegion(region["region_name"]) - if err != nil { - return regionsConfig, err - } - - if replaceRegion != "" && r == originalRegion { - r, err = conversion.ValRegion(replaceRegion) - } - if err != nil { - return regionsConfig, err - } - - regionsConfig[r] = matlas.RegionsConfig{ - AnalyticsNodes: pointy.Int64(cast.ToInt64(region["analytics_nodes"])), - ElectableNodes: pointy.Int64(cast.ToInt64(region["electable_nodes"])), - Priority: pointy.Int64(cast.ToInt64(region["priority"])), - ReadOnlyNodes: pointy.Int64(cast.ToInt64(region["read_only_nodes"])), - } - } - - return regionsConfig, nil -} - -func flattenRegionsConfig(regionsConfig map[string]matlas.RegionsConfig) []map[string]any { - regions := make([]map[string]any, 0) - - for regionName, regionConfig := range regionsConfig { - region := map[string]any{ - "region_name": regionName, - "priority": regionConfig.Priority, - "analytics_nodes": regionConfig.AnalyticsNodes, - "electable_nodes": regionConfig.ElectableNodes, - "read_only_nodes": regionConfig.ReadOnlyNodes, - } - regions = append(regions, region) - } - - return regions -} - func resourceClusterCustomizeDiff(ctx context.Context, d *schema.ResourceDiff, meta any) error { var err error currentProvider, updatedProvider := d.GetChange("provider_name") @@ -1509,75 +1283,3 @@ func computedCloudProviderSnapshotBackupPolicySchema() *schema.Schema { }, } } - -func flattenCloudProviderSnapshotBackupPolicy(ctx context.Context, d *schema.ResourceData, conn *matlas.Client, projectID, clusterName string) ([]map[string]any, error) { - backupPolicy, res, err := conn.CloudProviderSnapshotBackupPolicies.Get(ctx, projectID, clusterName) - if err != nil { - if res.StatusCode == http.StatusNotFound || - strings.Contains(err.Error(), "BACKUP_CONFIG_NOT_FOUND") || - strings.Contains(err.Error(), "Not Found") || - strings.Contains(err.Error(), "404") { - return []map[string]any{}, nil - } - - return []map[string]any{}, fmt.Errorf(ErrorSnapshotBackupPolicyRead, clusterName, err) - } - - return []map[string]any{ - { - "cluster_id": backupPolicy.ClusterID, - "cluster_name": backupPolicy.ClusterName, - "next_snapshot": backupPolicy.NextSnapshot, - "reference_hour_of_day": backupPolicy.ReferenceHourOfDay, - "reference_minute_of_hour": backupPolicy.ReferenceMinuteOfHour, - "restore_window_days": backupPolicy.RestoreWindowDays, - "update_snapshots": cast.ToBool(backupPolicy.UpdateSnapshots), - "policies": flattenPolicies(backupPolicy.Policies), - }, - }, nil -} - -func flattenPolicies(policies []matlas.Policy) []map[string]any { - actionList := make([]map[string]any, 0) - for _, v := range policies { - actionList = append(actionList, map[string]any{ - "id": v.ID, - "policy_item": flattenPolicyItems(v.PolicyItems), - }) - } - - return actionList -} - -func flattenPolicyItems(items []matlas.PolicyItem) []map[string]any { - policyItems := make([]map[string]any, 0) - for _, v := range items { - policyItems = append(policyItems, map[string]any{ - "id": v.ID, - "frequency_interval": v.FrequencyInterval, - "frequency_type": v.FrequencyType, - "retention_unit": v.RetentionUnit, - "retention_value": v.RetentionValue, - }) - } - - return policyItems -} - -func flattenProcessArgs(p *matlas.ProcessArgs) []map[string]any { - return []map[string]any{ - { - "default_read_concern": p.DefaultReadConcern, - "default_write_concern": p.DefaultWriteConcern, - "fail_index_key_too_long": cast.ToBool(p.FailIndexKeyTooLong), - "javascript_enabled": cast.ToBool(p.JavascriptEnabled), - "minimum_enabled_tls_protocol": p.MinimumEnabledTLSProtocol, - "no_table_scan": cast.ToBool(p.NoTableScan), - "oplog_size_mb": p.OplogSizeMB, - "oplog_min_retention_hours": p.OplogMinRetentionHours, - "sample_size_bi_connector": p.SampleSizeBIConnector, - "sample_refresh_interval_bi_connector": p.SampleRefreshIntervalBIConnector, - "transaction_lifetime_limit_seconds": p.TransactionLifetimeLimitSeconds, - }, - } -} diff --git a/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode_test.go b/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode_test.go index b89091d995..df38ec2ddc 100644 --- a/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode_test.go +++ b/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" - "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/advancedcluster" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) @@ -177,8 +176,6 @@ func testAccCheckMongoDBAtlasPrivateEndpointRegionalModeClustersUpToDate(project return fmt.Errorf("Connection strings private endpoint count is not a number") } c, _, _ := acc.Conn().Clusters.Get(context.Background(), projectID, clusterName) - fmt.Printf("testAccCheckMongoDBAtlasPrivateEndpointRegionalModeClustersUpToDate %#v \n", rs.Primary.Attributes) - fmt.Printf("cluster.ConnectionStrings %#v \n", advancedcluster.FlattenConnectionStrings(c.ConnectionStrings)) if rsPrivateEndpointCount != len(c.ConnectionStrings.PrivateEndpoint) { return fmt.Errorf("Cluster PrivateEndpoint count does not match resource") } From d6818e6bd1e8a9e629c7d37feaa1f50d7f3f141e Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 12:48:54 +0100 Subject: [PATCH 21/52] run cluster tests --- .github/workflows/acceptance-tests-runner.yml | 2 +- .github/workflows/migration-tests.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/acceptance-tests-runner.yml b/.github/workflows/acceptance-tests-runner.yml index 097f30e412..b47a86902f 100644 --- a/.github/workflows/acceptance-tests-runner.yml +++ b/.github/workflows/acceptance-tests-runner.yml @@ -123,7 +123,7 @@ jobs: outputs: cluster_outage_simulation: ${{ steps.filter.outputs.cluster_outage_simulation == 'true' || env.mustTrigger == 'true' }} advanced_cluster: ${{ steps.filter.outputs.advanced_cluster == 'true' || env.mustTrigger == 'true' }} - cluster: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + cluster: ${{ steps.filter.outputs.cluster == 'true' || env.mustTrigger == 'true' }} search_deployment: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE stream: ${{ steps.filter.outputs.stream == 'true' || env.mustTrigger == 'true' }} generic: ${{ steps.filter.outputs.generic == 'true' || env.mustTrigger == 'true' }} diff --git a/.github/workflows/migration-tests.yml b/.github/workflows/migration-tests.yml index 27b9d3cc29..805ec13135 100644 --- a/.github/workflows/migration-tests.yml +++ b/.github/workflows/migration-tests.yml @@ -67,7 +67,7 @@ jobs: serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} data_lake: ${{ steps.filter.outputs.data_lake == 'true' || env.mustTrigger == 'true' }} cluster_outage_simulation: ${{ steps.filter.outputs.cluster_outage_simulation == 'true' || env.mustTrigger == 'true' }} - cluster: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + cluster: ${{ steps.filter.outputs.cluster == 'true' || env.mustTrigger == 'true' }} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 - uses: dorny/paths-filter@0bc4621a3135347011ad047f9ecf449bf72ce2bd From 24100034692a5a4ce7029112a818e4af6c8cbac5 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 12:51:42 +0100 Subject: [PATCH 22/52] TEMPORARY don't run network tests (fix) --- .github/workflows/acceptance-tests-runner.yml | 2 +- .github/workflows/migration-tests.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/acceptance-tests-runner.yml b/.github/workflows/acceptance-tests-runner.yml index b47a86902f..ac28105b60 100644 --- a/.github/workflows/acceptance-tests-runner.yml +++ b/.github/workflows/acceptance-tests-runner.yml @@ -130,7 +130,7 @@ jobs: backup: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE project: ${{ steps.filter.outputs.project == 'true' || env.mustTrigger == 'true' }} serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} - network: # TEMPORARY, WILL BE REVERTED BEFORE MERGE + network: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE config: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE assume_role: ${{ steps.filter.outputs.assume_role == 'true' || env.mustTrigger == 'true' }} event_trigger: ${{ steps.filter.outputs.event_trigger == 'true' || env.mustTrigger == 'true' }} diff --git a/.github/workflows/migration-tests.yml b/.github/workflows/migration-tests.yml index 805ec13135..2353f9627b 100644 --- a/.github/workflows/migration-tests.yml +++ b/.github/workflows/migration-tests.yml @@ -62,7 +62,7 @@ jobs: federated: ${{ steps.filter.outputs.federated == 'true' || env.mustTrigger == 'true' }} search_deployment: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE generic: ${{ steps.filter.outputs.generic == 'true' || env.mustTrigger == 'true' }} - network: ${{ steps.filter.outputs.network == 'true' || env.mustTrigger == 'true' }} + network: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE encryption: ${{ steps.filter.outputs.encryption == 'true' || env.mustTrigger == 'true' }} serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} data_lake: ${{ steps.filter.outputs.data_lake == 'true' || env.mustTrigger == 'true' }} From 8746120ebc64921084d9d191002eb74ef1de2506 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 13:09:32 +0100 Subject: [PATCH 23/52] Revert "run cluster tests" This reverts commit d6818e6bd1e8a9e629c7d37feaa1f50d7f3f141e. --- .github/workflows/acceptance-tests-runner.yml | 2 +- .github/workflows/migration-tests.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/acceptance-tests-runner.yml b/.github/workflows/acceptance-tests-runner.yml index ac28105b60..2cf860ddec 100644 --- a/.github/workflows/acceptance-tests-runner.yml +++ b/.github/workflows/acceptance-tests-runner.yml @@ -123,7 +123,7 @@ jobs: outputs: cluster_outage_simulation: ${{ steps.filter.outputs.cluster_outage_simulation == 'true' || env.mustTrigger == 'true' }} advanced_cluster: ${{ steps.filter.outputs.advanced_cluster == 'true' || env.mustTrigger == 'true' }} - cluster: ${{ steps.filter.outputs.cluster == 'true' || env.mustTrigger == 'true' }} + cluster: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE search_deployment: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE stream: ${{ steps.filter.outputs.stream == 'true' || env.mustTrigger == 'true' }} generic: ${{ steps.filter.outputs.generic == 'true' || env.mustTrigger == 'true' }} diff --git a/.github/workflows/migration-tests.yml b/.github/workflows/migration-tests.yml index 2353f9627b..3d26afa991 100644 --- a/.github/workflows/migration-tests.yml +++ b/.github/workflows/migration-tests.yml @@ -67,7 +67,7 @@ jobs: serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} data_lake: ${{ steps.filter.outputs.data_lake == 'true' || env.mustTrigger == 'true' }} cluster_outage_simulation: ${{ steps.filter.outputs.cluster_outage_simulation == 'true' || env.mustTrigger == 'true' }} - cluster: ${{ steps.filter.outputs.cluster == 'true' || env.mustTrigger == 'true' }} + cluster: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 - uses: dorny/paths-filter@0bc4621a3135347011ad047f9ecf449bf72ce2bd From 60c171a02baf8379b2516c970b2e5cdffd011fdf Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 16:37:50 +0100 Subject: [PATCH 24/52] FlattenTags --- .../data_source_advanced_cluster.go | 2 +- .../data_source_advanced_clusters.go | 71 +++++++++++-------- .../advancedcluster/model_advanced_cluster.go | 14 ---- .../resource_advanced_cluster.go | 2 +- 4 files changed, 44 insertions(+), 45 deletions(-) diff --git a/internal/service/advancedcluster/data_source_advanced_cluster.go b/internal/service/advancedcluster/data_source_advanced_cluster.go index 366c744b0c..2507a832da 100644 --- a/internal/service/advancedcluster/data_source_advanced_cluster.go +++ b/internal/service/advancedcluster/data_source_advanced_cluster.go @@ -278,7 +278,7 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "labels", clusterName, err)) } - if err := d.Set("tags", flattenTags(&clusterOld.Tags)); err != nil { + if err := d.Set("tags", conversion.FlattenTags(cluster.GetTags())); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "tags", clusterName, err)) } diff --git a/internal/service/advancedcluster/data_source_advanced_clusters.go b/internal/service/advancedcluster/data_source_advanced_clusters.go index 3ef5cf60bf..f00306d7bf 100644 --- a/internal/service/advancedcluster/data_source_advanced_clusters.go +++ b/internal/service/advancedcluster/data_source_advanced_clusters.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/constant" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "go.mongodb.org/atlas-sdk/v20231115006/admin" matlas "go.mongodb.org/atlas/mongodbatlas" @@ -247,59 +248,71 @@ func dataSourcePluralRead(ctx context.Context, d *schema.ResourceData, meta any) projectID := d.Get("project_id").(string) d.SetId(id.UniqueId()) - clusters, resp, err := conn.AdvancedClusters.List(ctx, projectID, nil) + list, resp, err := connV2.ClustersApi.ListClusters(ctx, projectID).Execute() + listOld, _, _ := conn.AdvancedClusters.List(ctx, projectID, nil) if err != nil { if resp != nil && resp.StatusCode == http.StatusNotFound { return nil } - return diag.FromErr(fmt.Errorf("error reading advanced cluster list for project(%s): %s", projectID, err)) } + if len(list.GetResults()) == 0 || len(listOld.Results) == 0 { + return nil + } - if err := d.Set("results", flattenAdvancedClusters(ctx, conn, connV2, clusters.Results, d)); err != nil { + if err := d.Set("results", flattenAdvancedClusters(ctx, conn, connV2, list.GetResults(), listOld.Results, d)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "results", d.Id(), err)) } return nil } -func flattenAdvancedClusters(ctx context.Context, conn *matlas.Client, connV2 *admin.APIClient, clusters []*matlas.AdvancedCluster, d *schema.ResourceData) []map[string]any { - results := make([]map[string]any, 0) - +func flattenAdvancedClusters(ctx context.Context, conn *matlas.Client, connV2 *admin.APIClient, clusters []admin.AdvancedClusterDescription, clustersOld []*matlas.AdvancedCluster, d *schema.ResourceData) []map[string]any { + results := make([]map[string]any, 0, len(clusters)) for i := range clusters { - processArgs, _, err := connV2.ClustersApi.GetClusterAdvancedConfiguration(ctx, clusters[i].GroupID, clusters[i].Name).Execute() + cluster := &clusters[i] + var clusterOld *matlas.AdvancedCluster + for j := range clustersOld { + if clustersOld[j].ID == cluster.GetId() { + clusterOld = clustersOld[j] + break + } + } + if clusterOld == nil { + continue + } + processArgs, _, err := connV2.ClustersApi.GetClusterAdvancedConfiguration(ctx, cluster.GetGroupId(), cluster.GetName()).Execute() if err != nil { - log.Printf("[WARN] Error setting `advanced_configuration` for the cluster(%s): %s", clusters[i].ID, err) + log.Printf("[WARN] Error setting `advanced_configuration` for the cluster(%s): %s", cluster.GetId(), err) } - replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, clusters[i].ReplicationSpecs, nil, d, conn) + replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, clusterOld.ReplicationSpecs, nil, d, conn) if err != nil { - log.Printf("[WARN] Error setting `replication_specs` for the cluster(%s): %s", clusters[i].ID, err) + log.Printf("[WARN] Error setting `replication_specs` for the cluster(%s): %s", cluster.GetId(), err) } result := map[string]any{ "advanced_configuration": flattenProcessArgs(processArgs), - "backup_enabled": clusters[i].BackupEnabled, - "bi_connector_config": flattenBiConnectorConfig(clusters[i].BiConnector), - "cluster_type": clusters[i].ClusterType, - "create_date": clusters[i].CreateDate, - "connection_strings": flattenConnectionStrings(clusters[i].ConnectionStrings), - "disk_size_gb": clusters[i].DiskSizeGB, - "encryption_at_rest_provider": clusters[i].EncryptionAtRestProvider, - "labels": flattenLabels(clusters[i].Labels), - "tags": flattenTags(&clusters[i].Tags), - "mongo_db_major_version": clusters[i].MongoDBMajorVersion, - "mongo_db_version": clusters[i].MongoDBVersion, - "name": clusters[i].Name, - "paused": clusters[i].Paused, - "pit_enabled": clusters[i].PitEnabled, + "backup_enabled": cluster.GetBackupEnabled(), + "bi_connector_config": flattenBiConnectorConfig(clusterOld.BiConnector), + "cluster_type": cluster.GetClusterType(), + "create_date": conversion.TimePtrToStringPtr(cluster.CreateDate), + "connection_strings": flattenConnectionStrings(clusterOld.ConnectionStrings), + "disk_size_gb": cluster.GetDiskSizeGB(), + "encryption_at_rest_provider": cluster.GetEncryptionAtRestProvider(), + "labels": flattenLabels(clusterOld.Labels), + "tags": conversion.FlattenTags(cluster.GetTags()), + "mongo_db_major_version": cluster.GetMongoDBMajorVersion(), + "mongo_db_version": cluster.GetMongoDBVersion(), + "name": cluster.GetName(), + "paused": cluster.GetPaused(), + "pit_enabled": cluster.GetPitEnabled(), "replication_specs": replicationSpecs, - "root_cert_type": clusters[i].RootCertType, - "state_name": clusters[i].StateName, - "termination_protection_enabled": clusters[i].TerminationProtectionEnabled, - "version_release_system": clusters[i].VersionReleaseSystem, + "root_cert_type": cluster.GetRootCertType(), + "state_name": cluster.GetStateName(), + "termination_protection_enabled": cluster.GetTerminationProtectionEnabled(), + "version_release_system": cluster.GetVersionReleaseSystem(), } results = append(results, result) } - return results } diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index 60fa053525..20d07ed3f3 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -226,20 +226,6 @@ func flattenLabels(l []matlas.Label) []map[string]any { return labels } -func flattenTags(l *[]*matlas.Tag) []map[string]any { - if l == nil { - return []map[string]any{} - } - tags := make([]map[string]any, len(*l)) - for i, v := range *l { - tags[i] = map[string]any{ - "key": v.Key, - "value": v.Value, - } - } - return tags -} - func flattenConnectionStrings(connectionStrings *matlas.ConnectionStrings) []map[string]any { connections := make([]map[string]any, 0) diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 6e6f223454..27232cedc9 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -530,7 +530,7 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "labels", clusterName, err)) } - if err := d.Set("tags", flattenTags(&clusterOld.Tags)); err != nil { + if err := d.Set("tags", conversion.FlattenTags(cluster.GetTags())); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "tags", clusterName, err)) } From b1d811d3cf9a6504eddbb60941225934b2a8ffd7 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 15 Feb 2024 18:37:09 +0100 Subject: [PATCH 25/52] flattenLabels --- internal/common/conversion/flatten_expand.go | 12 +++---- .../data_source_advanced_cluster.go | 2 +- .../data_source_advanced_clusters.go | 2 +- .../advancedcluster/model_advanced_cluster.go | 36 ++++++------------- .../model_advanced_cluster_test.go | 24 ------------- .../resource_advanced_cluster.go | 2 +- 6 files changed, 19 insertions(+), 59 deletions(-) diff --git a/internal/common/conversion/flatten_expand.go b/internal/common/conversion/flatten_expand.go index a4afc5178b..1105092b62 100644 --- a/internal/common/conversion/flatten_expand.go +++ b/internal/common/conversion/flatten_expand.go @@ -6,10 +6,10 @@ import ( "go.mongodb.org/atlas-sdk/v20231115006/admin" ) -func FlattenLinks(links []admin.Link) []map[string]any { - ret := make([]map[string]any, len(links)) +func FlattenLinks(links []admin.Link) []map[string]string { + ret := make([]map[string]string, len(links)) for i, link := range links { - ret[i] = map[string]any{ + ret[i] = map[string]string{ "href": link.GetHref(), "rel": link.GetRel(), } @@ -17,10 +17,10 @@ func FlattenLinks(links []admin.Link) []map[string]any { return ret } -func FlattenTags(tags []admin.ResourceTag) []map[string]any { - ret := make([]map[string]any, len(tags)) +func FlattenTags(tags []admin.ResourceTag) []map[string]string { + ret := make([]map[string]string, len(tags)) for i, tag := range tags { - ret[i] = map[string]any{ + ret[i] = map[string]string{ "key": tag.GetKey(), "value": tag.GetValue(), } diff --git a/internal/service/advancedcluster/data_source_advanced_cluster.go b/internal/service/advancedcluster/data_source_advanced_cluster.go index 2507a832da..2c624f89bb 100644 --- a/internal/service/advancedcluster/data_source_advanced_cluster.go +++ b/internal/service/advancedcluster/data_source_advanced_cluster.go @@ -274,7 +274,7 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "encryption_at_rest_provider", clusterName, err)) } - if err := d.Set("labels", flattenLabels(RemoveLabel(clusterOld.Labels, defaultLabel))); err != nil { + if err := d.Set("labels", flattenLabels(cluster.GetLabels())); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "labels", clusterName, err)) } diff --git a/internal/service/advancedcluster/data_source_advanced_clusters.go b/internal/service/advancedcluster/data_source_advanced_clusters.go index f00306d7bf..56da3f1453 100644 --- a/internal/service/advancedcluster/data_source_advanced_clusters.go +++ b/internal/service/advancedcluster/data_source_advanced_clusters.go @@ -299,7 +299,7 @@ func flattenAdvancedClusters(ctx context.Context, conn *matlas.Client, connV2 *a "connection_strings": flattenConnectionStrings(clusterOld.ConnectionStrings), "disk_size_gb": cluster.GetDiskSizeGB(), "encryption_at_rest_provider": cluster.GetEncryptionAtRestProvider(), - "labels": flattenLabels(clusterOld.Labels), + "labels": flattenLabels(cluster.GetLabels()), "tags": conversion.FlattenTags(cluster.GetTags()), "mongo_db_major_version": cluster.GetMongoDBMajorVersion(), "mongo_db_version": cluster.GetMongoDBVersion(), diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index 20d07ed3f3..f202649c02 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -25,6 +25,7 @@ const ( ErrorAdvancedConfRead = "error reading Advanced Configuration Option form MongoDB Cluster (%s): %s" ErrorClusterAdvancedSetting = "error setting `%s` for MongoDB ClusterAdvanced (%s): %s" ErrorAdvancedClusterListStatus = "error awaiting MongoDB ClusterAdvanced List IDLE: %s" + ignoreLabel = "Infrastructure Tool" ) var ( @@ -63,25 +64,6 @@ var ( } ) -func RemoveLabel(list []matlas.Label, item matlas.Label) []matlas.Label { - var pos int - - for _, v := range list { - if reflect.DeepEqual(v, item) { - list = append(list[:pos], list[pos+1:]...) - - if pos > 0 { - pos-- - } - - continue - } - pos++ - } - - return list -} - func ContainsLabelOrKey(list []matlas.Label, item matlas.Label) bool { for _, v := range list { if reflect.DeepEqual(v, item) || v.Key == item.Key { @@ -211,17 +193,19 @@ func FormatMongoDBMajorVersion(val any) string { if strings.Contains(val.(string), ".") { return val.(string) } - return fmt.Sprintf("%.1f", cast.ToFloat32(val)) } -func flattenLabels(l []matlas.Label) []map[string]any { - labels := make([]map[string]any, len(l)) - for i, v := range l { - labels[i] = map[string]any{ - "key": v.Key, - "value": v.Value, +func flattenLabels(l []admin.ComponentLabel) []map[string]string { + labels := make([]map[string]string, 0, len(l)) + for _, item := range l { + if item.GetKey() == ignoreLabel { + continue } + labels = append(labels, map[string]string{ + "key": item.GetKey(), + "value": item.GetValue(), + }) } return labels } diff --git a/internal/service/advancedcluster/model_advanced_cluster_test.go b/internal/service/advancedcluster/model_advanced_cluster_test.go index 402e49450a..60edba75f8 100644 --- a/internal/service/advancedcluster/model_advanced_cluster_test.go +++ b/internal/service/advancedcluster/model_advanced_cluster_test.go @@ -5,7 +5,6 @@ import ( "net/http" "testing" - "github.com/go-test/deep" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/advancedcluster" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mocksvc" "github.com/stretchr/testify/assert" @@ -26,29 +25,6 @@ type Result struct { state string } -func TestRemoveLabel(t *testing.T) { - toRemove := matlas.Label{Key: "To Remove", Value: "To remove value"} - - expected := []matlas.Label{ - {Key: "Name", Value: "Test"}, - {Key: "Version", Value: "1.0"}, - {Key: "Type", Value: "testing"}, - } - - labels := []matlas.Label{ - {Key: "Name", Value: "Test"}, - {Key: "Version", Value: "1.0"}, - {Key: "To Remove", Value: "To remove value"}, - {Key: "Type", Value: "testing"}, - } - - got := advancedcluster.RemoveLabel(labels, toRemove) - - if diff := deep.Equal(expected, got); diff != nil { - t.Fatalf("Bad removeLabel return \n got = %#v\nwant = %#v \ndiff = %#v", got, expected, diff) - } -} - func TestResourceClusterRefreshFunc(t *testing.T) { testCases := []struct { mockCluster *matlas.Cluster diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 27232cedc9..c961643f55 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -526,7 +526,7 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "encryption_at_rest_provider", clusterName, err)) } - if err := d.Set("labels", flattenLabels(RemoveLabel(clusterOld.Labels, defaultLabel))); err != nil { + if err := d.Set("labels", flattenLabels(cluster.GetLabels())); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "labels", clusterName, err)) } From 5b8a27f3c1bc55d0ba98b4c16a5ddf1ca6bf5c45 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Sat, 17 Feb 2024 07:15:40 +0100 Subject: [PATCH 26/52] cluster and project random names --- ...esource_advanced_cluster_migration_test.go | 25 +- .../resource_advanced_cluster_test.go | 219 +++++++++--------- internal/testutil/acc/cluster.go | 6 +- internal/testutil/acc/name.go | 23 ++ 4 files changed, 146 insertions(+), 127 deletions(-) create mode 100644 internal/testutil/acc/name.go diff --git a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go index 0e3d5f71af..9104f7182b 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go @@ -4,7 +4,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" @@ -14,9 +13,9 @@ func TestAccMigrationAdvancedCluster_basic(t *testing.T) { // TEMPORARY: to delete, based on TestAccClusterAdvancedCluster_basicTenant var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - config = configTenant(orgID, projectName, rName) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + config = configTenant(orgID, projectName, clusterName) ) resource.ParallelTest(t, resource.TestCase{ @@ -29,7 +28,7 @@ func TestAccMigrationAdvancedCluster_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttrSet(resourceName, "termination_protection_enabled"), @@ -44,9 +43,9 @@ func TestAccMigrationAdvancedCluster_singleAWSProvider(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - config = configSingleProvider(orgID, projectName, rName) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + config = configSingleProvider(orgID, projectName, clusterName) ) resource.ParallelTest(t, resource.TestCase{ @@ -59,7 +58,7 @@ func TestAccMigrationAdvancedCluster_singleAWSProvider(t *testing.T) { Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "true"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), @@ -74,9 +73,9 @@ func TestAccMigrationAdvancedCluster_multiCloud(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - config = configMultiCloud(orgID, projectName, rName) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + config = configMultiCloud(orgID, projectName, clusterName) ) resource.ParallelTest(t, resource.TestCase{ @@ -89,7 +88,7 @@ func TestAccMigrationAdvancedCluster_multiCloud(t *testing.T) { Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 0aec6b5bfe..006578af48 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -7,7 +7,6 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -25,8 +24,8 @@ func TestAccClusterAdvancedCluster_basic(t *testing.T) { // TEMPORARY: to delete, based on TestAccClusterAdvancedCluster_basicTenant var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -35,15 +34,15 @@ func TestAccClusterAdvancedCluster_basic(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configTenant(orgID, projectName, rName), + Config: configTenant(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttrSet(resourceName, "termination_protection_enabled"), - resource.TestCheckResourceAttr(dataSourceName, "name", rName), + resource.TestCheckResourceAttr(dataSourceName, "name", clusterName), resource.TestCheckResourceAttr(dataSourceName, "termination_protection_enabled", "false"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), @@ -58,10 +57,10 @@ func TestAccClusterAdvancedCluster_basic(t *testing.T) { func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - rNameUpdated = acctest.RandomWithPrefix("test-acc") + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + clusterNameUpdated = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -70,15 +69,15 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configTenant(orgID, projectName, rName), + Config: configTenant(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttrSet(resourceName, "termination_protection_enabled"), - resource.TestCheckResourceAttr(dataSourceName, "name", rName), + resource.TestCheckResourceAttr(dataSourceName, "name", clusterName), resource.TestCheckResourceAttr(dataSourceName, "termination_protection_enabled", "false"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), @@ -87,15 +86,15 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { ), }, { - Config: configTenant(orgID, projectName, rNameUpdated), + Config: configTenant(orgID, projectName, clusterNameUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), + resource.TestCheckResourceAttr(resourceName, "name", clusterNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "labels.#", "0"), - resource.TestCheckResourceAttr(dataSourceName, "name", rNameUpdated), + resource.TestCheckResourceAttr(dataSourceName, "name", clusterNameUpdated), resource.TestCheckResourceAttr(dataSourceName, "termination_protection_enabled", "false"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), @@ -118,8 +117,8 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { var ( dataSourceName = fmt.Sprintf("data.%s", resourceName) orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -128,11 +127,11 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configSingleProvider(orgID, projectName, rName), + Config: configSingleProvider(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "true"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), @@ -141,11 +140,11 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { ), }, { - Config: configMultiCloud(orgID, projectName, rName), + Config: configMultiCloud(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), @@ -165,10 +164,10 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - rNameUpdated = acctest.RandomWithPrefix("test-acc") + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + clusterNameUpdated = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -177,33 +176,33 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configMultiCloud(orgID, projectName, rName), + Config: configMultiCloud(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), - resource.TestCheckResourceAttr(dataSourceName, "name", rName), + resource.TestCheckResourceAttr(dataSourceName, "name", clusterName), ), }, { - Config: configMultiCloud(orgID, projectName, rNameUpdated), + Config: configMultiCloud(orgID, projectName, clusterNameUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), + resource.TestCheckResourceAttr(resourceName, "name", clusterNameUpdated), resource.TestCheckResourceAttr(resourceName, "retain_backups_enabled", "false"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), - resource.TestCheckResourceAttr(dataSourceName, "name", rNameUpdated), + resource.TestCheckResourceAttr(dataSourceName, "name", clusterNameUpdated), ), }, { @@ -220,10 +219,10 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - rNameUpdated = acctest.RandomWithPrefix("test-acc") + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + clusterNameUpdated = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -232,21 +231,21 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configMultiCloudSharded(orgID, projectName, rName), + Config: configMultiCloudSharded(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), ), }, { - Config: configMultiCloudSharded(orgID, projectName, rNameUpdated), + Config: configMultiCloudSharded(orgID, projectName, clusterNameUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), + resource.TestCheckResourceAttr(resourceName, "name", clusterNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), ), @@ -266,8 +265,8 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() instanceSize = "M10" anotherInstanceSize = "M20" ) @@ -278,29 +277,29 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configSingleProviderPaused(orgID, projectName, rName, false, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, clusterName, false, instanceSize), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "paused", "false"), ), }, { - Config: configSingleProviderPaused(orgID, projectName, rName, true, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, clusterName, true, instanceSize), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "paused", "true"), ), }, { - Config: configSingleProviderPaused(orgID, projectName, rName, true, anotherInstanceSize), + Config: configSingleProviderPaused(orgID, projectName, clusterName, true, anotherInstanceSize), ExpectError: regexp.MustCompile("CANNOT_UPDATE_PAUSED_CLUSTER"), }, { @@ -318,8 +317,8 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() instanceSize = "M10" ) @@ -329,33 +328,33 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configSingleProviderPaused(orgID, projectName, rName, true, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, clusterName, true, instanceSize), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "paused", "true"), ), }, { - Config: configSingleProviderPaused(orgID, projectName, rName, false, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, clusterName, false, instanceSize), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "paused", "false"), ), }, { - Config: configSingleProviderPaused(orgID, projectName, rName, true, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, clusterName, true, instanceSize), ExpectError: regexp.MustCompile("CANNOT_PAUSE_RECENTLY_RESUMED_CLUSTER"), }, { - Config: configSingleProviderPaused(orgID, projectName, rName, false, instanceSize), + Config: configSingleProviderPaused(orgID, projectName, clusterName, false, instanceSize), }, { ResourceName: resourceName, @@ -371,11 +370,11 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - rNameUpdated = acctest.RandomWithPrefix("test-acc") - processArgs = &matlas.ProcessArgs{ + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + clusterNameUpdated = acc.RandomClusterName() + processArgs = &matlas.ProcessArgs{ DefaultReadConcern: "available", DefaultWriteConcern: "1", FailIndexKeyTooLong: conversion.Pointer(false), @@ -407,10 +406,10 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configAdvanced(orgID, projectName, rName, processArgs), + Config: configAdvanced(orgID, projectName, clusterName, processArgs), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.minimum_enabled_tls_protocol", "TLS1_1"), @@ -419,17 +418,17 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.sample_refresh_interval_bi_connector", "310"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.sample_size_bi_connector", "110"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.transaction_lifetime_limit_seconds", "300"), - resource.TestCheckResourceAttr(dataSourceName, "name", rName), + resource.TestCheckResourceAttr(dataSourceName, "name", clusterName), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), ), }, { - Config: configAdvanced(orgID, projectName, rNameUpdated, processArgsUpdated), + Config: configAdvanced(orgID, projectName, clusterNameUpdated, processArgsUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), + resource.TestCheckResourceAttr(resourceName, "name", clusterNameUpdated), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.minimum_enabled_tls_protocol", "TLS1_2"), @@ -438,7 +437,7 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.sample_refresh_interval_bi_connector", "310"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.sample_size_bi_connector", "110"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.transaction_lifetime_limit_seconds", "300"), - resource.TestCheckResourceAttr(dataSourceName, "name", rNameUpdated), + resource.TestCheckResourceAttr(dataSourceName, "name", clusterNameUpdated), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), @@ -451,11 +450,11 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - rNameUpdated = acctest.RandomWithPrefix("test-acc") - processArgs = &matlas.ProcessArgs{ + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + clusterNameUpdated = acc.RandomClusterName() + processArgs = &matlas.ProcessArgs{ DefaultReadConcern: "available", DefaultWriteConcern: "1", JavascriptEnabled: conversion.Pointer(true), @@ -484,10 +483,10 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configAdvancedDefaultWrite(orgID, projectName, rName, processArgs), + Config: configAdvancedDefaultWrite(orgID, projectName, clusterName, processArgs), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_read_concern", "available"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_write_concern", "1"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), @@ -500,10 +499,10 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { ), }, { - Config: configAdvancedDefaultWrite(orgID, projectName, rNameUpdated, processArgsUpdated), + Config: configAdvancedDefaultWrite(orgID, projectName, clusterNameUpdated, processArgsUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), + resource.TestCheckResourceAttr(resourceName, "name", clusterNameUpdated), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_read_concern", "available"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_write_concern", "majority"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), @@ -522,11 +521,11 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - rNameUpdated = acctest.RandomWithPrefix("test-acc") - autoScaling = &matlas.AutoScaling{ + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + clusterNameUpdated = acc.RandomClusterName() + autoScaling = &matlas.AutoScaling{ Compute: &matlas.Compute{Enabled: conversion.Pointer(false), MaxInstanceSize: ""}, DiskGBEnabled: conversion.Pointer(true), } @@ -542,19 +541,19 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configReplicationSpecsAutoScaling(orgID, projectName, rName, autoScaling), + Config: configReplicationSpecsAutoScaling(orgID, projectName, clusterName, autoScaling), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.auto_scaling.0.compute_enabled", "false"), ), }, { - Config: configReplicationSpecsAutoScaling(orgID, projectName, rNameUpdated, autoScalingUpdated), + Config: configReplicationSpecsAutoScaling(orgID, projectName, clusterNameUpdated, autoScalingUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), + resource.TestCheckResourceAttr(resourceName, "name", clusterNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.auto_scaling.0.compute_enabled", "true"), ), @@ -566,11 +565,11 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") - rNameUpdated = acctest.RandomWithPrefix("test-acc") - autoScaling = &matlas.AutoScaling{ + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + clusterNameUpdated = acc.RandomClusterName() + autoScaling = &matlas.AutoScaling{ Compute: &matlas.Compute{Enabled: conversion.Pointer(false), MaxInstanceSize: ""}, DiskGBEnabled: conversion.Pointer(true), } @@ -586,19 +585,19 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, rName, autoScaling), + Config: configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, clusterName, autoScaling), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.analytics_auto_scaling.0.compute_enabled", "false"), ), }, { - Config: configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, rNameUpdated, autoScalingUpdated), + Config: configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, clusterNameUpdated, autoScalingUpdated), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rNameUpdated), + resource.TestCheckResourceAttr(resourceName, "name", clusterNameUpdated), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.region_configs.0.analytics_auto_scaling.0.compute_enabled", "true"), ), @@ -611,8 +610,8 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() numShards = "1" numShardsUpdated = "2" ) @@ -623,19 +622,19 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configMultiZoneWithShards(orgID, projectName, rName, numShards, numShards), + Config: configMultiZoneWithShards(orgID, projectName, clusterName, numShards, numShards), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.num_shards", "1"), resource.TestCheckResourceAttr(resourceName, "replication_specs.1.num_shards", "1"), ), }, { - Config: configMultiZoneWithShards(orgID, projectName, rName, numShardsUpdated, numShards), + Config: configMultiZoneWithShards(orgID, projectName, clusterName, numShardsUpdated, numShards), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "replication_specs.0.num_shards", "2"), resource.TestCheckResourceAttr(resourceName, "replication_specs.1.num_shards", "1"), ), @@ -648,8 +647,8 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - rName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -658,19 +657,19 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configWithTags(orgID, projectName, rName, []matlas.Tag{}), + Config: configWithTags(orgID, projectName, clusterName, []matlas.Tag{}), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "tags.#", "0"), resource.TestCheckResourceAttr(dataSourceName, "tags.#", "0"), resource.TestCheckResourceAttr(dataSourcePluralName, "results.0.tags.#", "0"), ), }, { - Config: configWithTags(orgID, projectName, rName, []matlas.Tag{ + Config: configWithTags(orgID, projectName, clusterName, []matlas.Tag{ { Key: "key 1", Value: "value 1", @@ -682,9 +681,9 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { }), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "tags.#", "2"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tags.*", acc.ClusterTagsMap1), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tags.*", acc.ClusterTagsMap2), @@ -697,7 +696,7 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { ), }, { - Config: configWithTags(orgID, projectName, rName, []matlas.Tag{ + Config: configWithTags(orgID, projectName, clusterName, []matlas.Tag{ { Key: "key 3", Value: "value 3", @@ -705,9 +704,9 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { }), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "tags.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tags.*", acc.ClusterTagsMap3), resource.TestCheckResourceAttr(dataSourceName, "tags.#", "1"), diff --git a/internal/testutil/acc/cluster.go b/internal/testutil/acc/cluster.go index 342027941b..83db24ce72 100644 --- a/internal/testutil/acc/cluster.go +++ b/internal/testutil/acc/cluster.go @@ -3,8 +3,6 @@ package acc import ( "fmt" "os" - - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" ) type ClusterRequest struct { @@ -40,8 +38,8 @@ func GetClusterInfo(req *ClusterRequest) ClusterInfo { ClusterTerraformStr: "", } } - clusterName = acctest.RandomWithPrefix("test-acc") - projectName := acctest.RandomWithPrefix("test-acc") + projectName := RandomProjectName() + clusterName = RandomClusterName() clusterTypeStr := "REPLICASET" if req.Geosharded { clusterTypeStr = "GEOSHARDED" diff --git a/internal/testutil/acc/name.go b/internal/testutil/acc/name.go new file mode 100644 index 0000000000..0039b9d0ff --- /dev/null +++ b/internal/testutil/acc/name.go @@ -0,0 +1,23 @@ +package acc + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" +) + +const ( + prefixName = "test-acc-tf" + prefixProject = prefixName + "-p" + prefixCluster = prefixName + "-c" +) + +func RandomName() string { + return acctest.RandomWithPrefix(prefixName) +} + +func RandomProjectName() string { + return acctest.RandomWithPrefix(prefixProject) +} + +func RandomClusterName() string { + return acctest.RandomWithPrefix(prefixCluster) +} From 5412441e21a79857e67b263cc3314d3e2d23ac84 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Sat, 17 Feb 2024 07:52:32 +0100 Subject: [PATCH 27/52] flattenBiConnectorConfig --- .../service/advancedcluster/data_source_advanced_cluster.go | 2 +- .../advancedcluster/data_source_advanced_clusters.go | 2 +- internal/service/advancedcluster/model_advanced_cluster.go | 6 +++--- .../service/advancedcluster/resource_advanced_cluster.go | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/internal/service/advancedcluster/data_source_advanced_cluster.go b/internal/service/advancedcluster/data_source_advanced_cluster.go index 2c624f89bb..59672d99dc 100644 --- a/internal/service/advancedcluster/data_source_advanced_cluster.go +++ b/internal/service/advancedcluster/data_source_advanced_cluster.go @@ -250,7 +250,7 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "backup_enabled", clusterName, err)) } - if err := d.Set("bi_connector_config", flattenBiConnectorConfig(clusterOld.BiConnector)); err != nil { + if err := d.Set("bi_connector_config", flattenBiConnectorConfig(cluster.GetBiConnector())); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "bi_connector_config", clusterName, err)) } diff --git a/internal/service/advancedcluster/data_source_advanced_clusters.go b/internal/service/advancedcluster/data_source_advanced_clusters.go index 56da3f1453..b84b20223b 100644 --- a/internal/service/advancedcluster/data_source_advanced_clusters.go +++ b/internal/service/advancedcluster/data_source_advanced_clusters.go @@ -293,7 +293,7 @@ func flattenAdvancedClusters(ctx context.Context, conn *matlas.Client, connV2 *a result := map[string]any{ "advanced_configuration": flattenProcessArgs(processArgs), "backup_enabled": cluster.GetBackupEnabled(), - "bi_connector_config": flattenBiConnectorConfig(clusterOld.BiConnector), + "bi_connector_config": flattenBiConnectorConfig(cluster.GetBiConnector()), "cluster_type": cluster.GetClusterType(), "create_date": conversion.TimePtrToStringPtr(cluster.CreateDate), "connection_strings": flattenConnectionStrings(clusterOld.ConnectionStrings), diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index ff24617213..782b9e2e6e 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -224,11 +224,11 @@ func flattenConnectionStrings(connectionStrings *matlas.ConnectionStrings) []map return connections } -func flattenBiConnectorConfig(biConnector *matlas.BiConnector) []any { +func flattenBiConnectorConfig(biConnector admin.BiConnector) []any { return []any{ map[string]any{ - "enabled": *biConnector.Enabled, - "read_preference": biConnector.ReadPreference, + "enabled": biConnector.GetEnabled(), + "read_preference": biConnector.GetReadPreference(), }, } } diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 8e6d66a6ea..9745455895 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -501,7 +501,7 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "backup_enabled", clusterName, err)) } - if err := d.Set("bi_connector_config", flattenBiConnectorConfig(clusterOld.BiConnector)); err != nil { + if err := d.Set("bi_connector_config", flattenBiConnectorConfig(cluster.GetBiConnector())); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "bi_connector_config", clusterName, err)) } From 1ab9b2fcdfde16c437a246011434a1fc9fddb6c3 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Sat, 17 Feb 2024 08:05:56 +0100 Subject: [PATCH 28/52] flattenConnectionStrings --- .../data_source_advanced_cluster.go | 2 +- .../data_source_advanced_clusters.go | 2 +- .../advancedcluster/model_advanced_cluster.go | 80 +++++++++---------- .../resource_advanced_cluster.go | 2 +- 4 files changed, 42 insertions(+), 44 deletions(-) diff --git a/internal/service/advancedcluster/data_source_advanced_cluster.go b/internal/service/advancedcluster/data_source_advanced_cluster.go index 59672d99dc..55b1216986 100644 --- a/internal/service/advancedcluster/data_source_advanced_cluster.go +++ b/internal/service/advancedcluster/data_source_advanced_cluster.go @@ -258,7 +258,7 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "cluster_type", clusterName, err)) } - if err := d.Set("connection_strings", flattenConnectionStrings(clusterOld.ConnectionStrings)); err != nil { + if err := d.Set("connection_strings", flattenConnectionStrings(cluster.GetConnectionStrings())); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "connection_strings", clusterName, err)) } diff --git a/internal/service/advancedcluster/data_source_advanced_clusters.go b/internal/service/advancedcluster/data_source_advanced_clusters.go index b84b20223b..91e3648c35 100644 --- a/internal/service/advancedcluster/data_source_advanced_clusters.go +++ b/internal/service/advancedcluster/data_source_advanced_clusters.go @@ -296,7 +296,7 @@ func flattenAdvancedClusters(ctx context.Context, conn *matlas.Client, connV2 *a "bi_connector_config": flattenBiConnectorConfig(cluster.GetBiConnector()), "cluster_type": cluster.GetClusterType(), "create_date": conversion.TimePtrToStringPtr(cluster.CreateDate), - "connection_strings": flattenConnectionStrings(clusterOld.ConnectionStrings), + "connection_strings": flattenConnectionStrings(cluster.GetConnectionStrings()), "disk_size_gb": cluster.GetDiskSizeGB(), "encryption_at_rest_provider": cluster.GetEncryptionAtRestProvider(), "labels": flattenLabels(cluster.GetLabels()), diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index 782b9e2e6e..45bb91f139 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -210,23 +210,47 @@ func flattenLabels(l []admin.ComponentLabel) []map[string]string { return labels } -func flattenConnectionStrings(connectionStrings *matlas.ConnectionStrings) []map[string]any { - connections := make([]map[string]any, 0) - - connections = append(connections, map[string]any{ - "standard": connectionStrings.Standard, - "standard_srv": connectionStrings.StandardSrv, - "private": connectionStrings.Private, - "private_srv": connectionStrings.PrivateSrv, - "private_endpoint": flattenPrivateEndpoint(connectionStrings.PrivateEndpoint), - }) - - return connections +func flattenConnectionStrings(str admin.ClusterConnectionStrings) []map[string]any { + return []map[string]any{ + { + "standard": str.GetStandard(), + "standard_srv": str.GetStandardSrv(), + "private": str.GetPrivate(), + "private_srv": str.GetPrivateSrv(), + "private_endpoint": flattenPrivateEndpoint(str.GetPrivateEndpoint()), + }, + } +} + +func flattenPrivateEndpoint(privateEndpoints []admin.ClusterDescriptionConnectionStringsPrivateEndpoint) []map[string]any { + endpoints := make([]map[string]any, 0, len(privateEndpoints)) + for _, endpoint := range privateEndpoints { + endpoints = append(endpoints, map[string]any{ + "connection_string": endpoint.GetConnectionString(), + "srv_connection_string": endpoint.GetSrvConnectionString(), + "srv_shard_optimized_connection_string": endpoint.GetSrvShardOptimizedConnectionString(), + "type": endpoint.GetType(), + "endpoints": flattenEndpoints(endpoint.GetEndpoints()), + }) + } + return endpoints +} + +func flattenEndpoints(listEndpoints []admin.ClusterDescriptionConnectionStringsPrivateEndpointEndpoint) []map[string]any { + endpoints := make([]map[string]any, 0, len(listEndpoints)) + for _, endpoint := range listEndpoints { + endpoints = append(endpoints, map[string]any{ + "region": endpoint.GetRegion(), + "provider_name": endpoint.GetProviderName(), + "endpoint_id": endpoint.GetEndpointId(), + }) + } + return endpoints } -func flattenBiConnectorConfig(biConnector admin.BiConnector) []any { - return []any{ - map[string]any{ +func flattenBiConnectorConfig(biConnector admin.BiConnector) []map[string]any { + return []map[string]any{ + { "enabled": biConnector.GetEnabled(), "read_preference": biConnector.GetReadPreference(), }, @@ -561,32 +585,6 @@ func SchemaAdvancedConfig() *schema.Schema { } } -func flattenPrivateEndpoint(privateEndpoints []matlas.PrivateEndpoint) []map[string]any { - endpoints := make([]map[string]any, 0) - for _, endpoint := range privateEndpoints { - endpoints = append(endpoints, map[string]any{ - "connection_string": endpoint.ConnectionString, - "srv_connection_string": endpoint.SRVConnectionString, - "srv_shard_optimized_connection_string": endpoint.SRVShardOptimizedConnectionString, - "endpoints": flattenEndpoints(endpoint.Endpoints), - "type": endpoint.Type, - }) - } - return endpoints -} - -func flattenEndpoints(listEndpoints []matlas.Endpoint) []map[string]any { - endpoints := make([]map[string]any, 0) - for _, endpoint := range listEndpoints { - endpoints = append(endpoints, map[string]any{ - "region": endpoint.Region, - "provider_name": endpoint.ProviderName, - "endpoint_id": endpoint.EndpointID, - }) - } - return endpoints -} - func StringIsUppercase() schema.SchemaValidateDiagFunc { return func(v any, p cty.Path) diag.Diagnostics { value := v.(string) diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 9745455895..b9821acbba 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -509,7 +509,7 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "cluster_type", clusterName, err)) } - if err := d.Set("connection_strings", flattenConnectionStrings(clusterOld.ConnectionStrings)); err != nil { + if err := d.Set("connection_strings", flattenConnectionStrings(cluster.GetConnectionStrings())); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "connection_strings", clusterName, err)) } From cb55b01b430b46a4cbc12ca63d108cba32268409 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Sat, 17 Feb 2024 08:16:14 +0100 Subject: [PATCH 29/52] function reorg --- .../advancedcluster/model_advanced_cluster.go | 495 ++++++++++-------- .../resource_advanced_cluster.go | 71 --- 2 files changed, 283 insertions(+), 283 deletions(-) diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index 45bb91f139..6e525fa220 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -7,6 +7,7 @@ import ( "hash/crc32" "log" "reflect" + "slices" "strings" "time" @@ -64,6 +65,218 @@ var ( } ) +func SchemaAdvancedConfigDS() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "default_read_concern": { + Type: schema.TypeString, + Computed: true, + }, + "default_write_concern": { + Type: schema.TypeString, + Computed: true, + }, + "fail_index_key_too_long": { + Type: schema.TypeBool, + Computed: true, + }, + "javascript_enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "minimum_enabled_tls_protocol": { + Type: schema.TypeString, + Computed: true, + }, + "no_table_scan": { + Type: schema.TypeBool, + Computed: true, + }, + "oplog_size_mb": { + Type: schema.TypeInt, + Computed: true, + }, + "sample_size_bi_connector": { + Type: schema.TypeInt, + Computed: true, + }, + "sample_refresh_interval_bi_connector": { + Type: schema.TypeInt, + Computed: true, + }, + "oplog_min_retention_hours": { + Type: schema.TypeInt, + Computed: true, + }, + "transaction_lifetime_limit_seconds": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + } +} + +func SchemaConnectionStrings() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Computed: true, + ConfigMode: schema.SchemaConfigModeAttr, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "standard": { + Type: schema.TypeString, + Computed: true, + }, + "standard_srv": { + Type: schema.TypeString, + Computed: true, + }, + "private": { + Type: schema.TypeString, + Computed: true, + }, + "private_srv": { + Type: schema.TypeString, + Computed: true, + }, + "private_endpoint": { + Type: schema.TypeList, + Computed: true, + ConfigMode: schema.SchemaConfigModeAttr, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "connection_string": { + Type: schema.TypeString, + Computed: true, + }, + "endpoints": { + Type: schema.TypeList, + Computed: true, + ConfigMode: schema.SchemaConfigModeAttr, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "endpoint_id": { + Type: schema.TypeString, + Computed: true, + }, + "provider_name": { + Type: schema.TypeString, + Computed: true, + }, + "region": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "srv_connection_string": { + Type: schema.TypeString, + Computed: true, + }, + "srv_shard_optimized_connection_string": { + Type: schema.TypeString, + Computed: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + } +} + +func SchemaAdvancedConfig() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Computed: true, + ConfigMode: schema.SchemaConfigModeAttr, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "default_read_concern": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "default_write_concern": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "fail_index_key_too_long": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + "javascript_enabled": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + "minimum_enabled_tls_protocol": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "no_table_scan": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + "oplog_size_mb": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "oplog_min_retention_hours": { + Type: schema.TypeInt, + Optional: true, + }, + "sample_size_bi_connector": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "sample_refresh_interval_bi_connector": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "transaction_lifetime_limit_seconds": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + }, + }, + } +} + +func StringIsUppercase() schema.SchemaValidateDiagFunc { + return func(v any, p cty.Path) diag.Diagnostics { + value := v.(string) + var diags diag.Diagnostics + if value != strings.ToUpper(value) { + diagError := diag.Diagnostic{ + Severity: diag.Error, + Summary: fmt.Sprintf("The provided string '%q' must be uppercase.", value), + } + diags = append(diags, diagError) + } + return diags + } +} + func ContainsLabelOrKey(list []matlas.Label, item matlas.Label) bool { for _, v := range list { if reflect.DeepEqual(v, item) || v.Key == item.Key { @@ -311,6 +524,76 @@ func flattenProcessArgs(p *admin.ClusterDescriptionProcessArgs) []map[string]any } } +func flattenAdvancedReplicationSpecs(ctx context.Context, rawAPIObjects []*matlas.AdvancedReplicationSpec, tfMapObjects []any, + d *schema.ResourceData, conn *matlas.Client) ([]map[string]any, error) { + var apiObjects []*matlas.AdvancedReplicationSpec + + for _, advancedReplicationSpec := range rawAPIObjects { + if advancedReplicationSpec != nil { + apiObjects = append(apiObjects, advancedReplicationSpec) + } + } + + if len(apiObjects) == 0 { + return nil, nil + } + + tfList := make([]map[string]any, len(apiObjects)) + wasAPIObjectUsed := make([]bool, len(apiObjects)) + + for i := 0; i < len(tfList); i++ { + var tfMapObject map[string]any + + if len(tfMapObjects) > i { + tfMapObject = tfMapObjects[i].(map[string]any) + } + + for j := 0; j < len(apiObjects); j++ { + if wasAPIObjectUsed[j] { + continue + } + + if !doesAdvancedReplicationSpecMatchAPI(tfMapObject, apiObjects[j]) { + continue + } + + advancedReplicationSpec, err := flattenAdvancedReplicationSpec(ctx, apiObjects[j], tfMapObject, d, conn) + + if err != nil { + return nil, err + } + + tfList[i] = advancedReplicationSpec + wasAPIObjectUsed[j] = true + break + } + } + + for i, tfo := range tfList { + var tfMapObject map[string]any + + if tfo != nil { + continue + } + + if len(tfMapObjects) > i { + tfMapObject = tfMapObjects[i].(map[string]any) + } + + j := slices.IndexFunc(wasAPIObjectUsed, func(isUsed bool) bool { return !isUsed }) + advancedReplicationSpec, err := flattenAdvancedReplicationSpec(ctx, apiObjects[j], tfMapObject, d, conn) + + if err != nil { + return nil, err + } + + tfList[i] = advancedReplicationSpec + wasAPIObjectUsed[j] = true + } + + return tfList, nil +} + func expandProcessArgs(d *schema.ResourceData, p map[string]any) *matlas.ProcessArgs { res := &matlas.ProcessArgs{} @@ -387,215 +670,3 @@ func expandLabelSliceFromSetSchema(d *schema.ResourceData) []matlas.Label { return res } - -func SchemaAdvancedConfigDS() *schema.Schema { - return &schema.Schema{ - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "default_read_concern": { - Type: schema.TypeString, - Computed: true, - }, - "default_write_concern": { - Type: schema.TypeString, - Computed: true, - }, - "fail_index_key_too_long": { - Type: schema.TypeBool, - Computed: true, - }, - "javascript_enabled": { - Type: schema.TypeBool, - Computed: true, - }, - "minimum_enabled_tls_protocol": { - Type: schema.TypeString, - Computed: true, - }, - "no_table_scan": { - Type: schema.TypeBool, - Computed: true, - }, - "oplog_size_mb": { - Type: schema.TypeInt, - Computed: true, - }, - "sample_size_bi_connector": { - Type: schema.TypeInt, - Computed: true, - }, - "sample_refresh_interval_bi_connector": { - Type: schema.TypeInt, - Computed: true, - }, - "oplog_min_retention_hours": { - Type: schema.TypeInt, - Computed: true, - }, - "transaction_lifetime_limit_seconds": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - } -} - -func SchemaConnectionStrings() *schema.Schema { - return &schema.Schema{ - Type: schema.TypeList, - Computed: true, - ConfigMode: schema.SchemaConfigModeAttr, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "standard": { - Type: schema.TypeString, - Computed: true, - }, - "standard_srv": { - Type: schema.TypeString, - Computed: true, - }, - "private": { - Type: schema.TypeString, - Computed: true, - }, - "private_srv": { - Type: schema.TypeString, - Computed: true, - }, - "private_endpoint": { - Type: schema.TypeList, - Computed: true, - ConfigMode: schema.SchemaConfigModeAttr, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "connection_string": { - Type: schema.TypeString, - Computed: true, - }, - "endpoints": { - Type: schema.TypeList, - Computed: true, - ConfigMode: schema.SchemaConfigModeAttr, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "endpoint_id": { - Type: schema.TypeString, - Computed: true, - }, - "provider_name": { - Type: schema.TypeString, - Computed: true, - }, - "region": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "srv_connection_string": { - Type: schema.TypeString, - Computed: true, - }, - "srv_shard_optimized_connection_string": { - Type: schema.TypeString, - Computed: true, - }, - "type": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - }, - }, - } -} - -func SchemaAdvancedConfig() *schema.Schema { - return &schema.Schema{ - Type: schema.TypeList, - Optional: true, - Computed: true, - ConfigMode: schema.SchemaConfigModeAttr, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "default_read_concern": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - "default_write_concern": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - "fail_index_key_too_long": { - Type: schema.TypeBool, - Optional: true, - Computed: true, - }, - "javascript_enabled": { - Type: schema.TypeBool, - Optional: true, - Computed: true, - }, - "minimum_enabled_tls_protocol": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - "no_table_scan": { - Type: schema.TypeBool, - Optional: true, - Computed: true, - }, - "oplog_size_mb": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "oplog_min_retention_hours": { - Type: schema.TypeInt, - Optional: true, - }, - "sample_size_bi_connector": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "sample_refresh_interval_bi_connector": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - "transaction_lifetime_limit_seconds": { - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - }, - }, - } -} - -func StringIsUppercase() schema.SchemaValidateDiagFunc { - return func(v any, p cty.Path) diag.Diagnostics { - value := v.(string) - var diags diag.Diagnostics - if value != strings.ToUpper(value) { - diagError := diag.Diagnostic{ - Severity: diag.Error, - Summary: fmt.Sprintf("The provided string '%q' must be uppercase.", value), - } - diags = append(diags, diagError) - } - return diags - } -} diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index b9821acbba..a9a2a5caa7 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -21,7 +21,6 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "github.com/spf13/cast" matlas "go.mongodb.org/atlas/mongodbatlas" - "golang.org/x/exp/slices" ) const ( @@ -1028,76 +1027,6 @@ func doesAdvancedReplicationSpecMatchAPI(tfObject map[string]any, apiObject *mat return tfObject["id"] == apiObject.ID || (tfObject["id"] == nil && tfObject["zone_name"] == apiObject.ZoneName) } -func flattenAdvancedReplicationSpecs(ctx context.Context, rawAPIObjects []*matlas.AdvancedReplicationSpec, tfMapObjects []any, - d *schema.ResourceData, conn *matlas.Client) ([]map[string]any, error) { - var apiObjects []*matlas.AdvancedReplicationSpec - - for _, advancedReplicationSpec := range rawAPIObjects { - if advancedReplicationSpec != nil { - apiObjects = append(apiObjects, advancedReplicationSpec) - } - } - - if len(apiObjects) == 0 { - return nil, nil - } - - tfList := make([]map[string]any, len(apiObjects)) - wasAPIObjectUsed := make([]bool, len(apiObjects)) - - for i := 0; i < len(tfList); i++ { - var tfMapObject map[string]any - - if len(tfMapObjects) > i { - tfMapObject = tfMapObjects[i].(map[string]any) - } - - for j := 0; j < len(apiObjects); j++ { - if wasAPIObjectUsed[j] { - continue - } - - if !doesAdvancedReplicationSpecMatchAPI(tfMapObject, apiObjects[j]) { - continue - } - - advancedReplicationSpec, err := flattenAdvancedReplicationSpec(ctx, apiObjects[j], tfMapObject, d, conn) - - if err != nil { - return nil, err - } - - tfList[i] = advancedReplicationSpec - wasAPIObjectUsed[j] = true - break - } - } - - for i, tfo := range tfList { - var tfMapObject map[string]any - - if tfo != nil { - continue - } - - if len(tfMapObjects) > i { - tfMapObject = tfMapObjects[i].(map[string]any) - } - - j := slices.IndexFunc(wasAPIObjectUsed, func(isUsed bool) bool { return !isUsed }) - advancedReplicationSpec, err := flattenAdvancedReplicationSpec(ctx, apiObjects[j], tfMapObject, d, conn) - - if err != nil { - return nil, err - } - - tfList[i] = advancedReplicationSpec - wasAPIObjectUsed[j] = true - } - - return tfList, nil -} - func flattenAdvancedReplicationSpecRegionConfig(apiObject *matlas.AdvancedRegionConfig, tfMapObject map[string]any) map[string]any { if apiObject == nil { return nil From 50594ec240dcf15841eadc8b22a31af1030133a1 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Sat, 17 Feb 2024 13:25:27 +0100 Subject: [PATCH 30/52] finish read & ds --- .../data_source_advanced_cluster.go | 5 +- .../data_source_advanced_clusters.go | 23 +- .../advancedcluster/model_advanced_cluster.go | 210 ++++++++++++++++-- .../resource_advanced_cluster.go | 190 +--------------- 4 files changed, 202 insertions(+), 226 deletions(-) diff --git a/internal/service/advancedcluster/data_source_advanced_cluster.go b/internal/service/advancedcluster/data_source_advanced_cluster.go index 55b1216986..f63f2f583e 100644 --- a/internal/service/advancedcluster/data_source_advanced_cluster.go +++ b/internal/service/advancedcluster/data_source_advanced_cluster.go @@ -231,14 +231,11 @@ func DataSource() *schema.Resource { } func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) clusterName := d.Get("name").(string) cluster, resp, err := connV2.ClustersApi.GetCluster(ctx, projectID, clusterName).Execute() - clusterOld, _, _ := conn.AdvancedClusters.Get(ctx, projectID, clusterName) - if err != nil { if resp != nil && resp.StatusCode == http.StatusNotFound { return nil @@ -302,7 +299,7 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "pit_enabled", clusterName, err)) } - replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, clusterOld.ReplicationSpecs, d.Get("replication_specs").(*schema.Set).List(), d, conn) + replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, cluster.GetReplicationSpecs(), d.Get("replication_specs").(*schema.Set).List(), d, connV2) if err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "replication_specs", clusterName, err)) } diff --git a/internal/service/advancedcluster/data_source_advanced_clusters.go b/internal/service/advancedcluster/data_source_advanced_clusters.go index 91e3648c35..2b5333a949 100644 --- a/internal/service/advancedcluster/data_source_advanced_clusters.go +++ b/internal/service/advancedcluster/data_source_advanced_clusters.go @@ -13,7 +13,6 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "go.mongodb.org/atlas-sdk/v20231115006/admin" - matlas "go.mongodb.org/atlas/mongodbatlas" ) func PluralDataSource() *schema.Resource { @@ -243,49 +242,33 @@ func PluralDataSource() *schema.Resource { } func dataSourcePluralRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) d.SetId(id.UniqueId()) list, resp, err := connV2.ClustersApi.ListClusters(ctx, projectID).Execute() - listOld, _, _ := conn.AdvancedClusters.List(ctx, projectID, nil) if err != nil { if resp != nil && resp.StatusCode == http.StatusNotFound { return nil } return diag.FromErr(fmt.Errorf("error reading advanced cluster list for project(%s): %s", projectID, err)) } - if len(list.GetResults()) == 0 || len(listOld.Results) == 0 { - return nil - } - - if err := d.Set("results", flattenAdvancedClusters(ctx, conn, connV2, list.GetResults(), listOld.Results, d)); err != nil { + if err := d.Set("results", flattenAdvancedClusters(ctx, connV2, list.GetResults(), d)); err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "results", d.Id(), err)) } return nil } -func flattenAdvancedClusters(ctx context.Context, conn *matlas.Client, connV2 *admin.APIClient, clusters []admin.AdvancedClusterDescription, clustersOld []*matlas.AdvancedCluster, d *schema.ResourceData) []map[string]any { +func flattenAdvancedClusters(ctx context.Context, connV2 *admin.APIClient, clusters []admin.AdvancedClusterDescription, d *schema.ResourceData) []map[string]any { results := make([]map[string]any, 0, len(clusters)) for i := range clusters { cluster := &clusters[i] - var clusterOld *matlas.AdvancedCluster - for j := range clustersOld { - if clustersOld[j].ID == cluster.GetId() { - clusterOld = clustersOld[j] - break - } - } - if clusterOld == nil { - continue - } processArgs, _, err := connV2.ClustersApi.GetClusterAdvancedConfiguration(ctx, cluster.GetGroupId(), cluster.GetName()).Execute() if err != nil { log.Printf("[WARN] Error setting `advanced_configuration` for the cluster(%s): %s", cluster.GetId(), err) } - replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, clusterOld.ReplicationSpecs, nil, d, conn) + replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, cluster.GetReplicationSpecs(), nil, d, connV2) if err != nil { log.Printf("[WARN] Error setting `replication_specs` for the cluster(%s): %s", cluster.GetId(), err) } diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index 6e525fa220..a4bdbffab5 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -15,6 +15,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/constant" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/spf13/cast" "go.mongodb.org/atlas-sdk/v20231115006/admin" @@ -524,16 +525,8 @@ func flattenProcessArgs(p *admin.ClusterDescriptionProcessArgs) []map[string]any } } -func flattenAdvancedReplicationSpecs(ctx context.Context, rawAPIObjects []*matlas.AdvancedReplicationSpec, tfMapObjects []any, - d *schema.ResourceData, conn *matlas.Client) ([]map[string]any, error) { - var apiObjects []*matlas.AdvancedReplicationSpec - - for _, advancedReplicationSpec := range rawAPIObjects { - if advancedReplicationSpec != nil { - apiObjects = append(apiObjects, advancedReplicationSpec) - } - } - +func flattenAdvancedReplicationSpecs(ctx context.Context, apiObjects []admin.ReplicationSpec, tfMapObjects []any, + d *schema.ResourceData, connV2 *admin.APIClient) ([]map[string]any, error) { if len(apiObjects) == 0 { return nil, nil } @@ -553,11 +546,11 @@ func flattenAdvancedReplicationSpecs(ctx context.Context, rawAPIObjects []*matla continue } - if !doesAdvancedReplicationSpecMatchAPI(tfMapObject, apiObjects[j]) { + if !doesAdvancedReplicationSpecMatchAPI(tfMapObject, &apiObjects[j]) { continue } - advancedReplicationSpec, err := flattenAdvancedReplicationSpec(ctx, apiObjects[j], tfMapObject, d, conn) + advancedReplicationSpec, err := flattenAdvancedReplicationSpec(ctx, &apiObjects[j], tfMapObject, d, connV2) if err != nil { return nil, err @@ -581,7 +574,7 @@ func flattenAdvancedReplicationSpecs(ctx context.Context, rawAPIObjects []*matla } j := slices.IndexFunc(wasAPIObjectUsed, func(isUsed bool) bool { return !isUsed }) - advancedReplicationSpec, err := flattenAdvancedReplicationSpec(ctx, apiObjects[j], tfMapObject, d, conn) + advancedReplicationSpec, err := flattenAdvancedReplicationSpec(ctx, &apiObjects[j], tfMapObject, d, connV2) if err != nil { return nil, err @@ -594,6 +587,197 @@ func flattenAdvancedReplicationSpecs(ctx context.Context, rawAPIObjects []*matla return tfList, nil } +func doesAdvancedReplicationSpecMatchAPI(tfObject map[string]any, apiObject *admin.ReplicationSpec) bool { + return tfObject["id"] == apiObject.GetId() || (tfObject["id"] == nil && tfObject["zone_name"] == apiObject.GetZoneName()) +} + +func flattenAdvancedReplicationSpec(ctx context.Context, apiObject *admin.ReplicationSpec, tfMapObject map[string]any, + d *schema.ResourceData, connV2 *admin.APIClient) (map[string]any, error) { + if apiObject == nil { + return nil, nil + } + + tfMap := map[string]any{} + tfMap["num_shards"] = apiObject.GetNumShards() + tfMap["id"] = apiObject.GetId() + if tfMapObject != nil { + object, containerIDs, err := flattenAdvancedReplicationSpecRegionConfigs(ctx, apiObject.GetRegionConfigs(), tfMapObject["region_configs"].([]any), d, connV2) + if err != nil { + return nil, err + } + tfMap["region_configs"] = object + tfMap["container_id"] = containerIDs + } else { + object, containerIDs, err := flattenAdvancedReplicationSpecRegionConfigs(ctx, apiObject.GetRegionConfigs(), nil, d, connV2) + if err != nil { + return nil, err + } + tfMap["region_configs"] = object + tfMap["container_id"] = containerIDs + } + tfMap["zone_name"] = apiObject.GetZoneName() + + return tfMap, nil +} + +func flattenAdvancedReplicationSpecRegionConfigs(ctx context.Context, apiObjects []admin.CloudRegionConfig, tfMapObjects []any, + d *schema.ResourceData, connV2 *admin.APIClient) (tfResult []map[string]any, containersIDs map[string]string, err error) { + if len(apiObjects) == 0 { + return nil, nil, nil + } + + var tfList []map[string]any + containerIDs := make(map[string]string) + + for i := range apiObjects { + apiObject := apiObjects[i] + if len(tfMapObjects) > i { + tfMapObject := tfMapObjects[i].(map[string]any) + tfList = append(tfList, flattenAdvancedReplicationSpecRegionConfig(&apiObject, tfMapObject)) + } else { + tfList = append(tfList, flattenAdvancedReplicationSpecRegionConfig(&apiObject, nil)) + } + + if apiObject.GetProviderName() != "TENANT" { + params := &admin.ListPeeringContainerByCloudProviderApiParams{ + GroupId: d.Get("project_id").(string), + ProviderName: apiObject.ProviderName, + } + containers, _, err := connV2.NetworkPeeringApi.ListPeeringContainerByCloudProviderWithParams(ctx, params).Execute() + if err != nil { + return nil, nil, err + } + if result := getAdvancedClusterContainerID(containers.GetResults(), &apiObject); result != "" { + // Will print as "providerName:regionName" = "containerId" in terraform show + containerIDs[fmt.Sprintf("%s:%s", apiObject.GetProviderName(), apiObject.GetRegionName())] = result + } + } + } + return tfList, containerIDs, nil +} + +func flattenAdvancedReplicationSpecRegionConfig(apiObject *admin.CloudRegionConfig, tfMapObject map[string]any) map[string]any { + if apiObject == nil { + return nil + } + + tfMap := map[string]any{} + if tfMapObject != nil { + if v, ok := tfMapObject["analytics_specs"]; ok && len(v.([]any)) > 0 { + tfMap["analytics_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(apiObject.AnalyticsSpecs, apiObject.GetProviderName(), tfMapObject["analytics_specs"].([]any)) + } + if v, ok := tfMapObject["electable_specs"]; ok && len(v.([]any)) > 0 { + tfMap["electable_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(hwSpecToDedicatedHwSpec(apiObject.ElectableSpecs), apiObject.GetProviderName(), tfMapObject["electable_specs"].([]any)) + } + if v, ok := tfMapObject["read_only_specs"]; ok && len(v.([]any)) > 0 { + tfMap["read_only_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(apiObject.ReadOnlySpecs, apiObject.GetProviderName(), tfMapObject["read_only_specs"].([]any)) + } + if v, ok := tfMapObject["auto_scaling"]; ok && len(v.([]any)) > 0 { + tfMap["auto_scaling"] = flattenAdvancedReplicationSpecAutoScaling(apiObject.AutoScaling) + } + if v, ok := tfMapObject["analytics_auto_scaling"]; ok && len(v.([]any)) > 0 { + tfMap["analytics_auto_scaling"] = flattenAdvancedReplicationSpecAutoScaling(apiObject.AnalyticsAutoScaling) + } + } else { + tfMap["analytics_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(apiObject.AnalyticsSpecs, apiObject.GetProviderName(), nil) + tfMap["electable_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(hwSpecToDedicatedHwSpec(apiObject.ElectableSpecs), apiObject.GetProviderName(), nil) + tfMap["read_only_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(apiObject.ReadOnlySpecs, apiObject.GetProviderName(), nil) + tfMap["auto_scaling"] = flattenAdvancedReplicationSpecAutoScaling(apiObject.AutoScaling) + tfMap["analytics_auto_scaling"] = flattenAdvancedReplicationSpecAutoScaling(apiObject.AnalyticsAutoScaling) + } + + tfMap["region_name"] = apiObject.GetRegionName() + tfMap["provider_name"] = apiObject.GetProviderName() + tfMap["backing_provider_name"] = apiObject.GetBackingProviderName() + tfMap["priority"] = apiObject.GetPriority() + + return tfMap +} + +func hwSpecToDedicatedHwSpec(apiObject *admin.HardwareSpec) *admin.DedicatedHardwareSpec { + if apiObject == nil { + return nil + } + return &admin.DedicatedHardwareSpec{ + NodeCount: apiObject.NodeCount, + DiskIOPS: apiObject.DiskIOPS, + EbsVolumeType: apiObject.EbsVolumeType, + InstanceSize: apiObject.InstanceSize, + } +} + +func flattenAdvancedReplicationSpecRegionConfigSpec(apiObject *admin.DedicatedHardwareSpec, providerName string, tfMapObjects []any) []map[string]any { + if apiObject == nil { + return nil + } + var tfList []map[string]any + + tfMap := map[string]any{} + + if len(tfMapObjects) > 0 { + tfMapObject := tfMapObjects[0].(map[string]any) + + if providerName == "AWS" { + if cast.ToInt64(apiObject.GetDiskIOPS()) > 0 { + tfMap["disk_iops"] = apiObject.GetDiskIOPS() + } + if v, ok := tfMapObject["ebs_volume_type"]; ok && v.(string) != "" { + tfMap["ebs_volume_type"] = apiObject.GetEbsVolumeType() + } + } + if _, ok := tfMapObject["node_count"]; ok { + tfMap["node_count"] = apiObject.GetNodeCount() + } + if v, ok := tfMapObject["instance_size"]; ok && v.(string) != "" { + tfMap["instance_size"] = apiObject.GetInstanceSize() + tfList = append(tfList, tfMap) + } + } else { + tfMap["disk_iops"] = apiObject.GetDiskIOPS() + tfMap["ebs_volume_type"] = apiObject.GetEbsVolumeType() + tfMap["node_count"] = apiObject.GetNodeCount() + tfMap["instance_size"] = apiObject.GetInstanceSize() + tfList = append(tfList, tfMap) + } + return tfList +} + +func flattenAdvancedReplicationSpecAutoScaling(apiObject *admin.AdvancedAutoScalingSettings) []map[string]any { + if apiObject == nil { + return nil + } + var tfList []map[string]any + tfMap := map[string]any{} + if apiObject.DiskGB != nil { + tfMap["disk_gb_enabled"] = apiObject.DiskGB.GetEnabled() + } + if apiObject.Compute != nil { + tfMap["compute_enabled"] = apiObject.Compute.GetEnabled() + tfMap["compute_scale_down_enabled"] = apiObject.Compute.GetScaleDownEnabled() + tfMap["compute_min_instance_size"] = apiObject.Compute.GetMinInstanceSize() + tfMap["compute_max_instance_size"] = apiObject.Compute.GetMaxInstanceSize() + } + tfList = append(tfList, tfMap) + return tfList +} + +func getAdvancedClusterContainerID(containers []admin.CloudProviderContainer, cluster *admin.CloudRegionConfig) string { + if len(containers) == 0 { + return "" + } + for i := range containers { + if cluster.GetProviderName() == constant.GCP { + return containers[i].GetId() + } + if containers[i].GetProviderName() == cluster.GetProviderName() && + containers[i].GetRegion() == cluster.GetRegionName() || // For Azure + containers[i].GetRegionName() == cluster.GetRegionName() { // For AWS + return containers[i].GetId() + } + } + return "" +} + func expandProcessArgs(d *schema.ResourceData, p map[string]any) *matlas.ProcessArgs { res := &matlas.ProcessArgs{} diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index a9a2a5caa7..59f5f5fd59 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -475,14 +475,12 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. } func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) projectID := ids["project_id"] clusterName := ids["cluster_name"] cluster, resp, err := connV2.ClustersApi.GetCluster(ctx, projectID, clusterName).Execute() - clusterOld, _, _ := conn.AdvancedClusters.Get(ctx, projectID, clusterName) if err != nil { if resp != nil && resp.StatusCode == http.StatusNotFound { d.SetId("") @@ -552,7 +550,7 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "pit_enabled", clusterName, err)) } - replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, clusterOld.ReplicationSpecs, d.Get("replication_specs").([]any), d, conn) + replicationSpecs, err := flattenAdvancedReplicationSpecs(ctx, cluster.GetReplicationSpecs(), d.Get("replication_specs").([]any), d, connV2) if err != nil { return diag.FromErr(fmt.Errorf(ErrorClusterAdvancedSetting, "replication_specs", clusterName, err)) } @@ -994,174 +992,6 @@ func expandRegionConfigAutoScaling(tfList []any) *matlas.AdvancedAutoScaling { return advancedAutoScaling } -func flattenAdvancedReplicationSpec(ctx context.Context, apiObject *matlas.AdvancedReplicationSpec, tfMapObject map[string]any, - d *schema.ResourceData, conn *matlas.Client) (map[string]any, error) { - if apiObject == nil { - return nil, nil - } - - tfMap := map[string]any{} - tfMap["num_shards"] = apiObject.NumShards - tfMap["id"] = apiObject.ID - if tfMapObject != nil { - object, containerIDs, err := flattenAdvancedReplicationSpecRegionConfigs(ctx, apiObject.RegionConfigs, tfMapObject["region_configs"].([]any), d, conn) - if err != nil { - return nil, err - } - tfMap["region_configs"] = object - tfMap["container_id"] = containerIDs - } else { - object, containerIDs, err := flattenAdvancedReplicationSpecRegionConfigs(ctx, apiObject.RegionConfigs, nil, d, conn) - if err != nil { - return nil, err - } - tfMap["region_configs"] = object - tfMap["container_id"] = containerIDs - } - tfMap["zone_name"] = apiObject.ZoneName - - return tfMap, nil -} - -func doesAdvancedReplicationSpecMatchAPI(tfObject map[string]any, apiObject *matlas.AdvancedReplicationSpec) bool { - return tfObject["id"] == apiObject.ID || (tfObject["id"] == nil && tfObject["zone_name"] == apiObject.ZoneName) -} - -func flattenAdvancedReplicationSpecRegionConfig(apiObject *matlas.AdvancedRegionConfig, tfMapObject map[string]any) map[string]any { - if apiObject == nil { - return nil - } - - tfMap := map[string]any{} - if tfMapObject != nil { - if v, ok := tfMapObject["analytics_specs"]; ok && len(v.([]any)) > 0 { - tfMap["analytics_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(apiObject.AnalyticsSpecs, apiObject.ProviderName, tfMapObject["analytics_specs"].([]any)) - } - if v, ok := tfMapObject["electable_specs"]; ok && len(v.([]any)) > 0 { - tfMap["electable_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(apiObject.ElectableSpecs, apiObject.ProviderName, tfMapObject["electable_specs"].([]any)) - } - if v, ok := tfMapObject["read_only_specs"]; ok && len(v.([]any)) > 0 { - tfMap["read_only_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(apiObject.ReadOnlySpecs, apiObject.ProviderName, tfMapObject["read_only_specs"].([]any)) - } - if v, ok := tfMapObject["auto_scaling"]; ok && len(v.([]any)) > 0 { - tfMap["auto_scaling"] = flattenAdvancedReplicationSpecAutoScaling(apiObject.AutoScaling) - } - if v, ok := tfMapObject["analytics_auto_scaling"]; ok && len(v.([]any)) > 0 { - tfMap["analytics_auto_scaling"] = flattenAdvancedReplicationSpecAutoScaling(apiObject.AnalyticsAutoScaling) - } - } else { - tfMap["analytics_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(apiObject.AnalyticsSpecs, apiObject.ProviderName, nil) - tfMap["electable_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(apiObject.ElectableSpecs, apiObject.ProviderName, nil) - tfMap["read_only_specs"] = flattenAdvancedReplicationSpecRegionConfigSpec(apiObject.ReadOnlySpecs, apiObject.ProviderName, nil) - tfMap["auto_scaling"] = flattenAdvancedReplicationSpecAutoScaling(apiObject.AutoScaling) - tfMap["analytics_auto_scaling"] = flattenAdvancedReplicationSpecAutoScaling(apiObject.AnalyticsAutoScaling) - } - - tfMap["region_name"] = apiObject.RegionName - tfMap["provider_name"] = apiObject.ProviderName - tfMap["backing_provider_name"] = apiObject.BackingProviderName - tfMap["priority"] = apiObject.Priority - - return tfMap -} - -func flattenAdvancedReplicationSpecRegionConfigs(ctx context.Context, apiObjects []*matlas.AdvancedRegionConfig, tfMapObjects []any, - d *schema.ResourceData, conn *matlas.Client) (tfResult []map[string]any, containersIDs map[string]string, err error) { - if len(apiObjects) == 0 { - return nil, nil, nil - } - - var tfList []map[string]any - containerIDs := make(map[string]string) - - for i, apiObject := range apiObjects { - if apiObject == nil { - continue - } - - if len(tfMapObjects) > i { - tfMapObject := tfMapObjects[i].(map[string]any) - tfList = append(tfList, flattenAdvancedReplicationSpecRegionConfig(apiObject, tfMapObject)) - } else { - tfList = append(tfList, flattenAdvancedReplicationSpecRegionConfig(apiObject, nil)) - } - - if apiObject.ProviderName != "TENANT" { - containers, _, err := conn.Containers.List(ctx, d.Get("project_id").(string), - &matlas.ContainersListOptions{ProviderName: apiObject.ProviderName}) - if err != nil { - return nil, nil, err - } - if result := getAdvancedClusterContainerID(containers, apiObject); result != "" { - // Will print as "providerName:regionName" = "containerId" in terraform show - containerIDs[fmt.Sprintf("%s:%s", apiObject.ProviderName, apiObject.RegionName)] = result - } - } - } - - return tfList, containerIDs, nil -} - -func flattenAdvancedReplicationSpecRegionConfigSpec(apiObject *matlas.Specs, providerName string, tfMapObjects []any) []map[string]any { - if apiObject == nil { - return nil - } - var tfList []map[string]any - - tfMap := map[string]any{} - - if len(tfMapObjects) > 0 { - tfMapObject := tfMapObjects[0].(map[string]any) - - if providerName == "AWS" { - if cast.ToInt64(apiObject.DiskIOPS) > 0 { - tfMap["disk_iops"] = apiObject.DiskIOPS - } - if v, ok := tfMapObject["ebs_volume_type"]; ok && v.(string) != "" { - tfMap["ebs_volume_type"] = apiObject.EbsVolumeType - } - } - if _, ok := tfMapObject["node_count"]; ok { - tfMap["node_count"] = apiObject.NodeCount - } - if v, ok := tfMapObject["instance_size"]; ok && v.(string) != "" { - tfMap["instance_size"] = apiObject.InstanceSize - tfList = append(tfList, tfMap) - } - } else { - tfMap["disk_iops"] = apiObject.DiskIOPS - tfMap["ebs_volume_type"] = apiObject.EbsVolumeType - tfMap["node_count"] = apiObject.NodeCount - tfMap["instance_size"] = apiObject.InstanceSize - tfList = append(tfList, tfMap) - } - - return tfList -} - -func flattenAdvancedReplicationSpecAutoScaling(apiObject *matlas.AdvancedAutoScaling) []map[string]any { - if apiObject == nil { - return nil - } - - var tfList []map[string]any - - tfMap := map[string]any{} - if apiObject.DiskGB != nil { - tfMap["disk_gb_enabled"] = apiObject.DiskGB.Enabled - } - if apiObject.Compute != nil { - tfMap["compute_enabled"] = apiObject.Compute.Enabled - tfMap["compute_scale_down_enabled"] = apiObject.Compute.ScaleDownEnabled - tfMap["compute_min_instance_size"] = apiObject.Compute.MinInstanceSize - tfMap["compute_max_instance_size"] = apiObject.Compute.MaxInstanceSize - } - - tfList = append(tfList, tfMap) - - return tfList -} - func resourceRefreshFunc(ctx context.Context, name, projectID string, client *matlas.Client) retry.StateRefreshFunc { return func() (any, string, error) { c, resp, err := client.AdvancedClusters.Get(ctx, projectID, name) @@ -1260,21 +1090,3 @@ func updateAdvancedCluster( return cluster, resp, nil } - -func getAdvancedClusterContainerID(containers []matlas.Container, cluster *matlas.AdvancedRegionConfig) string { - if len(containers) != 0 { - for i := range containers { - if cluster.ProviderName == "GCP" { - return containers[i].ID - } - - if containers[i].ProviderName == cluster.ProviderName && - containers[i].Region == cluster.RegionName || // For Azure - containers[i].RegionName == cluster.RegionName { // For AWS - return containers[i].ID - } - } - } - - return "" -} From cc38401f73f98c795555b04d4ace442161262d9b Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Sat, 17 Feb 2024 13:27:24 +0100 Subject: [PATCH 31/52] enable more tests --- ...esource_advanced_cluster_migration_test.go | 32 ----------------- .../resource_advanced_cluster_test.go | 35 ------------------- 2 files changed, 67 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go index 9104f7182b..a9bb8150c0 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go @@ -9,38 +9,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" ) -func TestAccMigrationAdvancedCluster_basic(t *testing.T) { - // TEMPORARY: to delete, based on TestAccClusterAdvancedCluster_basicTenant - var ( - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acc.RandomProjectName() - clusterName = acc.RandomClusterName() - config = configTenant(orgID, projectName, clusterName) - ) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acc.PreCheckBasic(t) }, - CheckDestroy: acc.CheckDestroyCluster, - Steps: []resource.TestStep{ - { - ExternalProviders: mig.ExternalProviders(), - Config: config, - Check: resource.ComposeTestCheckFunc( - checkExists(resourceName), - resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", clusterName), - resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), - resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), - resource.TestCheckResourceAttrSet(resourceName, "termination_protection_enabled"), - ), - }, - mig.TestStep(config), - }, - }) -} - func TestAccMigrationAdvancedCluster_singleAWSProvider(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -70,7 +39,6 @@ func TestAccMigrationAdvancedCluster_singleAWSProvider(t *testing.T) { } func TestAccMigrationAdvancedCluster_multiCloud(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 006578af48..278d71fefe 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -20,42 +20,7 @@ const ( dataSourcePluralName = "data.mongodbatlas_advanced_clusters.test" ) -func TestAccClusterAdvancedCluster_basic(t *testing.T) { - // TEMPORARY: to delete, based on TestAccClusterAdvancedCluster_basicTenant - var ( - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acc.RandomProjectName() - clusterName = acc.RandomClusterName() - ) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acc.PreCheckBasic(t) }, - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - CheckDestroy: acc.CheckDestroyCluster, - Steps: []resource.TestStep{ - { - Config: configTenant(orgID, projectName, clusterName), - Check: resource.ComposeTestCheckFunc( - checkExists(resourceName), - resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", clusterName), - resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), - resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), - resource.TestCheckResourceAttrSet(resourceName, "termination_protection_enabled"), - resource.TestCheckResourceAttr(dataSourceName, "name", clusterName), - resource.TestCheckResourceAttr(dataSourceName, "termination_protection_enabled", "false"), - resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.#"), - resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.replication_specs.#"), - resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.name"), - resource.TestCheckResourceAttrSet(dataSourcePluralName, "results.0.termination_protection_enabled"), - ), - }, - }, - }) -} - func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() From 22607f21538608e981ba417ccb6197ee145a8d24 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Sat, 17 Feb 2024 16:25:21 +0100 Subject: [PATCH 32/52] enable more tests --- .../advancedcluster/resource_advanced_cluster_test.go | 5 ----- 1 file changed, 5 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 278d71fefe..46a6b6fe65 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -78,7 +78,6 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { } func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( dataSourceName = fmt.Sprintf("data.%s", resourceName) orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") @@ -227,7 +226,6 @@ func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { } func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -279,7 +277,6 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { } func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -484,7 +481,6 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { } func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -609,7 +605,6 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes } func TestAccClusterAdvancedCluster_withTags(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() From 8eb9ebddea3f8da6ff57c9f152469993d13335c8 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Sat, 17 Feb 2024 18:38:21 +0100 Subject: [PATCH 33/52] revert long tests --- .../service/advancedcluster/resource_advanced_cluster_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 46a6b6fe65..747eeb7baf 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -78,6 +78,7 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { } func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( dataSourceName = fmt.Sprintf("data.%s", resourceName) orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") @@ -277,6 +278,7 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { } func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -481,6 +483,7 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { } func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -605,6 +608,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes } func TestAccClusterAdvancedCluster_withTags(t *testing.T) { + acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() From e1136c4ca27e2ccc82d34dcd9807c0c3b9d39a61 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 11:58:58 +0100 Subject: [PATCH 34/52] most of create --- internal/common/conversion/flatten_expand.go | 4 +- .../advancedcluster/model_advanced_cluster.go | 326 +++++++++++++++++- .../resource_advanced_cluster.go | 235 ++----------- .../resource_serverless_instance.go | 6 +- 4 files changed, 361 insertions(+), 210 deletions(-) diff --git a/internal/common/conversion/flatten_expand.go b/internal/common/conversion/flatten_expand.go index 1105092b62..42ffe43ec2 100644 --- a/internal/common/conversion/flatten_expand.go +++ b/internal/common/conversion/flatten_expand.go @@ -28,7 +28,7 @@ func FlattenTags(tags []admin.ResourceTag) []map[string]string { return ret } -func ExpandTagsFromSetSchema(d *schema.ResourceData) []admin.ResourceTag { +func ExpandTagsFromSetSchema(d *schema.ResourceData) *[]admin.ResourceTag { list := d.Get("tags").(*schema.Set) ret := make([]admin.ResourceTag, list.Len()) for i, item := range list.List() { @@ -38,7 +38,7 @@ func ExpandTagsFromSetSchema(d *schema.ResourceData) []admin.ResourceTag { Value: StringPtr(tag["value"].(string)), } } - return ret + return &ret } func ExpandStringList(list []any) (res []string) { diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index a4bdbffab5..1fddc05ef1 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -491,6 +491,19 @@ func expandBiConnectorConfig(d *schema.ResourceData) (*matlas.BiConnector, error return &biConnector, nil } +func expandBiConnectorConfigV2(d *schema.ResourceData) *admin.BiConnector { + if v, ok := d.GetOk("bi_connector_config"); ok { + if biConn := v.([]any); len(biConn) > 0 { + biConnMap := biConn[0].(map[string]any) + return &admin.BiConnector{ + Enabled: conversion.Pointer(cast.ToBool(biConnMap["enabled"])), + ReadPreference: conversion.StringPtr(cast.ToString(biConnMap["read_preference"])), + } + } + } + return nil +} + func expandTagSliceFromSetSchema(d *schema.ResourceData) []*matlas.Tag { list := d.Get("tags").(*schema.Set) res := make([]*matlas.Tag, list.Len()) @@ -706,6 +719,18 @@ func hwSpecToDedicatedHwSpec(apiObject *admin.HardwareSpec) *admin.DedicatedHard } } +func dedicatedHwSpecToHwSpec(apiObject *admin.DedicatedHardwareSpec) *admin.HardwareSpec { + if apiObject == nil { + return nil + } + return &admin.HardwareSpec{ + NodeCount: apiObject.NodeCount, + DiskIOPS: apiObject.DiskIOPS, + EbsVolumeType: apiObject.EbsVolumeType, + InstanceSize: apiObject.InstanceSize, + } +} + func flattenAdvancedReplicationSpecRegionConfigSpec(apiObject *admin.DedicatedHardwareSpec, providerName string, tfMapObjects []any) []map[string]any { if apiObject == nil { return nil @@ -851,6 +876,305 @@ func expandLabelSliceFromSetSchema(d *schema.ResourceData) []matlas.Label { Value: v["value"].(string), } } - return res } + +func expandLabelSliceFromSetSchemaV2(d *schema.ResourceData) ([]admin.ComponentLabel, diag.Diagnostics) { + list := d.Get("labels").(*schema.Set) + res := make([]admin.ComponentLabel, list.Len()) + for i, val := range list.List() { + v := val.(map[string]any) + key := v["key"].(string) + if key == ignoreLabel { + return nil, diag.FromErr(fmt.Errorf("you should not set `Infrastructure Tool` label, it is used for internal purposes")) + } + res[i] = admin.ComponentLabel{ + Key: conversion.StringPtr(key), + Value: conversion.StringPtr(v["value"].(string)), + } + } + return res, nil +} + +func expandAdvancedReplicationSpecs(tfList []any) []*matlas.AdvancedReplicationSpec { + if len(tfList) == 0 { + return nil + } + + var apiObjects []*matlas.AdvancedReplicationSpec + + for _, tfMapRaw := range tfList { + tfMap, ok := tfMapRaw.(map[string]any) + + if !ok { + continue + } + + apiObject := expandAdvancedReplicationSpec(tfMap) + + apiObjects = append(apiObjects, apiObject) + } + + return apiObjects +} + +func expandAdvancedReplicationSpecsV2(tfList []any) *[]admin.ReplicationSpec { + if len(tfList) == 0 { + return nil + } + var apiObjects []admin.ReplicationSpec + for _, tfMapRaw := range tfList { + tfMap, ok := tfMapRaw.(map[string]any) + if !ok || tfMap == nil { + continue + } + apiObject := expandAdvancedReplicationSpecV2(tfMap) + apiObjects = append(apiObjects, *apiObject) + } + return &apiObjects +} + +func expandAdvancedReplicationSpec(tfMap map[string]any) *matlas.AdvancedReplicationSpec { + if tfMap == nil { + return nil + } + + apiObject := &matlas.AdvancedReplicationSpec{ + NumShards: tfMap["num_shards"].(int), + ZoneName: tfMap["zone_name"].(string), + RegionConfigs: expandRegionConfigs(tfMap["region_configs"].([]any)), + } + + if tfMap["id"].(string) != "" { + apiObject.ID = tfMap["id"].(string) + } + + return apiObject +} + +func expandAdvancedReplicationSpecV2(tfMap map[string]any) *admin.ReplicationSpec { + apiObject := &admin.ReplicationSpec{ + NumShards: conversion.Pointer(tfMap["num_shards"].(int)), + ZoneName: conversion.StringPtr(tfMap["zone_name"].(string)), + RegionConfigs: expandRegionConfigsV2(tfMap["region_configs"].([]any)), + } + if tfMap["id"].(string) != "" { + apiObject.Id = conversion.StringPtr(tfMap["id"].(string)) + } + return apiObject +} + +func expandRegionConfigs(tfList []any) []*matlas.AdvancedRegionConfig { + if len(tfList) == 0 { + return nil + } + + var apiObjects []*matlas.AdvancedRegionConfig + + for _, tfMapRaw := range tfList { + tfMap, ok := tfMapRaw.(map[string]any) + + if !ok { + continue + } + + apiObject := expandRegionConfig(tfMap) + + apiObjects = append(apiObjects, apiObject) + } + + return apiObjects +} + +func expandRegionConfigsV2(tfList []any) *[]admin.CloudRegionConfig { + if len(tfList) == 0 { + return nil + } + var apiObjects []admin.CloudRegionConfig + for _, tfMapRaw := range tfList { + tfMap, ok := tfMapRaw.(map[string]any) + if !ok || tfMap == nil { + continue + } + apiObject := expandRegionConfigV2(tfMap) + apiObjects = append(apiObjects, *apiObject) + } + + return &apiObjects +} + +func expandRegionConfig(tfMap map[string]any) *matlas.AdvancedRegionConfig { + providerName := tfMap["provider_name"].(string) + apiObject := &matlas.AdvancedRegionConfig{ + Priority: conversion.Pointer(cast.ToInt(tfMap["priority"])), + ProviderName: providerName, + RegionName: tfMap["region_name"].(string), + } + + if v, ok := tfMap["analytics_specs"]; ok && len(v.([]any)) > 0 { + apiObject.AnalyticsSpecs = expandRegionConfigSpec(v.([]any), providerName) + } + if v, ok := tfMap["electable_specs"]; ok && len(v.([]any)) > 0 { + apiObject.ElectableSpecs = expandRegionConfigSpec(v.([]any), providerName) + } + if v, ok := tfMap["read_only_specs"]; ok && len(v.([]any)) > 0 { + apiObject.ReadOnlySpecs = expandRegionConfigSpec(v.([]any), providerName) + } + if v, ok := tfMap["auto_scaling"]; ok && len(v.([]any)) > 0 { + apiObject.AutoScaling = expandRegionConfigAutoScaling(v.([]any)) + } + if v, ok := tfMap["analytics_auto_scaling"]; ok && len(v.([]any)) > 0 { + apiObject.AnalyticsAutoScaling = expandRegionConfigAutoScaling(v.([]any)) + } + if v, ok := tfMap["backing_provider_name"]; ok { + apiObject.BackingProviderName = v.(string) + } + + return apiObject +} + +func expandRegionConfigV2(tfMap map[string]any) *admin.CloudRegionConfig { + providerName := tfMap["provider_name"].(string) + apiObject := &admin.CloudRegionConfig{ + Priority: conversion.Pointer(cast.ToInt(tfMap["priority"])), + ProviderName: conversion.StringPtr(providerName), + RegionName: conversion.StringPtr(tfMap["region_name"].(string)), + } + + if v, ok := tfMap["analytics_specs"]; ok && len(v.([]any)) > 0 { + apiObject.AnalyticsSpecs = expandRegionConfigSpecV2(v.([]any), providerName) + } + if v, ok := tfMap["electable_specs"]; ok && len(v.([]any)) > 0 { + apiObject.ElectableSpecs = dedicatedHwSpecToHwSpec(expandRegionConfigSpecV2(v.([]any), providerName)) + } + if v, ok := tfMap["read_only_specs"]; ok && len(v.([]any)) > 0 { + apiObject.ReadOnlySpecs = expandRegionConfigSpecV2(v.([]any), providerName) + } + if v, ok := tfMap["auto_scaling"]; ok && len(v.([]any)) > 0 { + apiObject.AutoScaling = expandRegionConfigAutoScalingV2(v.([]any)) + } + if v, ok := tfMap["analytics_auto_scaling"]; ok && len(v.([]any)) > 0 { + apiObject.AnalyticsAutoScaling = expandRegionConfigAutoScalingV2(v.([]any)) + } + if v, ok := tfMap["backing_provider_name"]; ok { + apiObject.BackingProviderName = conversion.StringPtr(v.(string)) + } + return apiObject +} + +func expandRegionConfigSpec(tfList []any, providerName string) *matlas.Specs { + if tfList == nil && len(tfList) > 0 { + return nil + } + + tfMap, _ := tfList[0].(map[string]any) + + apiObject := &matlas.Specs{} + + if providerName == "AWS" { + if v, ok := tfMap["disk_iops"]; ok && v.(int) > 0 { + apiObject.DiskIOPS = conversion.Pointer(cast.ToInt64(v.(int))) + } + if v, ok := tfMap["ebs_volume_type"]; ok { + apiObject.EbsVolumeType = v.(string) + } + } + if v, ok := tfMap["instance_size"]; ok { + apiObject.InstanceSize = v.(string) + } + if v, ok := tfMap["node_count"]; ok { + apiObject.NodeCount = conversion.Pointer(v.(int)) + } + + return apiObject +} + +func expandRegionConfigSpecV2(tfList []any, providerName string) *admin.DedicatedHardwareSpec { + tfMap, _ := tfList[0].(map[string]any) + apiObject := new(admin.DedicatedHardwareSpec) + if providerName == "AWS" { + if v, ok := tfMap["disk_iops"]; ok && v.(int) > 0 { + apiObject.DiskIOPS = conversion.Pointer(v.(int)) + } + if v, ok := tfMap["ebs_volume_type"]; ok { + apiObject.EbsVolumeType = conversion.StringPtr(v.(string)) + } + } + if v, ok := tfMap["instance_size"]; ok { + apiObject.InstanceSize = conversion.StringPtr(v.(string)) + } + if v, ok := tfMap["node_count"]; ok { + apiObject.NodeCount = conversion.Pointer(v.(int)) + } + return apiObject +} + +func expandRegionConfigAutoScaling(tfList []any) *matlas.AdvancedAutoScaling { + if tfList == nil && len(tfList) > 0 { + return nil + } + + tfMap, _ := tfList[0].(map[string]any) + + advancedAutoScaling := &matlas.AdvancedAutoScaling{} + diskGB := &matlas.DiskGB{} + compute := &matlas.Compute{} + + if v, ok := tfMap["disk_gb_enabled"]; ok { + diskGB.Enabled = conversion.Pointer(v.(bool)) + } + if v, ok := tfMap["compute_enabled"]; ok { + compute.Enabled = conversion.Pointer(v.(bool)) + } + if v, ok := tfMap["compute_scale_down_enabled"]; ok { + compute.ScaleDownEnabled = conversion.Pointer(v.(bool)) + } + if v, ok := tfMap["compute_min_instance_size"]; ok { + value := compute.ScaleDownEnabled + if *value { + compute.MinInstanceSize = v.(string) + } + } + if v, ok := tfMap["compute_max_instance_size"]; ok { + value := compute.Enabled + if *value { + compute.MaxInstanceSize = v.(string) + } + } + + advancedAutoScaling.DiskGB = diskGB + advancedAutoScaling.Compute = compute + + return advancedAutoScaling +} + +func expandRegionConfigAutoScalingV2(tfList []any) *admin.AdvancedAutoScalingSettings { + tfMap, _ := tfList[0].(map[string]any) + settings := admin.AdvancedAutoScalingSettings{ + DiskGB: new(admin.DiskGBAutoScaling), + Compute: new(admin.AdvancedComputeAutoScaling), + } + + if v, ok := tfMap["disk_gb_enabled"]; ok { + settings.DiskGB.Enabled = conversion.Pointer(v.(bool)) + } + if v, ok := tfMap["compute_enabled"]; ok { + settings.Compute.Enabled = conversion.Pointer(v.(bool)) + } + if v, ok := tfMap["compute_scale_down_enabled"]; ok { + settings.Compute.ScaleDownEnabled = conversion.Pointer(v.(bool)) + } + if v, ok := tfMap["compute_min_instance_size"]; ok { + value := settings.Compute.ScaleDownEnabled + if *value { + settings.Compute.MinInstanceSize = conversion.StringPtr(v.(string)) + } + } + if v, ok := tfMap["compute_max_instance_size"]; ok { + value := settings.Compute.Enabled + if *value { + settings.Compute.MaxInstanceSize = conversion.StringPtr(v.(string)) + } + } + return &settings +} diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 59f5f5fd59..834dbfd97c 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -20,6 +20,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "github.com/spf13/cast" + "go.mongodb.org/atlas-sdk/v20231115006/admin" matlas "go.mongodb.org/atlas/mongodbatlas" ) @@ -358,65 +359,64 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. } conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) - request := &matlas.AdvancedCluster{ - Name: d.Get("name").(string), - ClusterType: cast.ToString(d.Get("cluster_type")), - ReplicationSpecs: expandAdvancedReplicationSpecs(d.Get("replication_specs").([]any)), + params := &admin.AdvancedClusterDescription{ + Name: conversion.StringPtr(cast.ToString(d.Get("name"))), + ClusterType: conversion.StringPtr(cast.ToString(d.Get("cluster_type"))), + ReplicationSpecs: expandAdvancedReplicationSpecsV2(d.Get("replication_specs").([]any)), } if v, ok := d.GetOk("backup_enabled"); ok { - request.BackupEnabled = conversion.Pointer(v.(bool)) + params.BackupEnabled = conversion.Pointer(v.(bool)) } if _, ok := d.GetOk("bi_connector_config"); ok { - biConnector, err := expandBiConnectorConfig(d) - if err != nil { - return diag.FromErr(fmt.Errorf(errorCreate, err)) - } - request.BiConnector = biConnector + params.BiConnector = expandBiConnectorConfigV2(d) } if v, ok := d.GetOk("disk_size_gb"); ok { - request.DiskSizeGB = conversion.Pointer(v.(float64)) + params.DiskSizeGB = conversion.Pointer(v.(float64)) } if v, ok := d.GetOk("encryption_at_rest_provider"); ok { - request.EncryptionAtRestProvider = v.(string) + params.EncryptionAtRestProvider = conversion.StringPtr(v.(string)) } - if _, ok := d.GetOk("labels"); ok && ContainsLabelOrKey(expandLabelSliceFromSetSchema(d), defaultLabel) { - return diag.FromErr(fmt.Errorf("you should not set `Infrastructure Tool` label, it is used for internal purposes")) + if _, ok := d.GetOk("labels"); ok { + labels, err := expandLabelSliceFromSetSchemaV2(d) + if err != nil { + return nil + } + params.Labels = &labels } - request.Labels = append(expandLabelSliceFromSetSchema(d), defaultLabel) if _, ok := d.GetOk("tags"); ok { - request.Tags = expandTagSliceFromSetSchema(d) + params.Tags = conversion.ExpandTagsFromSetSchema(d) } if v, ok := d.GetOk("mongo_db_major_version"); ok { - request.MongoDBMajorVersion = FormatMongoDBMajorVersion(v.(string)) + params.MongoDBMajorVersion = conversion.StringPtr(FormatMongoDBMajorVersion(v.(string))) } if v, ok := d.GetOk("pit_enabled"); ok { - request.PitEnabled = conversion.Pointer(v.(bool)) + params.PitEnabled = conversion.Pointer(v.(bool)) } if v, ok := d.GetOk("root_cert_type"); ok { - request.RootCertType = v.(string) + params.RootCertType = conversion.StringPtr(v.(string)) } if v, ok := d.GetOk("termination_protection_enabled"); ok { - request.TerminationProtectionEnabled = conversion.Pointer(v.(bool)) + params.TerminationProtectionEnabled = conversion.Pointer(v.(bool)) } if v, ok := d.GetOk("version_release_system"); ok { - request.VersionReleaseSystem = v.(string) + params.VersionReleaseSystem = conversion.StringPtr(v.(string)) } - // We need to validate the oplog_size_mb attr of the advanced configuration option to show the error - // before that the cluster is created + // Validate oplog_size_mb to show the error before the cluster is created. if oplogSizeMB, ok := d.GetOkExists("advanced_configuration.0.oplog_size_mb"); ok { if cast.ToInt64(oplogSizeMB) <= 0 { return diag.FromErr(fmt.Errorf("`advanced_configuration.oplog_size_mb` cannot be <= 0")) } } - cluster, _, err := conn.AdvancedClusters.Create(ctx, projectID, request) + cluster, _, err := connV2.ClustersApi.CreateCluster(ctx, projectID, params).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorCreate, err)) } @@ -431,31 +431,23 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. Delay: 3 * time.Minute, } - // Wait, catching any errors _, err = stateConf.WaitForStateContext(ctx) if err != nil { return diag.FromErr(fmt.Errorf(errorCreate, err)) } - /* - So far, the cluster has created correctly, so we need to set up - the advanced configuration option to attach it - */ - ac, ok := d.GetOk("advanced_configuration") - if aclist, ok1 := ac.([]any); ok1 && len(aclist) > 0 { - advancedConfReq := expandProcessArgs(d, aclist[0].(map[string]any)) - - if ok { - _, _, err := conn.Clusters.UpdateProcessArgs(ctx, projectID, cluster.Name, advancedConfReq) + if ac, ok := d.GetOk("advanced_configuration"); ok { + if aclist, ok := ac.([]any); ok && len(aclist) > 0 { + advancedConfReq := expandProcessArgs(d, aclist[0].(map[string]any)) + _, _, err := conn.Clusters.UpdateProcessArgs(ctx, projectID, cluster.GetName(), advancedConfReq) if err != nil { - return diag.FromErr(fmt.Errorf(errorConfigUpdate, cluster.Name, err)) + return diag.FromErr(fmt.Errorf(errorConfigUpdate, cluster.GetName(), err)) } } } - // To pause a cluster if v := d.Get("paused").(bool); v { - request = &matlas.AdvancedCluster{ + request := &matlas.AdvancedCluster{ Paused: conversion.Pointer(v), } @@ -466,9 +458,9 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. } d.SetId(conversion.EncodeStateID(map[string]string{ - "cluster_id": cluster.ID, + "cluster_id": cluster.GetId(), "project_id": projectID, - "cluster_name": cluster.Name, + "cluster_name": cluster.GetName(), })) return resourceRead(ctx, d, meta) @@ -486,7 +478,6 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di d.SetId("") return nil } - return diag.FromErr(fmt.Errorf(errorRead, clusterName, err)) } @@ -830,168 +821,6 @@ func splitSClusterAdvancedImportID(id string) (projectID, clusterName *string, e return } -func expandAdvancedReplicationSpec(tfMap map[string]any) *matlas.AdvancedReplicationSpec { - if tfMap == nil { - return nil - } - - apiObject := &matlas.AdvancedReplicationSpec{ - NumShards: tfMap["num_shards"].(int), - ZoneName: tfMap["zone_name"].(string), - RegionConfigs: expandRegionConfigs(tfMap["region_configs"].([]any)), - } - - if tfMap["id"].(string) != "" { - apiObject.ID = tfMap["id"].(string) - } - - return apiObject -} - -func expandAdvancedReplicationSpecs(tfList []any) []*matlas.AdvancedReplicationSpec { - if len(tfList) == 0 { - return nil - } - - var apiObjects []*matlas.AdvancedReplicationSpec - - for _, tfMapRaw := range tfList { - tfMap, ok := tfMapRaw.(map[string]any) - - if !ok { - continue - } - - apiObject := expandAdvancedReplicationSpec(tfMap) - - apiObjects = append(apiObjects, apiObject) - } - - return apiObjects -} - -func expandRegionConfig(tfMap map[string]any) *matlas.AdvancedRegionConfig { - if tfMap == nil { - return nil - } - - providerName := tfMap["provider_name"].(string) - apiObject := &matlas.AdvancedRegionConfig{ - Priority: conversion.Pointer(cast.ToInt(tfMap["priority"])), - ProviderName: providerName, - RegionName: tfMap["region_name"].(string), - } - - if v, ok := tfMap["analytics_specs"]; ok && len(v.([]any)) > 0 { - apiObject.AnalyticsSpecs = expandRegionConfigSpec(v.([]any), providerName) - } - if v, ok := tfMap["electable_specs"]; ok && len(v.([]any)) > 0 { - apiObject.ElectableSpecs = expandRegionConfigSpec(v.([]any), providerName) - } - if v, ok := tfMap["read_only_specs"]; ok && len(v.([]any)) > 0 { - apiObject.ReadOnlySpecs = expandRegionConfigSpec(v.([]any), providerName) - } - if v, ok := tfMap["auto_scaling"]; ok && len(v.([]any)) > 0 { - apiObject.AutoScaling = expandRegionConfigAutoScaling(v.([]any)) - } - if v, ok := tfMap["analytics_auto_scaling"]; ok && len(v.([]any)) > 0 { - apiObject.AnalyticsAutoScaling = expandRegionConfigAutoScaling(v.([]any)) - } - if v, ok := tfMap["backing_provider_name"]; ok { - apiObject.BackingProviderName = v.(string) - } - - return apiObject -} - -func expandRegionConfigs(tfList []any) []*matlas.AdvancedRegionConfig { - if len(tfList) == 0 { - return nil - } - - var apiObjects []*matlas.AdvancedRegionConfig - - for _, tfMapRaw := range tfList { - tfMap, ok := tfMapRaw.(map[string]any) - - if !ok { - continue - } - - apiObject := expandRegionConfig(tfMap) - - apiObjects = append(apiObjects, apiObject) - } - - return apiObjects -} - -func expandRegionConfigSpec(tfList []any, providerName string) *matlas.Specs { - if tfList == nil && len(tfList) > 0 { - return nil - } - - tfMap, _ := tfList[0].(map[string]any) - - apiObject := &matlas.Specs{} - - if providerName == "AWS" { - if v, ok := tfMap["disk_iops"]; ok && v.(int) > 0 { - apiObject.DiskIOPS = conversion.Pointer(cast.ToInt64(v.(int))) - } - if v, ok := tfMap["ebs_volume_type"]; ok { - apiObject.EbsVolumeType = v.(string) - } - } - if v, ok := tfMap["instance_size"]; ok { - apiObject.InstanceSize = v.(string) - } - if v, ok := tfMap["node_count"]; ok { - apiObject.NodeCount = conversion.Pointer(v.(int)) - } - - return apiObject -} - -func expandRegionConfigAutoScaling(tfList []any) *matlas.AdvancedAutoScaling { - if tfList == nil && len(tfList) > 0 { - return nil - } - - tfMap, _ := tfList[0].(map[string]any) - - advancedAutoScaling := &matlas.AdvancedAutoScaling{} - diskGB := &matlas.DiskGB{} - compute := &matlas.Compute{} - - if v, ok := tfMap["disk_gb_enabled"]; ok { - diskGB.Enabled = conversion.Pointer(v.(bool)) - } - if v, ok := tfMap["compute_enabled"]; ok { - compute.Enabled = conversion.Pointer(v.(bool)) - } - if v, ok := tfMap["compute_scale_down_enabled"]; ok { - compute.ScaleDownEnabled = conversion.Pointer(v.(bool)) - } - if v, ok := tfMap["compute_min_instance_size"]; ok { - value := compute.ScaleDownEnabled - if *value { - compute.MinInstanceSize = v.(string) - } - } - if v, ok := tfMap["compute_max_instance_size"]; ok { - value := compute.Enabled - if *value { - compute.MaxInstanceSize = v.(string) - } - } - - advancedAutoScaling.DiskGB = diskGB - advancedAutoScaling.Compute = compute - - return advancedAutoScaling -} - func resourceRefreshFunc(ctx context.Context, name, projectID string, client *matlas.Client) retry.StateRefreshFunc { return func() (any, string, error) { c, resp, err := client.AdvancedClusters.Get(ctx, projectID, name) diff --git a/internal/service/serverlessinstance/resource_serverless_instance.go b/internal/service/serverlessinstance/resource_serverless_instance.go index c8fc3811bc..4504f366e7 100644 --- a/internal/service/serverlessinstance/resource_serverless_instance.go +++ b/internal/service/serverlessinstance/resource_serverless_instance.go @@ -143,8 +143,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if _, ok := d.GetOk("tags"); ok { - tags := conversion.ExpandTagsFromSetSchema(d) - params.Tags = &tags + params.Tags = conversion.ExpandTagsFromSetSchema(d) } _, _, err := connV2.ServerlessInstancesApi.CreateServerlessInstance(ctx, projectID, params).Execute() @@ -262,8 +261,7 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if d.HasChange("tags") { - tags := conversion.ExpandTagsFromSetSchema(d) - params.Tags = &tags + params.Tags = conversion.ExpandTagsFromSetSchema(d) } _, _, err := connV2.ServerlessInstancesApi.UpdateServerlessInstance(ctx, projectID, instanceName, params).Execute() From 6a1f37ec72cae7c1a01b2720d24560e33b8fcbd2 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 12:35:14 +0100 Subject: [PATCH 35/52] TEMPORARY: don't run serverless tests --- .github/workflows/acceptance-tests-runner.yml | 2 +- .github/workflows/migration-tests.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/acceptance-tests-runner.yml b/.github/workflows/acceptance-tests-runner.yml index 2cf860ddec..ab4d26a6e7 100644 --- a/.github/workflows/acceptance-tests-runner.yml +++ b/.github/workflows/acceptance-tests-runner.yml @@ -129,7 +129,7 @@ jobs: generic: ${{ steps.filter.outputs.generic == 'true' || env.mustTrigger == 'true' }} backup: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE project: ${{ steps.filter.outputs.project == 'true' || env.mustTrigger == 'true' }} - serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} + serverless: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE network: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE config: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE assume_role: ${{ steps.filter.outputs.assume_role == 'true' || env.mustTrigger == 'true' }} diff --git a/.github/workflows/migration-tests.yml b/.github/workflows/migration-tests.yml index 3d26afa991..743594fc31 100644 --- a/.github/workflows/migration-tests.yml +++ b/.github/workflows/migration-tests.yml @@ -64,7 +64,7 @@ jobs: generic: ${{ steps.filter.outputs.generic == 'true' || env.mustTrigger == 'true' }} network: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE encryption: ${{ steps.filter.outputs.encryption == 'true' || env.mustTrigger == 'true' }} - serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} + serverless: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE data_lake: ${{ steps.filter.outputs.data_lake == 'true' || env.mustTrigger == 'true' }} cluster_outage_simulation: ${{ steps.filter.outputs.cluster_outage_simulation == 'true' || env.mustTrigger == 'true' }} cluster: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE From 3cb23bc1a0cd1ff691759e04b9188feb1126e3e8 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 13:31:17 +0100 Subject: [PATCH 36/52] delete --- .../advancedcluster/resource_advanced_cluster.go | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 834dbfd97c..ce233dceef 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -738,20 +738,21 @@ func resourceMongoDBAtlasAdvancedClusterUpdate(ctx context.Context, d *schema.Re } func resourceDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - // Get client connection. conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) projectID := ids["project_id"] clusterName := ids["cluster_name"] - var options *matlas.DeleteAdvanceClusterOptions + params := &admin.DeleteClusterApiParams{ + GroupId: projectID, + ClusterName: clusterName, + } if v, ok := d.GetOkExists("retain_backups_enabled"); ok { - options = &matlas.DeleteAdvanceClusterOptions{ - RetainBackups: conversion.Pointer(v.(bool)), - } + params.RetainBackups = conversion.Pointer(v.(bool)) } - _, err := conn.AdvancedClusters.Delete(ctx, projectID, clusterName, options) + _, err := connV2.ClustersApi.DeleteClusterWithParams(ctx, params).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorDelete, clusterName, err)) } From ead12e5dc69957a145c29065f2cbc6265524256d Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 13:31:35 +0100 Subject: [PATCH 37/52] expandProcessArgs in create --- .../advancedcluster/model_advanced_cluster.go | 62 +++++++++++++++++++ .../resource_advanced_cluster.go | 4 +- 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index 1fddc05ef1..59d527da42 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -865,6 +865,68 @@ func expandProcessArgs(d *schema.ResourceData, p map[string]any) *matlas.Process return res } +func expandProcessArgsV2(d *schema.ResourceData, p map[string]any) *admin.ClusterDescriptionProcessArgs { + res := new(admin.ClusterDescriptionProcessArgs) + + if _, ok := d.GetOkExists("advanced_configuration.0.default_read_concern"); ok { + res.DefaultReadConcern = conversion.StringPtr(cast.ToString(p["default_read_concern"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.default_write_concern"); ok { + res.DefaultWriteConcern = conversion.StringPtr(cast.ToString(p["default_write_concern"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.fail_index_key_too_long"); ok { + res.FailIndexKeyTooLong = conversion.Pointer(cast.ToBool(p["fail_index_key_too_long"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.javascript_enabled"); ok { + res.JavascriptEnabled = conversion.Pointer(cast.ToBool(p["javascript_enabled"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.minimum_enabled_tls_protocol"); ok { + res.MinimumEnabledTlsProtocol = conversion.StringPtr(cast.ToString(p["minimum_enabled_tls_protocol"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.no_table_scan"); ok { + res.NoTableScan = conversion.Pointer(cast.ToBool(p["no_table_scan"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.sample_size_bi_connector"); ok { + res.SampleSizeBIConnector = conversion.Pointer(cast.ToInt(p["sample_size_bi_connector"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.sample_refresh_interval_bi_connector"); ok { + res.SampleRefreshIntervalBIConnector = conversion.Pointer(cast.ToInt(p["sample_refresh_interval_bi_connector"])) + } + + if _, ok := d.GetOkExists("advanced_configuration.0.oplog_size_mb"); ok { + if sizeMB := cast.ToInt64(p["oplog_size_mb"]); sizeMB != 0 { + res.OplogSizeMB = conversion.Pointer(cast.ToInt(p["oplog_size_mb"])) + } else { + log.Printf(ErrorClusterSetting, `oplog_size_mb`, "", cast.ToString(sizeMB)) + } + } + + if _, ok := d.GetOkExists("advanced_configuration.0.oplog_min_retention_hours"); ok { + if minRetentionHours := cast.ToFloat64(p["oplog_min_retention_hours"]); minRetentionHours >= 0 { + res.OplogMinRetentionHours = conversion.Pointer(cast.ToFloat64(p["oplog_min_retention_hours"])) + } else { + log.Printf(ErrorClusterSetting, `oplog_min_retention_hours`, "", cast.ToString(minRetentionHours)) + } + } + + if _, ok := d.GetOkExists("advanced_configuration.0.transaction_lifetime_limit_seconds"); ok { + if transactionLifetimeLimitSeconds := cast.ToInt64(p["transaction_lifetime_limit_seconds"]); transactionLifetimeLimitSeconds > 0 { + res.TransactionLifetimeLimitSeconds = conversion.Pointer(cast.ToInt64(p["transaction_lifetime_limit_seconds"])) + } else { + log.Printf(ErrorClusterSetting, `transaction_lifetime_limit_seconds`, "", cast.ToString(transactionLifetimeLimitSeconds)) + } + } + + return res +} + func expandLabelSliceFromSetSchema(d *schema.ResourceData) []matlas.Label { list := d.Get("labels").(*schema.Set) res := make([]matlas.Label, list.Len()) diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index ce233dceef..139f03c5c8 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -438,8 +438,8 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. if ac, ok := d.GetOk("advanced_configuration"); ok { if aclist, ok := ac.([]any); ok && len(aclist) > 0 { - advancedConfReq := expandProcessArgs(d, aclist[0].(map[string]any)) - _, _, err := conn.Clusters.UpdateProcessArgs(ctx, projectID, cluster.GetName(), advancedConfReq) + params := expandProcessArgsV2(d, aclist[0].(map[string]any)) + _, _, err := connV2.ClustersApi.UpdateClusterAdvancedConfiguration(ctx, projectID, cluster.GetName(), params).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorConfigUpdate, cluster.GetName(), err)) } From 575fcd6f6bafb9494d36f96826b87c8dd6983eb1 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 13:44:36 +0100 Subject: [PATCH 38/52] expandProcessArgs --- .../advancedcluster/model_advanced_cluster.go | 64 +------------------ .../resource_advanced_cluster.go | 18 +++--- 2 files changed, 10 insertions(+), 72 deletions(-) diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index 59d527da42..c91dc28a75 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -803,69 +803,7 @@ func getAdvancedClusterContainerID(containers []admin.CloudProviderContainer, cl return "" } -func expandProcessArgs(d *schema.ResourceData, p map[string]any) *matlas.ProcessArgs { - res := &matlas.ProcessArgs{} - - if _, ok := d.GetOkExists("advanced_configuration.0.default_read_concern"); ok { - res.DefaultReadConcern = cast.ToString(p["default_read_concern"]) - } - - if _, ok := d.GetOkExists("advanced_configuration.0.default_write_concern"); ok { - res.DefaultWriteConcern = cast.ToString(p["default_write_concern"]) - } - - if _, ok := d.GetOkExists("advanced_configuration.0.fail_index_key_too_long"); ok { - res.FailIndexKeyTooLong = conversion.Pointer(cast.ToBool(p["fail_index_key_too_long"])) - } - - if _, ok := d.GetOkExists("advanced_configuration.0.javascript_enabled"); ok { - res.JavascriptEnabled = conversion.Pointer(cast.ToBool(p["javascript_enabled"])) - } - - if _, ok := d.GetOkExists("advanced_configuration.0.minimum_enabled_tls_protocol"); ok { - res.MinimumEnabledTLSProtocol = cast.ToString(p["minimum_enabled_tls_protocol"]) - } - - if _, ok := d.GetOkExists("advanced_configuration.0.no_table_scan"); ok { - res.NoTableScan = conversion.Pointer(cast.ToBool(p["no_table_scan"])) - } - - if _, ok := d.GetOkExists("advanced_configuration.0.sample_size_bi_connector"); ok { - res.SampleSizeBIConnector = conversion.Pointer(cast.ToInt64(p["sample_size_bi_connector"])) - } - - if _, ok := d.GetOkExists("advanced_configuration.0.sample_refresh_interval_bi_connector"); ok { - res.SampleRefreshIntervalBIConnector = conversion.Pointer(cast.ToInt64(p["sample_refresh_interval_bi_connector"])) - } - - if _, ok := d.GetOkExists("advanced_configuration.0.oplog_size_mb"); ok { - if sizeMB := cast.ToInt64(p["oplog_size_mb"]); sizeMB != 0 { - res.OplogSizeMB = conversion.Pointer(cast.ToInt64(p["oplog_size_mb"])) - } else { - log.Printf(ErrorClusterSetting, `oplog_size_mb`, "", cast.ToString(sizeMB)) - } - } - - if _, ok := d.GetOkExists("advanced_configuration.0.oplog_min_retention_hours"); ok { - if minRetentionHours := cast.ToFloat64(p["oplog_min_retention_hours"]); minRetentionHours >= 0 { - res.OplogMinRetentionHours = conversion.Pointer(cast.ToFloat64(p["oplog_min_retention_hours"])) - } else { - log.Printf(ErrorClusterSetting, `oplog_min_retention_hours`, "", cast.ToString(minRetentionHours)) - } - } - - if _, ok := d.GetOkExists("advanced_configuration.0.transaction_lifetime_limit_seconds"); ok { - if transactionLifetimeLimitSeconds := cast.ToInt64(p["transaction_lifetime_limit_seconds"]); transactionLifetimeLimitSeconds > 0 { - res.TransactionLifetimeLimitSeconds = conversion.Pointer(cast.ToInt64(p["transaction_lifetime_limit_seconds"])) - } else { - log.Printf(ErrorClusterSetting, `transaction_lifetime_limit_seconds`, "", cast.ToString(transactionLifetimeLimitSeconds)) - } - } - - return res -} - -func expandProcessArgsV2(d *schema.ResourceData, p map[string]any) *admin.ClusterDescriptionProcessArgs { +func expandProcessArgs(d *schema.ResourceData, p map[string]any) *admin.ClusterDescriptionProcessArgs { res := new(admin.ClusterDescriptionProcessArgs) if _, ok := d.GetOkExists("advanced_configuration.0.default_read_concern"); ok { diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 139f03c5c8..426e4a2844 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -438,7 +438,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. if ac, ok := d.GetOk("advanced_configuration"); ok { if aclist, ok := ac.([]any); ok && len(aclist) > 0 { - params := expandProcessArgsV2(d, aclist[0].(map[string]any)) + params := expandProcessArgs(d, aclist[0].(map[string]any)) _, _, err := connV2.ClustersApi.UpdateClusterAdvancedConfiguration(ctx, projectID, cluster.GetName(), params).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorConfigUpdate, cluster.GetName(), err)) @@ -584,13 +584,13 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di func resourceUpdateOrUpgrade(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { if upgradeRequest := getUpgradeRequest(d); upgradeRequest != nil { upgradeCtx := context.WithValue(ctx, upgradeRequestCtxKey, upgradeRequest) - return resourceMongoDBAtlasAdvancedClusterUpgrade(upgradeCtx, d, meta) + return resourceUpgrade(upgradeCtx, d, meta) } - return resourceMongoDBAtlasAdvancedClusterUpdate(ctx, d, meta) + return resourceUpdate(ctx, d, meta) } -func resourceMongoDBAtlasAdvancedClusterUpgrade(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { +func resourceUpgrade(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { conn := meta.(*config.MongoDBClient).Atlas ids := conversion.DecodeStateID(d.Id()) projectID := ids["project_id"] @@ -617,9 +617,9 @@ func resourceMongoDBAtlasAdvancedClusterUpgrade(ctx context.Context, d *schema.R return resourceRead(ctx, d, meta) } -func resourceMongoDBAtlasAdvancedClusterUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - // Get client connection. +func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) projectID := ids["project_id"] clusterName := ids["cluster_name"] @@ -696,9 +696,9 @@ func resourceMongoDBAtlasAdvancedClusterUpdate(ctx context.Context, d *schema.Re if d.HasChange("advanced_configuration") { ac := d.Get("advanced_configuration") if aclist, ok := ac.([]any); ok && len(aclist) > 0 { - advancedConfReq := expandProcessArgs(d, aclist[0].(map[string]any)) - if !reflect.DeepEqual(advancedConfReq, matlas.ProcessArgs{}) { - _, _, err := conn.Clusters.UpdateProcessArgs(ctx, projectID, clusterName, advancedConfReq) + params := expandProcessArgs(d, aclist[0].(map[string]any)) + if !reflect.DeepEqual(*params, admin.ClusterDescriptionProcessArgs{}) { + _, _, err := connV2.ClustersApi.UpdateClusterAdvancedConfiguration(ctx, projectID, clusterName, params).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorConfigUpdate, clusterName, err)) } From 687b62ca986b12a6d678ff0d26157ec70cc4c074 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 13:55:11 +0100 Subject: [PATCH 39/52] split ResourceClusterRefreshFunc --- .../resource_cloud_backup_snapshot.go | 4 +-- internal/service/cluster/resource_cluster.go | 35 +++++++++++++++++-- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot.go b/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot.go index b5134fda30..068670f143 100644 --- a/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot.go +++ b/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot.go @@ -13,7 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/advancedcluster" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/cluster" "go.mongodb.org/atlas-sdk/v20231115006/admin" ) @@ -131,7 +131,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. stateConf := &retry.StateChangeConf{ Pending: []string{"CREATING", "UPDATING", "REPAIRING", "REPEATING"}, Target: []string{"IDLE"}, - Refresh: advancedcluster.ResourceClusterRefreshFunc(ctx, d.Get("cluster_name").(string), d.Get("project_id").(string), advancedcluster.ServiceFromClient(conn)), + Refresh: cluster.ResourceClusterRefreshFunc(ctx, d.Get("cluster_name").(string), d.Get("project_id").(string), conn), Timeout: 15 * time.Minute, MinTimeout: 30 * time.Second, } diff --git a/internal/service/cluster/resource_cluster.go b/internal/service/cluster/resource_cluster.go index 6c437a72b6..d5a01e8ccf 100644 --- a/internal/service/cluster/resource_cluster.go +++ b/internal/service/cluster/resource_cluster.go @@ -9,6 +9,7 @@ import ( "net/http" "reflect" "regexp" + "strings" "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -538,7 +539,7 @@ func resourceMongoDBAtlasClusterCreate(ctx context.Context, d *schema.ResourceDa stateConf := &retry.StateChangeConf{ Pending: []string{"CREATING", "UPDATING", "REPAIRING", "REPEATING", "PENDING"}, Target: []string{"IDLE"}, - Refresh: advancedcluster.ResourceClusterRefreshFunc(ctx, d.Get("name").(string), projectID, advancedcluster.ServiceFromClient(conn)), + Refresh: ResourceClusterRefreshFunc(ctx, d.Get("name").(string), projectID, conn), Timeout: timeout, MinTimeout: 1 * time.Minute, Delay: 3 * time.Minute, @@ -1039,7 +1040,7 @@ func resourceMongoDBAtlasClusterDelete(ctx context.Context, d *schema.ResourceDa stateConf := &retry.StateChangeConf{ Pending: []string{"IDLE", "CREATING", "UPDATING", "REPAIRING", "DELETING"}, Target: []string{"DELETED"}, - Refresh: advancedcluster.ResourceClusterRefreshFunc(ctx, clusterName, projectID, advancedcluster.ServiceFromClient(conn)), + Refresh: ResourceClusterRefreshFunc(ctx, clusterName, projectID, conn), Timeout: d.Timeout(schema.TimeoutDelete), MinTimeout: 30 * time.Second, Delay: 1 * time.Minute, // Wait 30 secs before starting @@ -1186,7 +1187,7 @@ func updateCluster(ctx context.Context, conn *matlas.Client, request *matlas.Clu stateConf := &retry.StateChangeConf{ Pending: []string{"CREATING", "UPDATING", "REPAIRING"}, Target: []string{"IDLE"}, - Refresh: advancedcluster.ResourceClusterRefreshFunc(ctx, name, projectID, advancedcluster.ServiceFromClient(conn)), + Refresh: ResourceClusterRefreshFunc(ctx, name, projectID, conn), Timeout: timeout, MinTimeout: 30 * time.Second, Delay: 1 * time.Minute, @@ -1282,3 +1283,31 @@ func computedCloudProviderSnapshotBackupPolicySchema() *schema.Schema { }, } } + +func ResourceClusterRefreshFunc(ctx context.Context, name, projectID string, conn *matlas.Client) retry.StateRefreshFunc { + return func() (any, string, error) { + c, resp, err := conn.Clusters.Get(ctx, projectID, name) + + if err != nil && strings.Contains(err.Error(), "reset by peer") { + return nil, "REPEATING", nil + } + + if err != nil && c == nil && resp == nil { + return nil, "", err + } else if err != nil { + if resp.StatusCode == 404 { + return "", "DELETED", nil + } + if resp.StatusCode == 503 { + return "", "PENDING", nil + } + return nil, "", err + } + + if c.StateName != "" { + log.Printf("[DEBUG] status for MongoDB cluster: %s: %s", name, c.StateName) + } + + return c, c.StateName, nil + } +} From 5f37936be8cb513352cb38bf9f02584176606ad2 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 18:32:09 +0100 Subject: [PATCH 40/52] resourceRefreshFunc --- internal/common/conversion/type_conversion.go | 6 + .../common/conversion/type_conversion_test.go | 27 +++-- .../advancedcluster/model_advanced_cluster.go | 60 +--------- .../resource_advanced_cluster.go | 103 +++++++++--------- 4 files changed, 77 insertions(+), 119 deletions(-) diff --git a/internal/common/conversion/type_conversion.go b/internal/common/conversion/type_conversion.go index ae6fc6a254..21a555db76 100644 --- a/internal/common/conversion/type_conversion.go +++ b/internal/common/conversion/type_conversion.go @@ -29,6 +29,12 @@ func TimeToString(t time.Time) string { return t.UTC().Format(time.RFC3339Nano) } +// StringToTime is the opposite to TimeToString, returns ok if conversion is possible. +func StringToTime(str string) (time.Time, bool) { + ret, err := time.Parse(time.RFC3339Nano, str) + return ret, err == nil +} + func Int64PtrToIntPtr(i64 *int64) *int { if i64 == nil { return nil diff --git a/internal/common/conversion/type_conversion_test.go b/internal/common/conversion/type_conversion_test.go index cb0cfa0995..badf82f279 100644 --- a/internal/common/conversion/type_conversion_test.go +++ b/internal/common/conversion/type_conversion_test.go @@ -5,28 +5,39 @@ import ( "time" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" + "github.com/stretchr/testify/assert" ) -func TestTimeToStringWithoutNanos(t *testing.T) { +func TestTimeWithoutNanos(t *testing.T) { inputTime := time.Date(2023, time.July, 18, 16, 12, 23, 0, time.UTC) expectedOutput := "2023-07-18T16:12:23Z" result := conversion.TimeToString(inputTime) + assert.Equal(t, expectedOutput, result) - if result != expectedOutput { - t.Errorf("TimeToString(%v) = %v; want %v", inputTime, result, expectedOutput) - } + expectedTime, ok := conversion.StringToTime(result) + assert.True(t, ok) + assert.Equal(t, expectedTime, inputTime) } -func TestTimeToStringWithNanos(t *testing.T) { +func TestTimeWithNanos(t *testing.T) { inputTime := time.Date(2023, time.July, 18, 16, 12, 23, 456_000_000, time.UTC) expectedOutput := "2023-07-18T16:12:23.456Z" result := conversion.TimeToString(inputTime) + assert.Equal(t, expectedOutput, result) - if result != expectedOutput { - t.Errorf("TimeToString(%v) = %v; want %v", inputTime, result, expectedOutput) - } + expectedTime, ok := conversion.StringToTime(result) + assert.True(t, ok) + assert.Equal(t, expectedTime, inputTime) +} + +func TestStringToTimeInvalid(t *testing.T) { + _, ok := conversion.StringToTime("") + assert.False(t, ok) + + _, ok = conversion.StringToTime("123") + assert.False(t, ok) } func TestIsStringPresent(t *testing.T) { diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index c91dc28a75..b2b6d5e2bc 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -22,16 +22,7 @@ import ( matlas "go.mongodb.org/atlas/mongodbatlas" ) -const ( - ErrorClusterSetting = "error setting `%s` for MongoDB Cluster (%s): %s" - ErrorAdvancedConfRead = "error reading Advanced Configuration Option form MongoDB Cluster (%s): %s" - ErrorClusterAdvancedSetting = "error setting `%s` for MongoDB ClusterAdvanced (%s): %s" - ErrorAdvancedClusterListStatus = "error awaiting MongoDB ClusterAdvanced List IDLE: %s" - ignoreLabel = "Infrastructure Tool" -) - var ( - defaultLabel = matlas.Label{Key: "Infrastructure Tool", Value: "MongoDB Atlas Terraform Provider"} DSTagsSchema = schema.Schema{ Type: schema.TypeSet, Computed: true, @@ -471,27 +462,7 @@ func flattenBiConnectorConfig(biConnector admin.BiConnector) []map[string]any { } } -func expandBiConnectorConfig(d *schema.ResourceData) (*matlas.BiConnector, error) { - var biConnector matlas.BiConnector - - if v, ok := d.GetOk("bi_connector_config"); ok { - biConn := v.([]any) - if len(biConn) > 0 { - biConnMap := biConn[0].(map[string]any) - - enabled := cast.ToBool(biConnMap["enabled"]) - - biConnector = matlas.BiConnector{ - Enabled: &enabled, - ReadPreference: cast.ToString(biConnMap["read_preference"]), - } - } - } - - return &biConnector, nil -} - -func expandBiConnectorConfigV2(d *schema.ResourceData) *admin.BiConnector { +func expandBiConnectorConfig(d *schema.ResourceData) *admin.BiConnector { if v, ok := d.GetOk("bi_connector_config"); ok { if biConn := v.([]any); len(biConn) > 0 { biConnMap := biConn[0].(map[string]any) @@ -504,19 +475,6 @@ func expandBiConnectorConfigV2(d *schema.ResourceData) *admin.BiConnector { return nil } -func expandTagSliceFromSetSchema(d *schema.ResourceData) []*matlas.Tag { - list := d.Get("tags").(*schema.Set) - res := make([]*matlas.Tag, list.Len()) - for i, val := range list.List() { - v := val.(map[string]any) - res[i] = &matlas.Tag{ - Key: v["key"].(string), - Value: v["value"].(string), - } - } - return res -} - func flattenProcessArgs(p *admin.ClusterDescriptionProcessArgs) []map[string]any { if p == nil { return nil @@ -865,21 +823,7 @@ func expandProcessArgs(d *schema.ResourceData, p map[string]any) *admin.ClusterD return res } -func expandLabelSliceFromSetSchema(d *schema.ResourceData) []matlas.Label { - list := d.Get("labels").(*schema.Set) - res := make([]matlas.Label, list.Len()) - - for i, val := range list.List() { - v := val.(map[string]any) - res[i] = matlas.Label{ - Key: v["key"].(string), - Value: v["value"].(string), - } - } - return res -} - -func expandLabelSliceFromSetSchemaV2(d *schema.ResourceData) ([]admin.ComponentLabel, diag.Diagnostics) { +func expandLabelSliceFromSetSchema(d *schema.ResourceData) ([]admin.ComponentLabel, diag.Diagnostics) { list := d.Get("labels").(*schema.Set) res := make([]admin.ComponentLabel, list.Len()) for i, val := range list.List() { diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 426e4a2844..c9050eca7b 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -25,12 +25,17 @@ import ( ) const ( - errorCreate = "error creating advanced cluster: %s" - errorRead = "error reading advanced cluster (%s): %s" - errorDelete = "error deleting advanced cluster (%s): %s" - errorUpdate = "error updating advanced cluster (%s): %s" - errorConfigUpdate = "error updating advanced cluster configuration options (%s): %s" - errorConfigRead = "error reading advanced cluster configuration options (%s): %s" + errorCreate = "error creating advanced cluster: %s" + errorRead = "error reading advanced cluster (%s): %s" + errorDelete = "error deleting advanced cluster (%s): %s" + errorUpdate = "error updating advanced cluster (%s): %s" + errorConfigUpdate = "error updating advanced cluster configuration options (%s): %s" + errorConfigRead = "error reading advanced cluster configuration options (%s): %s" + ErrorClusterSetting = "error setting `%s` for MongoDB Cluster (%s): %s" + ErrorAdvancedConfRead = "error reading Advanced Configuration Option form MongoDB Cluster (%s): %s" + ErrorClusterAdvancedSetting = "error setting `%s` for MongoDB ClusterAdvanced (%s): %s" + ErrorAdvancedClusterListStatus = "error awaiting MongoDB ClusterAdvanced List IDLE: %s" + ignoreLabel = "Infrastructure Tool" ) type acCtxKey string @@ -357,10 +362,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf("accept_data_risks_and_force_replica_set_reconfig can not be set in creation, only in update")) } } - - conn := meta.(*config.MongoDBClient).Atlas connV2 := meta.(*config.MongoDBClient).AtlasV2 - projectID := d.Get("project_id").(string) params := &admin.AdvancedClusterDescription{ @@ -373,7 +375,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. params.BackupEnabled = conversion.Pointer(v.(bool)) } if _, ok := d.GetOk("bi_connector_config"); ok { - params.BiConnector = expandBiConnectorConfigV2(d) + params.BiConnector = expandBiConnectorConfig(d) } if v, ok := d.GetOk("disk_size_gb"); ok { params.DiskSizeGB = conversion.Pointer(v.(float64)) @@ -383,9 +385,9 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if _, ok := d.GetOk("labels"); ok { - labels, err := expandLabelSliceFromSetSchemaV2(d) + labels, err := expandLabelSliceFromSetSchema(d) if err != nil { - return nil + return err } params.Labels = &labels } @@ -425,7 +427,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. stateConf := &retry.StateChangeConf{ Pending: []string{"CREATING", "UPDATING", "REPAIRING", "REPEATING", "PENDING"}, Target: []string{"IDLE"}, - Refresh: resourceRefreshFunc(ctx, d.Get("name").(string), projectID, conn), + Refresh: resourceRefreshFunc(ctx, d.Get("name").(string), projectID, connV2), Timeout: timeout, MinTimeout: 1 * time.Minute, Delay: 3 * time.Minute, @@ -447,11 +449,10 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if v := d.Get("paused").(bool); v { - request := &matlas.AdvancedCluster{ + request := &admin.AdvancedClusterDescription{ Paused: conversion.Pointer(v), } - - _, _, err = updateAdvancedCluster(ctx, conn, request, projectID, d.Get("name").(string), timeout) + _, _, err = updateAdvancedCluster(ctx, connV2, request, projectID, d.Get("name").(string), timeout) if err != nil { return diag.FromErr(fmt.Errorf(errorUpdate, d.Get("name").(string), err)) } @@ -618,25 +619,24 @@ func resourceUpgrade(ctx context.Context, d *schema.ResourceData, meta any) diag } func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) projectID := ids["project_id"] clusterName := ids["cluster_name"] - cluster := new(matlas.AdvancedCluster) - clusterChangeDetect := new(matlas.AdvancedCluster) + cluster := new(admin.AdvancedClusterDescription) + clusterChangeDetect := new(admin.AdvancedClusterDescription) if d.HasChange("backup_enabled") { cluster.BackupEnabled = conversion.Pointer(d.Get("backup_enabled").(bool)) } if d.HasChange("bi_connector_config") { - cluster.BiConnector, _ = expandBiConnectorConfig(d) + cluster.BiConnector = expandBiConnectorConfig(d) } if d.HasChange("cluster_type") { - cluster.ClusterType = d.Get("cluster_type").(string) + cluster.ClusterType = conversion.StringPtr(d.Get("cluster_type").(string)) } if d.HasChange("disk_size_gb") { @@ -644,23 +644,23 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if d.HasChange("encryption_at_rest_provider") { - cluster.EncryptionAtRestProvider = d.Get("encryption_at_rest_provider").(string) + cluster.EncryptionAtRestProvider = conversion.StringPtr(d.Get("encryption_at_rest_provider").(string)) } if d.HasChange("labels") { - if ContainsLabelOrKey(expandLabelSliceFromSetSchema(d), defaultLabel) { - return diag.FromErr(fmt.Errorf("you should not set `Infrastructure Tool` label, it is used for internal purposes")) + labels, err := expandLabelSliceFromSetSchema(d) + if err != nil { + return err } - - cluster.Labels = append(expandLabelSliceFromSetSchema(d), defaultLabel) + cluster.Labels = &labels } if d.HasChange("tags") { - cluster.Tags = expandTagSliceFromSetSchema(d) + cluster.Tags = conversion.ExpandTagsFromSetSchema(d) } if d.HasChange("mongo_db_major_version") { - cluster.MongoDBMajorVersion = FormatMongoDBMajorVersion(d.Get("mongo_db_major_version")) + cluster.MongoDBMajorVersion = conversion.StringPtr(FormatMongoDBMajorVersion(d.Get("mongo_db_major_version"))) } if d.HasChange("pit_enabled") { @@ -668,11 +668,11 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if d.HasChange("replication_specs") { - cluster.ReplicationSpecs = expandAdvancedReplicationSpecs(d.Get("replication_specs").([]any)) + cluster.ReplicationSpecs = expandAdvancedReplicationSpecsV2(d.Get("replication_specs").([]any)) } if d.HasChange("root_cert_type") { - cluster.RootCertType = d.Get("root_cert_type").(string) + cluster.RootCertType = conversion.StringPtr(d.Get("root_cert_type").(string)) } if d.HasChange("termination_protection_enabled") { @@ -680,11 +680,15 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if d.HasChange("version_release_system") { - cluster.VersionReleaseSystem = d.Get("version_release_system").(string) + cluster.VersionReleaseSystem = conversion.StringPtr(d.Get("version_release_system").(string)) } if d.HasChange("accept_data_risks_and_force_replica_set_reconfig") { - cluster.AcceptDataRisksAndForceReplicaSetReconfig = d.Get("accept_data_risks_and_force_replica_set_reconfig").(string) + t, ok := conversion.StringToTime(d.Get("accept_data_risks_and_force_replica_set_reconfig").(string)) + if !ok { + return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, "accept_data_risks_and_force_replica_set_reconfig time format is incorrect")) + } + cluster.AcceptDataRisksAndForceReplicaSetReconfig = &t } if d.HasChange("paused") && !d.Get("paused").(bool) { @@ -709,7 +713,7 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. // Has changes if !reflect.DeepEqual(cluster, clusterChangeDetect) { err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { - _, resp, err := updateAdvancedCluster(ctx, conn, cluster, projectID, clusterName, timeout) + _, resp, err := updateAdvancedCluster(ctx, connV2, cluster, projectID, clusterName, timeout) if err != nil { if resp == nil || resp.StatusCode == 400 { return retry.NonRetryableError(fmt.Errorf(errorUpdate, clusterName, err)) @@ -724,11 +728,10 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if d.Get("paused").(bool) { - clusterRequest := &matlas.AdvancedCluster{ + clusterRequest := &admin.AdvancedClusterDescription{ Paused: conversion.Pointer(true), } - - _, _, err := updateAdvancedCluster(ctx, conn, clusterRequest, projectID, clusterName, timeout) + _, _, err := updateAdvancedCluster(ctx, connV2, clusterRequest, projectID, clusterName, timeout) if err != nil { return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, err)) } @@ -738,7 +741,6 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. } func resourceDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) projectID := ids["project_id"] @@ -762,7 +764,7 @@ func resourceDelete(ctx context.Context, d *schema.ResourceData, meta any) diag. stateConf := &retry.StateChangeConf{ Pending: []string{"IDLE", "CREATING", "UPDATING", "REPAIRING", "DELETING"}, Target: []string{"DELETED"}, - Refresh: resourceRefreshFunc(ctx, clusterName, projectID, conn), + Refresh: resourceRefreshFunc(ctx, clusterName, projectID, connV2), Timeout: d.Timeout(schema.TimeoutDelete), MinTimeout: 30 * time.Second, Delay: 1 * time.Minute, // Wait 30 secs before starting @@ -822,15 +824,14 @@ func splitSClusterAdvancedImportID(id string) (projectID, clusterName *string, e return } -func resourceRefreshFunc(ctx context.Context, name, projectID string, client *matlas.Client) retry.StateRefreshFunc { +func resourceRefreshFunc(ctx context.Context, name, projectID string, connV2 *admin.APIClient) retry.StateRefreshFunc { return func() (any, string, error) { - c, resp, err := client.AdvancedClusters.Get(ctx, projectID, name) - + cluster, resp, err := connV2.ClustersApi.GetCluster(ctx, projectID, name).Execute() if err != nil && strings.Contains(err.Error(), "reset by peer") { return nil, "REPEATING", nil } - if err != nil && c == nil && resp == nil { + if err != nil && cluster == nil && resp == nil { return nil, "", err } @@ -844,11 +845,8 @@ func resourceRefreshFunc(ctx context.Context, name, projectID string, client *ma return nil, "", err } - if c.StateName != "" { - log.Printf("[DEBUG] status for MongoDB cluster: %s: %s", name, c.StateName) - } - - return c, c.StateName, nil + state := cluster.GetStateName() + return cluster, state, nil } } @@ -893,12 +891,12 @@ func getUpgradeRequest(d *schema.ResourceData) *matlas.Cluster { func updateAdvancedCluster( ctx context.Context, - conn *matlas.Client, - request *matlas.AdvancedCluster, + connV2 *admin.APIClient, + request *admin.AdvancedClusterDescription, projectID, name string, timeout time.Duration, -) (*matlas.AdvancedCluster, *matlas.Response, error) { - cluster, resp, err := conn.AdvancedClusters.Update(ctx, projectID, name, request) +) (*admin.AdvancedClusterDescription, *http.Response, error) { + cluster, resp, err := connV2.ClustersApi.UpdateCluster(ctx, projectID, name, request).Execute() if err != nil { return nil, nil, err } @@ -906,13 +904,12 @@ func updateAdvancedCluster( stateConf := &retry.StateChangeConf{ Pending: []string{"CREATING", "UPDATING", "REPAIRING"}, Target: []string{"IDLE"}, - Refresh: resourceRefreshFunc(ctx, name, projectID, conn), + Refresh: resourceRefreshFunc(ctx, name, projectID, connV2), Timeout: timeout, MinTimeout: 30 * time.Second, Delay: 1 * time.Minute, } - // Wait, catching any errors _, err = stateConf.WaitForStateContext(ctx) if err != nil { return nil, nil, err From 6be017028bf5a34df8f3a997f77d7b43ee675ce3 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 20:58:12 +0100 Subject: [PATCH 41/52] UpgradeCluster --- .../advancedcluster/model_advanced_cluster.go | 44 ++++----- .../model_advanced_cluster_test.go | 76 ++++++++-------- .../resource_advanced_cluster.go | 8 +- .../service_advanced_cluster.go | 24 +++-- internal/service/cluster/model_cluster.go | 10 +++ internal/service/cluster/resource_cluster.go | 32 ++++++- ...resource_private_endpoint_regional_mode.go | 3 +- .../resource_privatelink_endpoint_service.go | 6 +- internal/testutil/mocksvc/cluster_service.go | 90 ++++++------------- 9 files changed, 142 insertions(+), 151 deletions(-) diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index b2b6d5e2bc..8d4f7da484 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -6,7 +6,7 @@ import ( "fmt" "hash/crc32" "log" - "reflect" + "net/http" "slices" "strings" "time" @@ -269,16 +269,6 @@ func StringIsUppercase() schema.SchemaValidateDiagFunc { } } -func ContainsLabelOrKey(list []matlas.Label, item matlas.Label) bool { - for _, v := range list { - if reflect.DeepEqual(v, item) || v.Key == item.Key { - return true - } - } - - return false -} - func HashFunctionForKeyValuePair(v any) int { var buf bytes.Buffer m := v.(map[string]any) @@ -308,10 +298,10 @@ func IsSharedTier(instanceSize string) bool { return instanceSize == "M0" || instanceSize == "M2" || instanceSize == "M5" } -func UpgradeCluster(ctx context.Context, conn *matlas.Client, request *matlas.Cluster, projectID, name string, timeout time.Duration) (*matlas.Cluster, *matlas.Response, error) { +func UpgradeCluster(ctx context.Context, connV2 *admin.APIClient, request *admin.LegacyAtlasTenantClusterUpgradeRequest, projectID, name string, timeout time.Duration) (*admin.LegacyAtlasCluster, *http.Response, error) { request.Name = name - cluster, resp, err := conn.Clusters.Upgrade(ctx, projectID, request) + cluster, resp, err := connV2.ClustersApi.UpgradeSharedCluster(ctx, projectID, request).Execute() if err != nil { return nil, nil, err } @@ -319,7 +309,7 @@ func UpgradeCluster(ctx context.Context, conn *matlas.Client, request *matlas.Cl stateConf := &retry.StateChangeConf{ Pending: []string{"CREATING", "UPDATING", "REPAIRING"}, Target: []string{"IDLE"}, - Refresh: ResourceClusterRefreshFunc(ctx, name, projectID, ServiceFromClient(conn)), + Refresh: UpgradeRefreshFunc(ctx, name, projectID, ServiceFromClient(connV2)), Timeout: timeout, MinTimeout: 30 * time.Second, Delay: 1 * time.Minute, @@ -334,15 +324,15 @@ func UpgradeCluster(ctx context.Context, conn *matlas.Client, request *matlas.Cl return cluster, resp, nil } -func ResourceClusterRefreshFunc(ctx context.Context, name, projectID string, client ClusterService) retry.StateRefreshFunc { +func UpgradeRefreshFunc(ctx context.Context, name, projectID string, client ClusterService) retry.StateRefreshFunc { return func() (any, string, error) { - c, resp, err := client.Get(ctx, projectID, name) + cluster, resp, err := client.Get(ctx, projectID, name) if err != nil && strings.Contains(err.Error(), "reset by peer") { return nil, "REPEATING", nil } - if err != nil && c == nil && resp == nil { + if err != nil && cluster == nil && resp == nil { return nil, "", err } else if err != nil { if resp.StatusCode == 404 { @@ -354,17 +344,17 @@ func ResourceClusterRefreshFunc(ctx context.Context, name, projectID string, cli return nil, "", err } - if c.StateName != "" { - log.Printf("[DEBUG] status for MongoDB cluster: %s: %s", name, c.StateName) - } - - return c, c.StateName, nil + state := cluster.GetStateName() + return cluster, state, nil } } func ResourceClusterListAdvancedRefreshFunc(ctx context.Context, projectID string, client ClusterService) retry.StateRefreshFunc { return func() (any, string, error) { - clusters, resp, err := client.List(ctx, projectID, nil) + params := &admin.ListClustersApiParams{ + GroupId: projectID, + } + clusters, resp, err := client.List(ctx, params) if err != nil && strings.Contains(err.Error(), "reset by peer") { return nil, "REPEATING", nil @@ -384,12 +374,12 @@ func ResourceClusterListAdvancedRefreshFunc(ctx context.Context, projectID strin return nil, "", err } - for i := range clusters.Results { - if clusters.Results[i].StateName != "IDLE" { - return clusters.Results[i], "PENDING", nil + for i := range clusters.GetResults() { + cluster := clusters.GetResults()[i] + if cluster.GetStateName() != "IDLE" { + return cluster, "PENDING", nil } } - return clusters, "IDLE", nil } } diff --git a/internal/service/advancedcluster/model_advanced_cluster_test.go b/internal/service/advancedcluster/model_advanced_cluster_test.go index 60edba75f8..ae62f5962e 100644 --- a/internal/service/advancedcluster/model_advanced_cluster_test.go +++ b/internal/service/advancedcluster/model_advanced_cluster_test.go @@ -2,21 +2,23 @@ package advancedcluster_test import ( "context" + "errors" "net/http" "testing" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/advancedcluster" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mocksvc" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" - matlas "go.mongodb.org/atlas/mongodbatlas" + "go.mongodb.org/atlas-sdk/v20231115006/admin" ) var ( dummyClusterName = "clusterName" dummyProjectID = "projectId" - genericError = matlas.NewArgError("error", "generic") - advancedClusters = []*matlas.AdvancedCluster{{StateName: "NOT IDLE"}} + errGeneric = errors.New("generic") + advancedClusters = []admin.AdvancedClusterDescription{{StateName: conversion.StringPtr("NOT IDLE")}} ) type Result struct { @@ -25,10 +27,10 @@ type Result struct { state string } -func TestResourceClusterRefreshFunc(t *testing.T) { +func TestUpgradeRefreshFunc(t *testing.T) { testCases := []struct { - mockCluster *matlas.Cluster - mockResponse *matlas.Response + mockCluster *admin.AdvancedClusterDescription + mockResponse *http.Response expectedResult Result mockError error name string @@ -36,7 +38,7 @@ func TestResourceClusterRefreshFunc(t *testing.T) { }{ { name: "Error in the API call: reset by peer", - mockError: matlas.NewArgError("error", "reset by peer"), + mockError: errors.New("reset by peer"), expectedError: false, expectedResult: Result{ response: nil, @@ -46,18 +48,18 @@ func TestResourceClusterRefreshFunc(t *testing.T) { }, { name: "Generic error in the API call", - mockError: genericError, + mockError: errGeneric, expectedError: true, expectedResult: Result{ response: nil, state: "", - error: genericError, + error: errGeneric, }, }, { name: "Error in the API call: HTTP 404", - mockError: genericError, - mockResponse: &matlas.Response{Response: &http.Response{StatusCode: 404}, Links: nil, Raw: nil}, + mockError: errGeneric, + mockResponse: &http.Response{StatusCode: 404}, expectedError: false, expectedResult: Result{ response: "", @@ -67,8 +69,8 @@ func TestResourceClusterRefreshFunc(t *testing.T) { }, { name: "Error in the API call: HTTP 503", - mockError: genericError, - mockResponse: &matlas.Response{Response: &http.Response{StatusCode: 503}, Links: nil, Raw: nil}, + mockError: errGeneric, + mockResponse: &http.Response{StatusCode: 503}, expectedError: false, expectedResult: Result{ response: "", @@ -78,22 +80,22 @@ func TestResourceClusterRefreshFunc(t *testing.T) { }, { name: "Error in the API call: Neither HTTP 503 or 404", - mockError: genericError, - mockResponse: &matlas.Response{Response: &http.Response{StatusCode: 400}, Links: nil, Raw: nil}, + mockError: errGeneric, + mockResponse: &http.Response{StatusCode: 400}, expectedError: true, expectedResult: Result{ response: nil, state: "", - error: genericError, + error: errGeneric, }, }, { name: "Successful", - mockCluster: &matlas.Cluster{StateName: "stateName"}, - mockResponse: &matlas.Response{Response: &http.Response{StatusCode: 200}, Links: nil, Raw: nil}, + mockCluster: &admin.AdvancedClusterDescription{StateName: conversion.StringPtr("stateName")}, + mockResponse: &http.Response{StatusCode: 200}, expectedError: false, expectedResult: Result{ - response: &matlas.Cluster{StateName: "stateName"}, + response: &admin.AdvancedClusterDescription{StateName: conversion.StringPtr("stateName")}, state: "stateName", error: nil, }, @@ -106,7 +108,7 @@ func TestResourceClusterRefreshFunc(t *testing.T) { testObject.On("Get", mock.Anything, mock.Anything, mock.Anything).Return(tc.mockCluster, tc.mockResponse, tc.mockError) - result, stateName, err := advancedcluster.ResourceClusterRefreshFunc(context.Background(), dummyClusterName, dummyProjectID, testObject)() + result, stateName, err := advancedcluster.UpgradeRefreshFunc(context.Background(), dummyClusterName, dummyProjectID, testObject)() if (err != nil) != tc.expectedError { t.Errorf("Case %s: Received unexpected error: %v", tc.name, err) } @@ -153,8 +155,8 @@ func TestStringIsUppercase(t *testing.T) { func TestResourceListAdvancedRefreshFunc(t *testing.T) { testCases := []struct { - mockCluster *matlas.AdvancedClustersResponse - mockResponse *matlas.Response + mockCluster *admin.PaginatedAdvancedClusterDescription + mockResponse *http.Response expectedResult Result mockError error name string @@ -162,7 +164,7 @@ func TestResourceListAdvancedRefreshFunc(t *testing.T) { }{ { name: "Error in the API call: reset by peer", - mockError: matlas.NewArgError("error", "reset by peer"), + mockError: errors.New("reset by peer"), expectedError: false, expectedResult: Result{ response: nil, @@ -172,18 +174,18 @@ func TestResourceListAdvancedRefreshFunc(t *testing.T) { }, { name: "Generic error in the API call", - mockError: genericError, + mockError: errGeneric, expectedError: true, expectedResult: Result{ response: nil, state: "", - error: genericError, + error: errGeneric, }, }, { name: "Error in the API call: HTTP 404", - mockError: genericError, - mockResponse: &matlas.Response{Response: &http.Response{StatusCode: 404}, Links: nil, Raw: nil}, + mockError: errGeneric, + mockResponse: &http.Response{StatusCode: 404}, expectedError: false, expectedResult: Result{ response: "", @@ -193,8 +195,8 @@ func TestResourceListAdvancedRefreshFunc(t *testing.T) { }, { name: "Error in the API call: HTTP 503", - mockError: genericError, - mockResponse: &matlas.Response{Response: &http.Response{StatusCode: 503}, Links: nil, Raw: nil}, + mockError: errGeneric, + mockResponse: &http.Response{StatusCode: 503}, expectedError: false, expectedResult: Result{ response: "", @@ -204,19 +206,19 @@ func TestResourceListAdvancedRefreshFunc(t *testing.T) { }, { name: "Error in the API call: Neither HTTP 503 or 404", - mockError: genericError, - mockResponse: &matlas.Response{Response: &http.Response{StatusCode: 400}, Links: nil, Raw: nil}, + mockError: errGeneric, + mockResponse: &http.Response{StatusCode: 400}, expectedError: true, expectedResult: Result{ response: nil, state: "", - error: genericError, + error: errGeneric, }, }, { name: "Successful but with at least one cluster not idle", - mockCluster: &matlas.AdvancedClustersResponse{Results: advancedClusters}, - mockResponse: &matlas.Response{Response: &http.Response{StatusCode: 200}, Links: nil, Raw: nil}, + mockCluster: &admin.PaginatedAdvancedClusterDescription{Results: &advancedClusters}, + mockResponse: &http.Response{StatusCode: 200}, expectedError: false, expectedResult: Result{ response: advancedClusters[0], @@ -226,11 +228,11 @@ func TestResourceListAdvancedRefreshFunc(t *testing.T) { }, { name: "Successful", - mockCluster: &matlas.AdvancedClustersResponse{}, - mockResponse: &matlas.Response{Response: &http.Response{StatusCode: 200}, Links: nil, Raw: nil}, + mockCluster: &admin.PaginatedAdvancedClusterDescription{}, + mockResponse: &http.Response{StatusCode: 200}, expectedError: false, expectedResult: Result{ - response: &matlas.AdvancedClustersResponse{}, + response: &admin.PaginatedAdvancedClusterDescription{}, state: "IDLE", error: nil, }, diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index c9050eca7b..9761e1522f 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -592,25 +592,25 @@ func resourceUpdateOrUpgrade(ctx context.Context, d *schema.ResourceData, meta a } func resourceUpgrade(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) projectID := ids["project_id"] clusterName := ids["cluster_name"] - upgradeRequest := ctx.Value(upgradeRequestCtxKey).(*matlas.Cluster) + upgradeRequest := ctx.Value(upgradeRequestCtxKey).(*admin.LegacyAtlasTenantClusterUpgradeRequest) if upgradeRequest == nil { return diag.FromErr(fmt.Errorf("upgrade called without %s in ctx", string(upgradeRequestCtxKey))) } - upgradeResponse, _, err := UpgradeCluster(ctx, conn, upgradeRequest, projectID, clusterName, d.Timeout(schema.TimeoutUpdate)) + upgradeResponse, _, err := UpgradeCluster(ctx, connV2, upgradeRequest, projectID, clusterName, d.Timeout(schema.TimeoutUpdate)) if err != nil { return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, err)) } d.SetId(conversion.EncodeStateID(map[string]string{ - "cluster_id": upgradeResponse.ID, + "cluster_id": upgradeResponse.GetId(), "project_id": projectID, "cluster_name": clusterName, })) diff --git a/internal/service/advancedcluster/service_advanced_cluster.go b/internal/service/advancedcluster/service_advanced_cluster.go index 95571fe8ef..e991ecf3c9 100644 --- a/internal/service/advancedcluster/service_advanced_cluster.go +++ b/internal/service/advancedcluster/service_advanced_cluster.go @@ -2,33 +2,29 @@ package advancedcluster import ( "context" + "net/http" - matlas "go.mongodb.org/atlas/mongodbatlas" + "go.mongodb.org/atlas-sdk/v20231115006/admin" ) type ClusterService interface { - Get(ctx context.Context, groupID, clusterName string) (*matlas.Cluster, *matlas.Response, error) - List(ctx context.Context, groupID string, options *matlas.ListOptions) (*matlas.AdvancedClustersResponse, *matlas.Response, error) - GetAdvancedCluster(ctx context.Context, groupID, clusterName string) (*matlas.AdvancedCluster, *matlas.Response, error) + Get(ctx context.Context, groupID, clusterName string) (*admin.AdvancedClusterDescription, *http.Response, error) + List(ctx context.Context, options *admin.ListClustersApiParams) (*admin.PaginatedAdvancedClusterDescription, *http.Response, error) } type ClusterServiceFromClient struct { - client *matlas.Client + client *admin.APIClient } -func (a *ClusterServiceFromClient) Get(ctx context.Context, groupID, clusterName string) (*matlas.Cluster, *matlas.Response, error) { - return a.client.Clusters.Get(ctx, groupID, clusterName) +func (a *ClusterServiceFromClient) Get(ctx context.Context, groupID, clusterName string) (*admin.AdvancedClusterDescription, *http.Response, error) { + return a.client.ClustersApi.GetCluster(ctx, groupID, clusterName).Execute() } -func (a *ClusterServiceFromClient) GetAdvancedCluster(ctx context.Context, groupID, clusterName string) (*matlas.AdvancedCluster, *matlas.Response, error) { - return a.client.AdvancedClusters.Get(ctx, groupID, clusterName) +func (a *ClusterServiceFromClient) List(ctx context.Context, options *admin.ListClustersApiParams) (*admin.PaginatedAdvancedClusterDescription, *http.Response, error) { + return a.client.ClustersApi.ListClustersWithParams(ctx, options).Execute() } -func (a *ClusterServiceFromClient) List(ctx context.Context, groupID string, options *matlas.ListOptions) (*matlas.AdvancedClustersResponse, *matlas.Response, error) { - return a.client.AdvancedClusters.List(ctx, groupID, options) -} - -func ServiceFromClient(client *matlas.Client) ClusterService { +func ServiceFromClient(client *admin.APIClient) ClusterService { return &ClusterServiceFromClient{ client: client, } diff --git a/internal/service/cluster/model_cluster.go b/internal/service/cluster/model_cluster.go index 1a5f38f603..e68b5d39ec 100644 --- a/internal/service/cluster/model_cluster.go +++ b/internal/service/cluster/model_cluster.go @@ -516,3 +516,13 @@ func flattenProviderSettings(d *schema.ResourceData, settings *matlas.ProviderSe log.Printf(advancedcluster.ErrorClusterSetting, "provider_volume_type", clusterName, err) } } + +func containsLabelOrKey(list []matlas.Label, item matlas.Label) bool { + for _, v := range list { + if reflect.DeepEqual(v, item) || v.Key == item.Key { + return true + } + } + + return false +} diff --git a/internal/service/cluster/resource_cluster.go b/internal/service/cluster/resource_cluster.go index d5a01e8ccf..cf25619cf6 100644 --- a/internal/service/cluster/resource_cluster.go +++ b/internal/service/cluster/resource_cluster.go @@ -493,7 +493,7 @@ func resourceMongoDBAtlasClusterCreate(ctx context.Context, d *schema.ResourceDa clusterRequest.BiConnector = biConnector } - if advancedcluster.ContainsLabelOrKey(expandLabelSliceFromSetSchema(d), defaultLabel) { + if containsLabelOrKey(expandLabelSliceFromSetSchema(d), defaultLabel) { return diag.FromErr(fmt.Errorf("you should not set `Infrastructure Tool` label, it is used for internal purposes")) } @@ -893,7 +893,7 @@ func resourceMongoDBAtlasClusterUpdate(ctx context.Context, d *schema.ResourceDa } if d.HasChange("labels") { - if advancedcluster.ContainsLabelOrKey(expandLabelSliceFromSetSchema(d), defaultLabel) { + if containsLabelOrKey(expandLabelSliceFromSetSchema(d), defaultLabel) { return diag.FromErr(fmt.Errorf("you should not set `Infrastructure Tool` label, it is used for internal purposes")) } @@ -935,7 +935,7 @@ func resourceMongoDBAtlasClusterUpdate(ctx context.Context, d *schema.ResourceDa } if isUpgradeRequired(d) { - updatedCluster, _, err := advancedcluster.UpgradeCluster(ctx, conn, cluster, projectID, clusterName, timeout) + updatedCluster, _, err := upgradeCluster(ctx, conn, cluster, projectID, clusterName, timeout) if err != nil { return diag.FromErr(fmt.Errorf(errorClusterUpdate, clusterName, err)) @@ -1311,3 +1311,29 @@ func ResourceClusterRefreshFunc(ctx context.Context, name, projectID string, con return c, c.StateName, nil } } + +func upgradeCluster(ctx context.Context, conn *matlas.Client, request *matlas.Cluster, projectID, name string, timeout time.Duration) (*matlas.Cluster, *matlas.Response, error) { + request.Name = name + + cluster, resp, err := conn.Clusters.Upgrade(ctx, projectID, request) + if err != nil { + return nil, nil, err + } + + stateConf := &retry.StateChangeConf{ + Pending: []string{"CREATING", "UPDATING", "REPAIRING"}, + Target: []string{"IDLE"}, + Refresh: ResourceClusterRefreshFunc(ctx, name, projectID, conn), + Timeout: timeout, + MinTimeout: 30 * time.Second, + Delay: 1 * time.Minute, + } + + // Wait, catching any errors + _, err = stateConf.WaitForStateContext(ctx) + if err != nil { + return nil, nil, err + } + + return cluster, resp, nil +} diff --git a/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode.go b/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode.go index 67d322f1c7..7f8a37f861 100644 --- a/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode.go +++ b/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode.go @@ -88,6 +88,7 @@ func resourceMongoDBAtlasPrivateEndpointRegionalModeRead(ctx context.Context, d func resourceMongoDBAtlasPrivateEndpointRegionalModeUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Id() enabled := d.Get("enabled").(bool) @@ -111,7 +112,7 @@ func resourceMongoDBAtlasPrivateEndpointRegionalModeUpdate(ctx context.Context, stateConf := &retry.StateChangeConf{ Pending: []string{"REPEATING", "PENDING"}, Target: []string{"IDLE", "DELETED"}, - Refresh: advancedcluster.ResourceClusterListAdvancedRefreshFunc(ctx, projectID, advancedcluster.ServiceFromClient(conn)), + Refresh: advancedcluster.ResourceClusterListAdvancedRefreshFunc(ctx, projectID, advancedcluster.ServiceFromClient(connV2)), Timeout: d.Timeout(timeoutKey.(string)), MinTimeout: 5 * time.Second, Delay: 3 * time.Second, diff --git a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go index 086a7596ae..7539d16ece 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go @@ -142,6 +142,7 @@ func Resource() *schema.Resource { func resourceMongoDBAtlasPrivateEndpointServiceLinkCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) privateLinkID := conversion.GetEncodedID(d.Get("private_link_id").(string), "private_link_id") providerName := d.Get("provider_name").(string) @@ -192,7 +193,7 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkCreate(ctx context.Context, d clusterConf := &retry.StateChangeConf{ Pending: []string{"REPEATING", "PENDING"}, Target: []string{"IDLE", "DELETED"}, - Refresh: advancedcluster.ResourceClusterListAdvancedRefreshFunc(ctx, projectID, advancedcluster.ServiceFromClient(conn)), + Refresh: advancedcluster.ResourceClusterListAdvancedRefreshFunc(ctx, projectID, advancedcluster.ServiceFromClient(connV2)), Timeout: d.Timeout(schema.TimeoutCreate), MinTimeout: 5 * time.Second, Delay: 5 * time.Minute, @@ -285,6 +286,7 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkRead(ctx context.Context, d * func resourceMongoDBAtlasPrivateEndpointServiceLinkDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { conn := meta.(*config.MongoDBClient).Atlas + connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) projectID := ids["project_id"] @@ -316,7 +318,7 @@ func resourceMongoDBAtlasPrivateEndpointServiceLinkDelete(ctx context.Context, d clusterConf := &retry.StateChangeConf{ Pending: []string{"REPEATING", "PENDING"}, Target: []string{"IDLE", "DELETED"}, - Refresh: advancedcluster.ResourceClusterListAdvancedRefreshFunc(ctx, projectID, advancedcluster.ServiceFromClient(conn)), + Refresh: advancedcluster.ResourceClusterListAdvancedRefreshFunc(ctx, projectID, advancedcluster.ServiceFromClient(connV2)), Timeout: d.Timeout(schema.TimeoutDelete), MinTimeout: 5 * time.Second, Delay: 5 * time.Minute, diff --git a/internal/testutil/mocksvc/cluster_service.go b/internal/testutil/mocksvc/cluster_service.go index 5ebff17576..424bbb329e 100644 --- a/internal/testutil/mocksvc/cluster_service.go +++ b/internal/testutil/mocksvc/cluster_service.go @@ -3,10 +3,13 @@ package mocksvc import ( + admin "go.mongodb.org/atlas-sdk/v20231115006/admin" + context "context" + http "net/http" + mock "github.com/stretchr/testify/mock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" ) // ClusterService is an autogenerated mock type for the ClusterService type @@ -15,71 +18,32 @@ type ClusterService struct { } // Get provides a mock function with given fields: ctx, groupID, clusterName -func (_m *ClusterService) Get(ctx context.Context, groupID string, clusterName string) (*mongodbatlas.Cluster, *mongodbatlas.Response, error) { +func (_m *ClusterService) Get(ctx context.Context, groupID string, clusterName string) (*admin.AdvancedClusterDescription, *http.Response, error) { ret := _m.Called(ctx, groupID, clusterName) if len(ret) == 0 { panic("no return value specified for Get") } - var r0 *mongodbatlas.Cluster - var r1 *mongodbatlas.Response - var r2 error - if rf, ok := ret.Get(0).(func(context.Context, string, string) (*mongodbatlas.Cluster, *mongodbatlas.Response, error)); ok { - return rf(ctx, groupID, clusterName) - } - if rf, ok := ret.Get(0).(func(context.Context, string, string) *mongodbatlas.Cluster); ok { - r0 = rf(ctx, groupID, clusterName) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*mongodbatlas.Cluster) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, string, string) *mongodbatlas.Response); ok { - r1 = rf(ctx, groupID, clusterName) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(*mongodbatlas.Response) - } - } - - if rf, ok := ret.Get(2).(func(context.Context, string, string) error); ok { - r2 = rf(ctx, groupID, clusterName) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -// GetAdvancedCluster provides a mock function with given fields: ctx, groupID, clusterName -func (_m *ClusterService) GetAdvancedCluster(ctx context.Context, groupID string, clusterName string) (*mongodbatlas.AdvancedCluster, *mongodbatlas.Response, error) { - ret := _m.Called(ctx, groupID, clusterName) - - if len(ret) == 0 { - panic("no return value specified for GetAdvancedCluster") - } - - var r0 *mongodbatlas.AdvancedCluster - var r1 *mongodbatlas.Response + var r0 *admin.AdvancedClusterDescription + var r1 *http.Response var r2 error - if rf, ok := ret.Get(0).(func(context.Context, string, string) (*mongodbatlas.AdvancedCluster, *mongodbatlas.Response, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, string, string) (*admin.AdvancedClusterDescription, *http.Response, error)); ok { return rf(ctx, groupID, clusterName) } - if rf, ok := ret.Get(0).(func(context.Context, string, string) *mongodbatlas.AdvancedCluster); ok { + if rf, ok := ret.Get(0).(func(context.Context, string, string) *admin.AdvancedClusterDescription); ok { r0 = rf(ctx, groupID, clusterName) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*mongodbatlas.AdvancedCluster) + r0 = ret.Get(0).(*admin.AdvancedClusterDescription) } } - if rf, ok := ret.Get(1).(func(context.Context, string, string) *mongodbatlas.Response); ok { + if rf, ok := ret.Get(1).(func(context.Context, string, string) *http.Response); ok { r1 = rf(ctx, groupID, clusterName) } else { if ret.Get(1) != nil { - r1 = ret.Get(1).(*mongodbatlas.Response) + r1 = ret.Get(1).(*http.Response) } } @@ -92,38 +56,38 @@ func (_m *ClusterService) GetAdvancedCluster(ctx context.Context, groupID string return r0, r1, r2 } -// List provides a mock function with given fields: ctx, groupID, options -func (_m *ClusterService) List(ctx context.Context, groupID string, options *mongodbatlas.ListOptions) (*mongodbatlas.AdvancedClustersResponse, *mongodbatlas.Response, error) { - ret := _m.Called(ctx, groupID, options) +// List provides a mock function with given fields: ctx, options +func (_m *ClusterService) List(ctx context.Context, options *admin.ListClustersApiParams) (*admin.PaginatedAdvancedClusterDescription, *http.Response, error) { + ret := _m.Called(ctx, options) if len(ret) == 0 { panic("no return value specified for List") } - var r0 *mongodbatlas.AdvancedClustersResponse - var r1 *mongodbatlas.Response + var r0 *admin.PaginatedAdvancedClusterDescription + var r1 *http.Response var r2 error - if rf, ok := ret.Get(0).(func(context.Context, string, *mongodbatlas.ListOptions) (*mongodbatlas.AdvancedClustersResponse, *mongodbatlas.Response, error)); ok { - return rf(ctx, groupID, options) + if rf, ok := ret.Get(0).(func(context.Context, *admin.ListClustersApiParams) (*admin.PaginatedAdvancedClusterDescription, *http.Response, error)); ok { + return rf(ctx, options) } - if rf, ok := ret.Get(0).(func(context.Context, string, *mongodbatlas.ListOptions) *mongodbatlas.AdvancedClustersResponse); ok { - r0 = rf(ctx, groupID, options) + if rf, ok := ret.Get(0).(func(context.Context, *admin.ListClustersApiParams) *admin.PaginatedAdvancedClusterDescription); ok { + r0 = rf(ctx, options) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*mongodbatlas.AdvancedClustersResponse) + r0 = ret.Get(0).(*admin.PaginatedAdvancedClusterDescription) } } - if rf, ok := ret.Get(1).(func(context.Context, string, *mongodbatlas.ListOptions) *mongodbatlas.Response); ok { - r1 = rf(ctx, groupID, options) + if rf, ok := ret.Get(1).(func(context.Context, *admin.ListClustersApiParams) *http.Response); ok { + r1 = rf(ctx, options) } else { if ret.Get(1) != nil { - r1 = ret.Get(1).(*mongodbatlas.Response) + r1 = ret.Get(1).(*http.Response) } } - if rf, ok := ret.Get(2).(func(context.Context, string, *mongodbatlas.ListOptions) error); ok { - r2 = rf(ctx, groupID, options) + if rf, ok := ret.Get(2).(func(context.Context, *admin.ListClustersApiParams) error); ok { + r2 = rf(ctx, options) } else { r2 = ret.Error(2) } From d881453e9d3c2a4df9f633c377e5b42008911204 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 21:53:18 +0100 Subject: [PATCH 42/52] getUpgradeRequest --- .../advancedcluster/model_advanced_cluster.go | 185 ++---------------- .../resource_advanced_cluster.go | 21 +- 2 files changed, 23 insertions(+), 183 deletions(-) diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index 8d4f7da484..df7a12bc81 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -19,7 +19,6 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/spf13/cast" "go.mongodb.org/atlas-sdk/v20231115006/admin" - matlas "go.mongodb.org/atlas/mongodbatlas" ) var ( @@ -830,29 +829,7 @@ func expandLabelSliceFromSetSchema(d *schema.ResourceData) ([]admin.ComponentLab return res, nil } -func expandAdvancedReplicationSpecs(tfList []any) []*matlas.AdvancedReplicationSpec { - if len(tfList) == 0 { - return nil - } - - var apiObjects []*matlas.AdvancedReplicationSpec - - for _, tfMapRaw := range tfList { - tfMap, ok := tfMapRaw.(map[string]any) - - if !ok { - continue - } - - apiObject := expandAdvancedReplicationSpec(tfMap) - - apiObjects = append(apiObjects, apiObject) - } - - return apiObjects -} - -func expandAdvancedReplicationSpecsV2(tfList []any) *[]admin.ReplicationSpec { +func expandAdvancedReplicationSpecs(tfList []any) *[]admin.ReplicationSpec { if len(tfList) == 0 { return nil } @@ -862,35 +839,17 @@ func expandAdvancedReplicationSpecsV2(tfList []any) *[]admin.ReplicationSpec { if !ok || tfMap == nil { continue } - apiObject := expandAdvancedReplicationSpecV2(tfMap) + apiObject := expandAdvancedReplicationSpec(tfMap) apiObjects = append(apiObjects, *apiObject) } return &apiObjects } -func expandAdvancedReplicationSpec(tfMap map[string]any) *matlas.AdvancedReplicationSpec { - if tfMap == nil { - return nil - } - - apiObject := &matlas.AdvancedReplicationSpec{ - NumShards: tfMap["num_shards"].(int), - ZoneName: tfMap["zone_name"].(string), - RegionConfigs: expandRegionConfigs(tfMap["region_configs"].([]any)), - } - - if tfMap["id"].(string) != "" { - apiObject.ID = tfMap["id"].(string) - } - - return apiObject -} - -func expandAdvancedReplicationSpecV2(tfMap map[string]any) *admin.ReplicationSpec { +func expandAdvancedReplicationSpec(tfMap map[string]any) *admin.ReplicationSpec { apiObject := &admin.ReplicationSpec{ NumShards: conversion.Pointer(tfMap["num_shards"].(int)), ZoneName: conversion.StringPtr(tfMap["zone_name"].(string)), - RegionConfigs: expandRegionConfigsV2(tfMap["region_configs"].([]any)), + RegionConfigs: expandRegionConfigs(tfMap["region_configs"].([]any)), } if tfMap["id"].(string) != "" { apiObject.Id = conversion.StringPtr(tfMap["id"].(string)) @@ -898,29 +857,7 @@ func expandAdvancedReplicationSpecV2(tfMap map[string]any) *admin.ReplicationSpe return apiObject } -func expandRegionConfigs(tfList []any) []*matlas.AdvancedRegionConfig { - if len(tfList) == 0 { - return nil - } - - var apiObjects []*matlas.AdvancedRegionConfig - - for _, tfMapRaw := range tfList { - tfMap, ok := tfMapRaw.(map[string]any) - - if !ok { - continue - } - - apiObject := expandRegionConfig(tfMap) - - apiObjects = append(apiObjects, apiObject) - } - - return apiObjects -} - -func expandRegionConfigsV2(tfList []any) *[]admin.CloudRegionConfig { +func expandRegionConfigs(tfList []any) *[]admin.CloudRegionConfig { if len(tfList) == 0 { return nil } @@ -930,26 +867,26 @@ func expandRegionConfigsV2(tfList []any) *[]admin.CloudRegionConfig { if !ok || tfMap == nil { continue } - apiObject := expandRegionConfigV2(tfMap) + apiObject := expandRegionConfig(tfMap) apiObjects = append(apiObjects, *apiObject) } return &apiObjects } -func expandRegionConfig(tfMap map[string]any) *matlas.AdvancedRegionConfig { +func expandRegionConfig(tfMap map[string]any) *admin.CloudRegionConfig { providerName := tfMap["provider_name"].(string) - apiObject := &matlas.AdvancedRegionConfig{ + apiObject := &admin.CloudRegionConfig{ Priority: conversion.Pointer(cast.ToInt(tfMap["priority"])), - ProviderName: providerName, - RegionName: tfMap["region_name"].(string), + ProviderName: conversion.StringPtr(providerName), + RegionName: conversion.StringPtr(tfMap["region_name"].(string)), } if v, ok := tfMap["analytics_specs"]; ok && len(v.([]any)) > 0 { apiObject.AnalyticsSpecs = expandRegionConfigSpec(v.([]any), providerName) } if v, ok := tfMap["electable_specs"]; ok && len(v.([]any)) > 0 { - apiObject.ElectableSpecs = expandRegionConfigSpec(v.([]any), providerName) + apiObject.ElectableSpecs = dedicatedHwSpecToHwSpec(expandRegionConfigSpec(v.([]any), providerName)) } if v, ok := tfMap["read_only_specs"]; ok && len(v.([]any)) > 0 { apiObject.ReadOnlySpecs = expandRegionConfigSpec(v.([]any), providerName) @@ -960,70 +897,13 @@ func expandRegionConfig(tfMap map[string]any) *matlas.AdvancedRegionConfig { if v, ok := tfMap["analytics_auto_scaling"]; ok && len(v.([]any)) > 0 { apiObject.AnalyticsAutoScaling = expandRegionConfigAutoScaling(v.([]any)) } - if v, ok := tfMap["backing_provider_name"]; ok { - apiObject.BackingProviderName = v.(string) - } - - return apiObject -} - -func expandRegionConfigV2(tfMap map[string]any) *admin.CloudRegionConfig { - providerName := tfMap["provider_name"].(string) - apiObject := &admin.CloudRegionConfig{ - Priority: conversion.Pointer(cast.ToInt(tfMap["priority"])), - ProviderName: conversion.StringPtr(providerName), - RegionName: conversion.StringPtr(tfMap["region_name"].(string)), - } - - if v, ok := tfMap["analytics_specs"]; ok && len(v.([]any)) > 0 { - apiObject.AnalyticsSpecs = expandRegionConfigSpecV2(v.([]any), providerName) - } - if v, ok := tfMap["electable_specs"]; ok && len(v.([]any)) > 0 { - apiObject.ElectableSpecs = dedicatedHwSpecToHwSpec(expandRegionConfigSpecV2(v.([]any), providerName)) - } - if v, ok := tfMap["read_only_specs"]; ok && len(v.([]any)) > 0 { - apiObject.ReadOnlySpecs = expandRegionConfigSpecV2(v.([]any), providerName) - } - if v, ok := tfMap["auto_scaling"]; ok && len(v.([]any)) > 0 { - apiObject.AutoScaling = expandRegionConfigAutoScalingV2(v.([]any)) - } - if v, ok := tfMap["analytics_auto_scaling"]; ok && len(v.([]any)) > 0 { - apiObject.AnalyticsAutoScaling = expandRegionConfigAutoScalingV2(v.([]any)) - } if v, ok := tfMap["backing_provider_name"]; ok { apiObject.BackingProviderName = conversion.StringPtr(v.(string)) } return apiObject } -func expandRegionConfigSpec(tfList []any, providerName string) *matlas.Specs { - if tfList == nil && len(tfList) > 0 { - return nil - } - - tfMap, _ := tfList[0].(map[string]any) - - apiObject := &matlas.Specs{} - - if providerName == "AWS" { - if v, ok := tfMap["disk_iops"]; ok && v.(int) > 0 { - apiObject.DiskIOPS = conversion.Pointer(cast.ToInt64(v.(int))) - } - if v, ok := tfMap["ebs_volume_type"]; ok { - apiObject.EbsVolumeType = v.(string) - } - } - if v, ok := tfMap["instance_size"]; ok { - apiObject.InstanceSize = v.(string) - } - if v, ok := tfMap["node_count"]; ok { - apiObject.NodeCount = conversion.Pointer(v.(int)) - } - - return apiObject -} - -func expandRegionConfigSpecV2(tfList []any, providerName string) *admin.DedicatedHardwareSpec { +func expandRegionConfigSpec(tfList []any, providerName string) *admin.DedicatedHardwareSpec { tfMap, _ := tfList[0].(map[string]any) apiObject := new(admin.DedicatedHardwareSpec) if providerName == "AWS" { @@ -1043,46 +923,7 @@ func expandRegionConfigSpecV2(tfList []any, providerName string) *admin.Dedicate return apiObject } -func expandRegionConfigAutoScaling(tfList []any) *matlas.AdvancedAutoScaling { - if tfList == nil && len(tfList) > 0 { - return nil - } - - tfMap, _ := tfList[0].(map[string]any) - - advancedAutoScaling := &matlas.AdvancedAutoScaling{} - diskGB := &matlas.DiskGB{} - compute := &matlas.Compute{} - - if v, ok := tfMap["disk_gb_enabled"]; ok { - diskGB.Enabled = conversion.Pointer(v.(bool)) - } - if v, ok := tfMap["compute_enabled"]; ok { - compute.Enabled = conversion.Pointer(v.(bool)) - } - if v, ok := tfMap["compute_scale_down_enabled"]; ok { - compute.ScaleDownEnabled = conversion.Pointer(v.(bool)) - } - if v, ok := tfMap["compute_min_instance_size"]; ok { - value := compute.ScaleDownEnabled - if *value { - compute.MinInstanceSize = v.(string) - } - } - if v, ok := tfMap["compute_max_instance_size"]; ok { - value := compute.Enabled - if *value { - compute.MaxInstanceSize = v.(string) - } - } - - advancedAutoScaling.DiskGB = diskGB - advancedAutoScaling.Compute = compute - - return advancedAutoScaling -} - -func expandRegionConfigAutoScalingV2(tfList []any) *admin.AdvancedAutoScalingSettings { +func expandRegionConfigAutoScaling(tfList []any) *admin.AdvancedAutoScalingSettings { tfMap, _ := tfList[0].(map[string]any) settings := admin.AdvancedAutoScalingSettings{ DiskGB: new(admin.DiskGBAutoScaling), diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 9761e1522f..30df40225d 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -21,7 +21,6 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "github.com/spf13/cast" "go.mongodb.org/atlas-sdk/v20231115006/admin" - matlas "go.mongodb.org/atlas/mongodbatlas" ) const ( @@ -368,7 +367,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. params := &admin.AdvancedClusterDescription{ Name: conversion.StringPtr(cast.ToString(d.Get("name"))), ClusterType: conversion.StringPtr(cast.ToString(d.Get("cluster_type"))), - ReplicationSpecs: expandAdvancedReplicationSpecsV2(d.Get("replication_specs").([]any)), + ReplicationSpecs: expandAdvancedReplicationSpecs(d.Get("replication_specs").([]any)), } if v, ok := d.GetOk("backup_enabled"); ok { @@ -668,7 +667,7 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if d.HasChange("replication_specs") { - cluster.ReplicationSpecs = expandAdvancedReplicationSpecsV2(d.Get("replication_specs").([]any)) + cluster.ReplicationSpecs = expandAdvancedReplicationSpecs(d.Get("replication_specs").([]any)) } if d.HasChange("root_cert_type") { @@ -859,7 +858,7 @@ func replicationSpecsHashSet(v any) int { return schema.HashString(buf.String()) } -func getUpgradeRequest(d *schema.ResourceData) *matlas.Cluster { +func getUpgradeRequest(d *schema.ResourceData) *admin.LegacyAtlasTenantClusterUpgradeRequest { if !d.HasChange("replication_specs") { return nil } @@ -868,21 +867,21 @@ func getUpgradeRequest(d *schema.ResourceData) *matlas.Cluster { currentSpecs := expandAdvancedReplicationSpecs(cs.([]any)) updatedSpecs := expandAdvancedReplicationSpecs(us.([]any)) - if len(currentSpecs) != 1 || len(updatedSpecs) != 1 || len(currentSpecs[0].RegionConfigs) != 1 || len(updatedSpecs[0].RegionConfigs) != 1 { + if currentSpecs == nil || updatedSpecs == nil || len(*currentSpecs) != 1 || len(*updatedSpecs) != 1 || len((*currentSpecs)[0].GetRegionConfigs()) != 1 || len((*updatedSpecs)[0].GetRegionConfigs()) != 1 { return nil } - currentRegion := currentSpecs[0].RegionConfigs[0] - updatedRegion := updatedSpecs[0].RegionConfigs[0] - currentSize := currentRegion.ElectableSpecs.InstanceSize + currentRegion := (*currentSpecs)[0].GetRegionConfigs()[0] + updatedRegion := (*updatedSpecs)[0].GetRegionConfigs()[0] + currentSize := conversion.SafeString(currentRegion.ElectableSpecs.InstanceSize) if currentRegion.ElectableSpecs.InstanceSize == updatedRegion.ElectableSpecs.InstanceSize || !IsSharedTier(currentSize) { return nil } - return &matlas.Cluster{ - ProviderSettings: &matlas.ProviderSettings{ - ProviderName: updatedRegion.ProviderName, + return &admin.LegacyAtlasTenantClusterUpgradeRequest{ + ProviderSettings: &admin.ClusterProviderSettings{ + ProviderName: updatedRegion.GetProviderName(), InstanceSizeName: updatedRegion.ElectableSpecs.InstanceSize, RegionName: updatedRegion.RegionName, }, From 4938549df21615597466d07e29bca6fdadf12032 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 21:54:16 +0100 Subject: [PATCH 43/52] revert test skips --- .../advancedcluster/resource_advanced_cluster_test.go | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 747eeb7baf..7f119076a4 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -78,7 +78,6 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { } func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( dataSourceName = fmt.Sprintf("data.%s", resourceName) orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") @@ -127,7 +126,6 @@ func TestAccClusterAdvancedCluster_singleProvider(t *testing.T) { } func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -182,7 +180,6 @@ func TestAccClusterAdvancedCluster_multicloud(t *testing.T) { } func TestAccClusterAdvancedCluster_multicloudSharded(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -278,7 +275,6 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { } func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -332,7 +328,6 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { } func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -412,7 +407,6 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { } func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -483,7 +477,6 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { } func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -527,7 +520,6 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. } func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -571,7 +563,6 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t } func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() @@ -608,7 +599,6 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAndShardUpdating(t *tes } func TestAccClusterAdvancedCluster_withTags(t *testing.T) { - acc.SkipTestForCI(t) // TEMPORARY, DON'T MERGE var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectName = acc.RandomProjectName() From 741c71c68679cb7d2db857872e606cc0983bcd6c Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 22:11:48 +0100 Subject: [PATCH 44/52] remove old sdk from tests --- .../resource_advanced_cluster_test.go | 124 +++++++++--------- 1 file changed, 62 insertions(+), 62 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 7f119076a4..6acc2f8154 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -11,7 +11,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" - matlas "go.mongodb.org/atlas/mongodbatlas" + "go.mongodb.org/atlas-sdk/v20231115006/admin" ) const ( @@ -333,28 +333,28 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { projectName = acc.RandomProjectName() clusterName = acc.RandomClusterName() clusterNameUpdated = acc.RandomClusterName() - processArgs = &matlas.ProcessArgs{ - DefaultReadConcern: "available", - DefaultWriteConcern: "1", + processArgs = &admin.ClusterDescriptionProcessArgs{ + DefaultReadConcern: conversion.StringPtr("available"), + DefaultWriteConcern: conversion.StringPtr("1"), FailIndexKeyTooLong: conversion.Pointer(false), JavascriptEnabled: conversion.Pointer(true), - MinimumEnabledTLSProtocol: "TLS1_1", + MinimumEnabledTlsProtocol: conversion.StringPtr("TLS1_1"), NoTableScan: conversion.Pointer(false), - OplogSizeMB: conversion.Pointer[int64](1000), - SampleRefreshIntervalBIConnector: conversion.Pointer[int64](310), - SampleSizeBIConnector: conversion.Pointer[int64](110), + OplogSizeMB: conversion.Pointer(1000), + SampleRefreshIntervalBIConnector: conversion.Pointer(310), + SampleSizeBIConnector: conversion.Pointer(110), TransactionLifetimeLimitSeconds: conversion.Pointer[int64](300), } - processArgsUpdated = &matlas.ProcessArgs{ - DefaultReadConcern: "available", - DefaultWriteConcern: "0", + processArgsUpdated = &admin.ClusterDescriptionProcessArgs{ + DefaultReadConcern: conversion.StringPtr("available"), + DefaultWriteConcern: conversion.StringPtr("0"), FailIndexKeyTooLong: conversion.Pointer(false), JavascriptEnabled: conversion.Pointer(true), - MinimumEnabledTLSProtocol: "TLS1_2", + MinimumEnabledTlsProtocol: conversion.StringPtr("TLS1_2"), NoTableScan: conversion.Pointer(false), - OplogSizeMB: conversion.Pointer[int64](1000), - SampleRefreshIntervalBIConnector: conversion.Pointer[int64](310), - SampleSizeBIConnector: conversion.Pointer[int64](110), + OplogSizeMB: conversion.Pointer(1000), + SampleRefreshIntervalBIConnector: conversion.Pointer(310), + SampleSizeBIConnector: conversion.Pointer(110), TransactionLifetimeLimitSeconds: conversion.Pointer[int64](300), } ) @@ -412,25 +412,25 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { projectName = acc.RandomProjectName() clusterName = acc.RandomClusterName() clusterNameUpdated = acc.RandomClusterName() - processArgs = &matlas.ProcessArgs{ - DefaultReadConcern: "available", - DefaultWriteConcern: "1", + processArgs = &admin.ClusterDescriptionProcessArgs{ + DefaultReadConcern: conversion.StringPtr("available"), + DefaultWriteConcern: conversion.StringPtr("1"), JavascriptEnabled: conversion.Pointer(true), - MinimumEnabledTLSProtocol: "TLS1_1", + MinimumEnabledTlsProtocol: conversion.StringPtr("TLS1_1"), NoTableScan: conversion.Pointer(false), - OplogSizeMB: conversion.Pointer[int64](1000), - SampleRefreshIntervalBIConnector: conversion.Pointer[int64](310), - SampleSizeBIConnector: conversion.Pointer[int64](110), + OplogSizeMB: conversion.Pointer(1000), + SampleRefreshIntervalBIConnector: conversion.Pointer(310), + SampleSizeBIConnector: conversion.Pointer(110), } - processArgsUpdated = &matlas.ProcessArgs{ - DefaultReadConcern: "available", - DefaultWriteConcern: "majority", + processArgsUpdated = &admin.ClusterDescriptionProcessArgs{ + DefaultReadConcern: conversion.StringPtr("available"), + DefaultWriteConcern: conversion.StringPtr("majority"), JavascriptEnabled: conversion.Pointer(true), - MinimumEnabledTLSProtocol: "TLS1_2", + MinimumEnabledTlsProtocol: conversion.StringPtr("TLS1_2"), NoTableScan: conversion.Pointer(false), - OplogSizeMB: conversion.Pointer[int64](1000), - SampleRefreshIntervalBIConnector: conversion.Pointer[int64](310), - SampleSizeBIConnector: conversion.Pointer[int64](110), + OplogSizeMB: conversion.Pointer(1000), + SampleRefreshIntervalBIConnector: conversion.Pointer(310), + SampleSizeBIConnector: conversion.Pointer(110), TransactionLifetimeLimitSeconds: conversion.Pointer[int64](300), } ) @@ -482,13 +482,13 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. projectName = acc.RandomProjectName() clusterName = acc.RandomClusterName() clusterNameUpdated = acc.RandomClusterName() - autoScaling = &matlas.AutoScaling{ - Compute: &matlas.Compute{Enabled: conversion.Pointer(false), MaxInstanceSize: ""}, - DiskGBEnabled: conversion.Pointer(true), + autoScaling = &admin.AdvancedAutoScalingSettings{ + Compute: &admin.AdvancedComputeAutoScaling{Enabled: conversion.Pointer(false), MaxInstanceSize: conversion.StringPtr("")}, + DiskGB: &admin.DiskGBAutoScaling{Enabled: conversion.Pointer(true)}, } - autoScalingUpdated = &matlas.AutoScaling{ - Compute: &matlas.Compute{Enabled: conversion.Pointer(true), MaxInstanceSize: "M20"}, - DiskGBEnabled: conversion.Pointer(true), + autoScalingUpdated = &admin.AdvancedAutoScalingSettings{ + Compute: &admin.AdvancedComputeAutoScaling{Enabled: conversion.Pointer(true), MaxInstanceSize: conversion.StringPtr("M20")}, + DiskGB: &admin.DiskGBAutoScaling{Enabled: conversion.Pointer(true)}, } ) @@ -525,13 +525,13 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t projectName = acc.RandomProjectName() clusterName = acc.RandomClusterName() clusterNameUpdated = acc.RandomClusterName() - autoScaling = &matlas.AutoScaling{ - Compute: &matlas.Compute{Enabled: conversion.Pointer(false), MaxInstanceSize: ""}, - DiskGBEnabled: conversion.Pointer(true), + autoScaling = &admin.AdvancedAutoScalingSettings{ + Compute: &admin.AdvancedComputeAutoScaling{Enabled: conversion.Pointer(false), MaxInstanceSize: conversion.StringPtr("")}, + DiskGB: &admin.DiskGBAutoScaling{Enabled: conversion.Pointer(true)}, } - autoScalingUpdated = &matlas.AutoScaling{ - Compute: &matlas.Compute{Enabled: conversion.Pointer(true), MaxInstanceSize: "M20"}, - DiskGBEnabled: conversion.Pointer(true), + autoScalingUpdated = &admin.AdvancedAutoScalingSettings{ + Compute: &admin.AdvancedComputeAutoScaling{Enabled: conversion.Pointer(true), MaxInstanceSize: conversion.StringPtr("M20")}, + DiskGB: &admin.DiskGBAutoScaling{Enabled: conversion.Pointer(true)}, } ) @@ -611,7 +611,7 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configWithTags(orgID, projectName, clusterName, []matlas.Tag{}), + Config: configWithTags(orgID, projectName, clusterName, nil), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", clusterName), @@ -623,14 +623,14 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { ), }, { - Config: configWithTags(orgID, projectName, clusterName, []matlas.Tag{ + Config: configWithTags(orgID, projectName, clusterName, []admin.ResourceTag{ { - Key: "key 1", - Value: "value 1", + Key: conversion.StringPtr("key 1"), + Value: conversion.StringPtr("value 1"), }, { - Key: "key 2", - Value: "value 2", + Key: conversion.StringPtr("key 2"), + Value: conversion.StringPtr("value 2"), }, }), Check: resource.ComposeTestCheckFunc( @@ -650,10 +650,10 @@ func TestAccClusterAdvancedCluster_withTags(t *testing.T) { ), }, { - Config: configWithTags(orgID, projectName, clusterName, []matlas.Tag{ + Config: configWithTags(orgID, projectName, clusterName, []admin.ResourceTag{ { - Key: "key 3", - Value: "value 3", + Key: conversion.StringPtr("key 3"), + Value: conversion.StringPtr("value 3"), }, }), Check: resource.ComposeTestCheckFunc( @@ -725,7 +725,7 @@ data "mongodbatlas_advanced_clusters" "test" { `, orgID, projectName, name) } -func configWithTags(orgID, projectName, name string, tags []matlas.Tag) string { +func configWithTags(orgID, projectName, name string, tags []admin.ResourceTag) string { var tagsConf string for _, label := range tags { tagsConf += fmt.Sprintf(` @@ -733,7 +733,7 @@ func configWithTags(orgID, projectName, name string, tags []matlas.Tag) string { key = "%s" value = "%s" } - `, label.Key, label.Value) + `, label.GetKey(), label.GetValue()) } return fmt.Sprintf(` @@ -933,7 +933,7 @@ resource "mongodbatlas_advanced_cluster" "test" { `, orgID, projectName, name, paused, instanceSize) } -func configAdvanced(orgID, projectName, name string, p *matlas.ProcessArgs) string { +func configAdvanced(orgID, projectName, name string, p *admin.ClusterDescriptionProcessArgs) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { name = %[2]q @@ -981,11 +981,11 @@ data "mongodbatlas_advanced_clusters" "test" { } `, orgID, projectName, name, - *p.FailIndexKeyTooLong, *p.JavascriptEnabled, p.MinimumEnabledTLSProtocol, *p.NoTableScan, - *p.OplogSizeMB, *p.SampleSizeBIConnector, *p.SampleRefreshIntervalBIConnector, *p.TransactionLifetimeLimitSeconds) + p.GetFailIndexKeyTooLong(), p.GetJavascriptEnabled(), p.GetMinimumEnabledTlsProtocol(), p.GetNoTableScan(), + p.GetOplogSizeMB(), p.GetSampleSizeBIConnector(), p.GetSampleRefreshIntervalBIConnector(), p.GetTransactionLifetimeLimitSeconds()) } -func configAdvancedDefaultWrite(orgID, projectName, name string, p *matlas.ProcessArgs) string { +func configAdvancedDefaultWrite(orgID, projectName, name string, p *admin.ClusterDescriptionProcessArgs) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { name = %[2]q @@ -1024,11 +1024,11 @@ resource "mongodbatlas_advanced_cluster" "test" { } } - `, orgID, projectName, name, *p.JavascriptEnabled, p.MinimumEnabledTLSProtocol, *p.NoTableScan, - *p.OplogSizeMB, *p.SampleSizeBIConnector, *p.SampleRefreshIntervalBIConnector, p.DefaultReadConcern, p.DefaultWriteConcern) + `, orgID, projectName, name, p.GetJavascriptEnabled(), p.GetMinimumEnabledTlsProtocol(), p.GetNoTableScan(), + p.GetOplogSizeMB(), p.GetSampleSizeBIConnector(), p.GetSampleRefreshIntervalBIConnector(), p.GetDefaultReadConcern(), p.GetDefaultWriteConcern()) } -func configReplicationSpecsAutoScaling(orgID, projectName, name string, p *matlas.AutoScaling) string { +func configReplicationSpecsAutoScaling(orgID, projectName, name string, p *admin.AdvancedAutoScalingSettings) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { name = %[2]q @@ -1063,10 +1063,10 @@ resource "mongodbatlas_advanced_cluster" "test" { } - `, orgID, projectName, name, *p.Compute.Enabled, *p.DiskGBEnabled, p.Compute.MaxInstanceSize) + `, orgID, projectName, name, p.Compute.GetEnabled(), p.DiskGB.GetEnabled(), p.Compute.GetMaxInstanceSize()) } -func configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, name string, p *matlas.AutoScaling) string { +func configReplicationSpecsAnalyticsAutoScaling(orgID, projectName, name string, p *admin.AdvancedAutoScalingSettings) string { return fmt.Sprintf(` resource "mongodbatlas_project" "cluster_project" { @@ -1103,7 +1103,7 @@ resource "mongodbatlas_advanced_cluster" "test" { } - `, orgID, projectName, name, *p.Compute.Enabled, *p.DiskGBEnabled, p.Compute.MaxInstanceSize) + `, orgID, projectName, name, p.Compute.GetEnabled(), p.DiskGB.GetEnabled(), p.Compute.GetMaxInstanceSize()) } func configMultiZoneWithShards(orgID, projectName, name, numShardsFirstZone, numShardsSecondZone string) string { From 28043129875ed367085ac08bc40e3503b2af47de Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 19 Feb 2024 22:13:14 +0100 Subject: [PATCH 45/52] blanks --- .../service/advancedcluster/resource_advanced_cluster_test.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 6acc2f8154..4851060227 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -1059,10 +1059,7 @@ resource "mongodbatlas_advanced_cluster" "test" { region_name = "EU_WEST_1" } } - - } - `, orgID, projectName, name, p.Compute.GetEnabled(), p.DiskGB.GetEnabled(), p.Compute.GetMaxInstanceSize()) } From 72f10e18f5ea086afaff2122e002c8fd177c54dc Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Tue, 20 Feb 2024 16:12:59 +0100 Subject: [PATCH 46/52] keep behavior for accept_data_risks_and_force_replica_set_reconfig --- .../advancedcluster/resource_advanced_cluster.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 30df40225d..3fa097463e 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -683,11 +683,13 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if d.HasChange("accept_data_risks_and_force_replica_set_reconfig") { - t, ok := conversion.StringToTime(d.Get("accept_data_risks_and_force_replica_set_reconfig").(string)) - if !ok { - return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, "accept_data_risks_and_force_replica_set_reconfig time format is incorrect")) + if strTime := d.Get("accept_data_risks_and_force_replica_set_reconfig").(string); strTime != "" { + t, ok := conversion.StringToTime(strTime) + if !ok { + return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, "accept_data_risks_and_force_replica_set_reconfig time format is incorrect")) + } + cluster.AcceptDataRisksAndForceReplicaSetReconfig = &t } - cluster.AcceptDataRisksAndForceReplicaSetReconfig = &t } if d.HasChange("paused") && !d.Get("paused").(bool) { From c371a9a0b5a1c66ad904e5c12e71bba51c7a3742 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Tue, 20 Feb 2024 16:17:39 +0100 Subject: [PATCH 47/52] move out UpgradeCluster from model --- .../advancedcluster/model_advanced_cluster.go | 28 ------------------- .../resource_advanced_cluster.go | 28 ++++++++++++++++++- 2 files changed, 27 insertions(+), 29 deletions(-) diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index df7a12bc81..e159c25194 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -6,10 +6,8 @@ import ( "fmt" "hash/crc32" "log" - "net/http" "slices" "strings" - "time" "github.com/hashicorp/go-cty/cty" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -297,32 +295,6 @@ func IsSharedTier(instanceSize string) bool { return instanceSize == "M0" || instanceSize == "M2" || instanceSize == "M5" } -func UpgradeCluster(ctx context.Context, connV2 *admin.APIClient, request *admin.LegacyAtlasTenantClusterUpgradeRequest, projectID, name string, timeout time.Duration) (*admin.LegacyAtlasCluster, *http.Response, error) { - request.Name = name - - cluster, resp, err := connV2.ClustersApi.UpgradeSharedCluster(ctx, projectID, request).Execute() - if err != nil { - return nil, nil, err - } - - stateConf := &retry.StateChangeConf{ - Pending: []string{"CREATING", "UPDATING", "REPAIRING"}, - Target: []string{"IDLE"}, - Refresh: UpgradeRefreshFunc(ctx, name, projectID, ServiceFromClient(connV2)), - Timeout: timeout, - MinTimeout: 30 * time.Second, - Delay: 1 * time.Minute, - } - - // Wait, catching any errors - _, err = stateConf.WaitForStateContext(ctx) - if err != nil { - return nil, nil, err - } - - return cluster, resp, nil -} - func UpgradeRefreshFunc(ctx context.Context, name, projectID string, client ClusterService) retry.StateRefreshFunc { return func() (any, string, error) { cluster, resp, err := client.Get(ctx, projectID, name) diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 3fa097463e..17043fd5a8 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -602,7 +602,7 @@ func resourceUpgrade(ctx context.Context, d *schema.ResourceData, meta any) diag return diag.FromErr(fmt.Errorf("upgrade called without %s in ctx", string(upgradeRequestCtxKey))) } - upgradeResponse, _, err := UpgradeCluster(ctx, connV2, upgradeRequest, projectID, clusterName, d.Timeout(schema.TimeoutUpdate)) + upgradeResponse, _, err := upgradeCluster(ctx, connV2, upgradeRequest, projectID, clusterName, d.Timeout(schema.TimeoutUpdate)) if err != nil { return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, err)) @@ -810,6 +810,32 @@ func resourceImport(ctx context.Context, d *schema.ResourceData, meta any) ([]*s return []*schema.ResourceData{d}, nil } +func upgradeCluster(ctx context.Context, connV2 *admin.APIClient, request *admin.LegacyAtlasTenantClusterUpgradeRequest, projectID, name string, timeout time.Duration) (*admin.LegacyAtlasCluster, *http.Response, error) { + request.Name = name + + cluster, resp, err := connV2.ClustersApi.UpgradeSharedCluster(ctx, projectID, request).Execute() + if err != nil { + return nil, nil, err + } + + stateConf := &retry.StateChangeConf{ + Pending: []string{"CREATING", "UPDATING", "REPAIRING"}, + Target: []string{"IDLE"}, + Refresh: UpgradeRefreshFunc(ctx, name, projectID, ServiceFromClient(connV2)), + Timeout: timeout, + MinTimeout: 30 * time.Second, + Delay: 1 * time.Minute, + } + + // Wait, catching any errors + _, err = stateConf.WaitForStateContext(ctx) + if err != nil { + return nil, nil, err + } + + return cluster, resp, nil +} + func splitSClusterAdvancedImportID(id string) (projectID, clusterName *string, err error) { var re = regexp.MustCompile(`(?s)^([0-9a-fA-F]{24})-(.*)$`) parts := re.FindStringSubmatch(id) From 5df8b2549772b0a431f5c2d97034ffbc8584d959 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Tue, 20 Feb 2024 16:33:52 +0100 Subject: [PATCH 48/52] remove pointer from expandProcessArgs return so it's clear it always returns a value --- internal/service/advancedcluster/model_advanced_cluster.go | 5 ++--- .../service/advancedcluster/resource_advanced_cluster.go | 6 +++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index e159c25194..2bf1a11728 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -722,8 +722,8 @@ func getAdvancedClusterContainerID(containers []admin.CloudProviderContainer, cl return "" } -func expandProcessArgs(d *schema.ResourceData, p map[string]any) *admin.ClusterDescriptionProcessArgs { - res := new(admin.ClusterDescriptionProcessArgs) +func expandProcessArgs(d *schema.ResourceData, p map[string]any) admin.ClusterDescriptionProcessArgs { + res := admin.ClusterDescriptionProcessArgs{} if _, ok := d.GetOkExists("advanced_configuration.0.default_read_concern"); ok { res.DefaultReadConcern = conversion.StringPtr(cast.ToString(p["default_read_concern"])) @@ -780,7 +780,6 @@ func expandProcessArgs(d *schema.ResourceData, p map[string]any) *admin.ClusterD log.Printf(ErrorClusterSetting, `transaction_lifetime_limit_seconds`, "", cast.ToString(transactionLifetimeLimitSeconds)) } } - return res } diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 17043fd5a8..6934ab0272 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -440,7 +440,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. if ac, ok := d.GetOk("advanced_configuration"); ok { if aclist, ok := ac.([]any); ok && len(aclist) > 0 { params := expandProcessArgs(d, aclist[0].(map[string]any)) - _, _, err := connV2.ClustersApi.UpdateClusterAdvancedConfiguration(ctx, projectID, cluster.GetName(), params).Execute() + _, _, err := connV2.ClustersApi.UpdateClusterAdvancedConfiguration(ctx, projectID, cluster.GetName(), ¶ms).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorConfigUpdate, cluster.GetName(), err)) } @@ -702,8 +702,8 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. ac := d.Get("advanced_configuration") if aclist, ok := ac.([]any); ok && len(aclist) > 0 { params := expandProcessArgs(d, aclist[0].(map[string]any)) - if !reflect.DeepEqual(*params, admin.ClusterDescriptionProcessArgs{}) { - _, _, err := connV2.ClustersApi.UpdateClusterAdvancedConfiguration(ctx, projectID, clusterName, params).Execute() + if !reflect.DeepEqual(params, admin.ClusterDescriptionProcessArgs{}) { + _, _, err := connV2.ClustersApi.UpdateClusterAdvancedConfiguration(ctx, projectID, clusterName, ¶ms).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorConfigUpdate, clusterName, err)) } From 1ab91d8299e3cf6ccde1a8998c85db5fa6679257 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Tue, 20 Feb 2024 16:34:37 +0100 Subject: [PATCH 49/52] rename mig.TestStep to TestStepCheckEmptyPlan --- .../resource_advanced_cluster_migration_test.go | 4 ++-- internal/testutil/mig/test_step.go | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go index a9bb8150c0..a4410ba70c 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_migration_test.go @@ -33,7 +33,7 @@ func TestAccMigrationAdvancedCluster_singleAWSProvider(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), ), }, - mig.TestStep(config), + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -62,7 +62,7 @@ func TestAccMigrationAdvancedCluster_multiCloud(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.region_configs.#"), ), }, - mig.TestStep(config), + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/testutil/mig/test_step.go b/internal/testutil/mig/test_step.go index 806f349fbb..9e0a04fbc3 100644 --- a/internal/testutil/mig/test_step.go +++ b/internal/testutil/mig/test_step.go @@ -6,7 +6,12 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) +// TestStep is being deprecated in favor of TestStepCheckEmptyPlan func TestStep(config string) resource.TestStep { + return TestStepCheckEmptyPlan(config) +} + +func TestStepCheckEmptyPlan(config string) resource.TestStep { return resource.TestStep{ ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, Config: config, From 2d9fd0ef86b68e72a3c0fd449f3cfefe95ef74ab Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Tue, 20 Feb 2024 18:16:51 +0100 Subject: [PATCH 50/52] random names functions and mig.TestStepCheckEmptyPlan for tests in test groups that must be executed before merging --- .../data_source_alert_configuration_test.go | 9 +- .../data_source_alert_configurations_test.go | 9 +- ...urce_alert_configuration_migration_test.go | 67 +--- .../resource_alert_configuration_test.go | 37 +- .../apikey/data_source_api_key_test.go | 13 +- .../apikey/data_source_api_keys_test.go | 13 +- .../apikey/resource_api_key_migration_test.go | 19 +- .../service/apikey/resource_api_key_test.go | 7 +- .../atlasuser/data_source_atlas_users_test.go | 7 +- ...ce_cloud_backup_snapshot_migration_test.go | 7 +- .../resource_cloud_backup_snapshot_test.go | 3 +- ..._cloud_backup_snapshot_restore_job_test.go | 33 +- ...loud_provider_access_authorization_test.go | 9 +- ...source_cloud_provider_access_setup_test.go | 7 +- .../service/cluster/resource_cluster_test.go | 362 +++++++++--------- .../data_source_custom_db_role_test.go | 16 +- .../data_source_custom_db_roles_test.go | 16 +- .../resource_custom_db_role_migration_test.go | 23 +- .../resource_custom_db_role_test.go | 101 ++--- ...stom_dns_configuration_cluster_aws_test.go | 3 +- ...onfiguration_cluster_aws_migration_test.go | 6 +- ...stom_dns_configuration_cluster_aws_test.go | 5 +- .../data_source_database_user_test.go | 16 +- .../data_source_database_users_test.go | 14 +- .../resource_database_user_migration_test.go | 260 ++++--------- .../resource_database_user_test.go | 55 ++- .../data_source_maintenance_window_test.go | 3 +- ...ource_maintenance_window_migration_test.go | 6 +- .../resource_maintenance_window_test.go | 7 +- .../data_source_network_container_test.go | 7 +- .../data_source_network_containers_test.go | 7 +- ...source_network_container_migration_test.go | 13 +- .../resource_network_container_test.go | 10 +- .../resource_network_peering_test.go | 5 +- .../resource_online_archive_migration_test.go | 23 +- .../resource_online_archive_test.go | 49 ++- .../resource_org_invitation_migration_test.go | 15 +- ...rce_private_endpoint_regional_mode_test.go | 22 +- ...rce_privatelink_endpoint_migration_test.go | 18 +- .../resource_privatelink_endpoint_test.go | 11 +- ...link_endpoint_serverless_migration_test.go | 20 +- ...ce_privatelink_endpoint_serverless_test.go | 9 +- ...point_service_serverless_migration_test.go | 8 +- ...telink_endpoint_service_serverless_test.go | 9 +- ...resource_project_api_key_migration_test.go | 6 +- .../resource_project_api_key_test.go | 40 +- ...source_search_deployment_migration_test.go | 19 +- .../resource_search_deployment_test.go | 5 +- ...urce_serverless_instance_migration_test.go | 7 +- .../resource_serverless_instance_test.go | 13 +- .../service/teams/data_source_teams_test.go | 5 +- .../teams/resource_teams_migration_test.go | 19 +- internal/service/teams/resource_teams_test.go | 7 +- 53 files changed, 610 insertions(+), 870 deletions(-) diff --git a/internal/service/alertconfiguration/data_source_alert_configuration_test.go b/internal/service/alertconfiguration/data_source_alert_configuration_test.go index b4bc4341f3..70513b009b 100644 --- a/internal/service/alertconfiguration/data_source_alert_configuration_test.go +++ b/internal/service/alertconfiguration/data_source_alert_configuration_test.go @@ -5,7 +5,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "go.mongodb.org/atlas-sdk/v20231115006/admin" @@ -16,7 +15,7 @@ func TestAccConfigDSAlertConfiguration_basic(t *testing.T) { alert = &admin.GroupAlertsConfig{} dataSourceName = "data.mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -45,7 +44,7 @@ func TestAccConfigDSAlertConfiguration_withThreshold(t *testing.T) { alert = &admin.GroupAlertsConfig{} dataSourceName = "data.mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -74,7 +73,7 @@ func TestAccConfigDSAlertConfiguration_withOutput(t *testing.T) { alert = &admin.GroupAlertsConfig{} dataSourceName = "data.mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() outputLabel = "resource_import" ) @@ -107,7 +106,7 @@ func TestAccConfigDSAlertConfiguration_withPagerDuty(t *testing.T) { alert = &admin.GroupAlertsConfig{} dataSourceName = "data.mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() serviceKey = dummy32CharKey ) diff --git a/internal/service/alertconfiguration/data_source_alert_configurations_test.go b/internal/service/alertconfiguration/data_source_alert_configurations_test.go index 271f4d23e1..9fee329171 100644 --- a/internal/service/alertconfiguration/data_source_alert_configurations_test.go +++ b/internal/service/alertconfiguration/data_source_alert_configurations_test.go @@ -9,7 +9,6 @@ import ( "strings" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -21,7 +20,7 @@ func TestAccConfigDSAlertConfigurations_basic(t *testing.T) { var ( dataSourceName = "data.mongodbatlas_alert_configurations.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -44,7 +43,7 @@ func TestAccConfigDSAlertConfigurations_withOutputTypes(t *testing.T) { var ( dataSourceName = "data.mongodbatlas_alert_configurations.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() outputTypes = []string{"resource_hcl", "resource_import"} ) @@ -67,7 +66,7 @@ func TestAccConfigDSAlertConfigurations_withOutputTypes(t *testing.T) { func TestAccConfigDSAlertConfigurations_invalidOutputTypeValue(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -86,7 +85,7 @@ func TestAccConfigDSAlertConfigurations_totalCount(t *testing.T) { var ( dataSourceName = "data.mongodbatlas_alert_configurations.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ diff --git a/internal/service/alertconfiguration/resource_alert_configuration_migration_test.go b/internal/service/alertconfiguration/resource_alert_configuration_migration_test.go index b2d6cee217..988e16cd8b 100644 --- a/internal/service/alertconfiguration/resource_alert_configuration_migration_test.go +++ b/internal/service/alertconfiguration/resource_alert_configuration_migration_test.go @@ -7,9 +7,7 @@ import ( "go.mongodb.org/atlas-sdk/v20231115006/admin" - "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" ) @@ -18,7 +16,7 @@ func TestAccMigrationConfigRSAlertConfiguration_withNotificationsMetricThreshold var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() alert = &admin.GroupAlertsConfig{} config = configBasicRS(orgID, projectName, true) ) @@ -36,16 +34,7 @@ func TestAccMigrationConfigRSAlertConfiguration_withNotificationsMetricThreshold resource.TestCheckResourceAttr(resourceName, "notification.#", "2"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: config, - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -54,7 +43,7 @@ func TestAccMigrationConfigRSAlertConfiguration_withThreshold(t *testing.T) { var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() alert = &admin.GroupAlertsConfig{} config = configWithThresholdUpdated(orgID, projectName, true, 1) ) @@ -74,16 +63,7 @@ func TestAccMigrationConfigRSAlertConfiguration_withThreshold(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "threshold_config.#", "1"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: config, - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -92,7 +72,7 @@ func TestAccMigrationConfigRSAlertConfiguration_withEmptyOptionalBlocks(t *testi var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() alert = &admin.GroupAlertsConfig{} config = configWithEmptyOptionalBlocks(orgID, projectName) ) @@ -113,16 +93,7 @@ func TestAccMigrationConfigRSAlertConfiguration_withEmptyOptionalBlocks(t *testi resource.TestCheckResourceAttr(resourceName, "metric_threshold_config.#", "0"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: config, - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -131,7 +102,7 @@ func TestAccMigrationConfigRSAlertConfiguration_withMultipleMatchers(t *testing. var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() alert = &admin.GroupAlertsConfig{} config = configWithMatchers(orgID, projectName, true, false, true, map[string]interface{}{ @@ -159,16 +130,7 @@ func TestAccMigrationConfigRSAlertConfiguration_withMultipleMatchers(t *testing. resource.TestCheckResourceAttr(resourceName, "matcher.#", "2"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: config, - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -177,7 +139,7 @@ func TestAccMigrationConfigRSAlertConfiguration_withEmptyOptionalAttributes(t *t var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() alert = &admin.GroupAlertsConfig{} config = configWithEmptyOptionalAttributes(orgID, projectName) ) @@ -195,16 +157,7 @@ func TestAccMigrationConfigRSAlertConfiguration_withEmptyOptionalAttributes(t *t resource.TestCheckResourceAttr(resourceName, "notification.#", "1"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: config, - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/alertconfiguration/resource_alert_configuration_test.go b/internal/service/alertconfiguration/resource_alert_configuration_test.go index c787560b2e..a3c7d274f1 100644 --- a/internal/service/alertconfiguration/resource_alert_configuration_test.go +++ b/internal/service/alertconfiguration/resource_alert_configuration_test.go @@ -7,7 +7,6 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -20,7 +19,7 @@ func TestAccConfigRSAlertConfiguration_basic(t *testing.T) { var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() alert = &admin.GroupAlertsConfig{} ) @@ -52,7 +51,7 @@ func TestAccConfigRSAlertConfiguration_basic(t *testing.T) { func TestAccConfigRSAlertConfiguration_withEmptyMetricThresholdConfig(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -71,7 +70,7 @@ func TestAccConfigRSAlertConfiguration_withEmptyMatcherMetricThresholdConfig(t * var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() alert = &admin.GroupAlertsConfig{} ) @@ -95,7 +94,7 @@ func TestAccConfigRSAlertConfiguration_withNotifications(t *testing.T) { var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() alert = &admin.GroupAlertsConfig{} ) @@ -126,7 +125,7 @@ func TestAccConfigRSAlertConfiguration_withMatchers(t *testing.T) { var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() alert = &admin.GroupAlertsConfig{} ) @@ -177,7 +176,7 @@ func TestAccConfigRSAlertConfiguration_withMetricUpdated(t *testing.T) { var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() alert = &admin.GroupAlertsConfig{} ) @@ -208,7 +207,7 @@ func TestAccConfigRSAlertConfiguration_withThresholdUpdated(t *testing.T) { var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() alert = &admin.GroupAlertsConfig{} ) @@ -247,7 +246,7 @@ func TestAccConfigRSAlertConfiguration_withoutRoles(t *testing.T) { alert = &admin.GroupAlertsConfig{} resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -271,7 +270,7 @@ func TestAccConfigRSAlertConfiguration_withoutOptionalAttributes(t *testing.T) { alert = &admin.GroupAlertsConfig{} resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -293,7 +292,7 @@ func TestAccConfigRSAlertConfiguration_withoutOptionalAttributes(t *testing.T) { func TestAccConfigRSAlertConfiguration_importBasic(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() resourceName = "mongodbatlas_alert_configuration.test" ) @@ -319,7 +318,7 @@ func TestAccConfigRSAlertConfiguration_importBasic(t *testing.T) { func TestAccConfigRSAlertConfiguration_importIncorrectId(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() resourceName = "mongodbatlas_alert_configuration.test" ) @@ -344,7 +343,7 @@ func TestAccConfigRSAlertConfiguration_importIncorrectId(t *testing.T) { func TestAccConfigRSAlertConfiguration_importConfigNotifications(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() resourceName = "mongodbatlas_alert_configuration.test" ) @@ -376,7 +375,7 @@ func TestAccConfigRSAlertConfiguration_importPagerDuty(t *testing.T) { var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() serviceKey = dummy32CharKey alert = &admin.GroupAlertsConfig{} ) @@ -408,7 +407,7 @@ func TestAccConfigRSAlertConfiguration_updatePagerDutyWithNotifierId(t *testing. var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() serviceKey = dummy32CharKey notifierID = "651dd9336afac13e1c112222" alert = &admin.GroupAlertsConfig{} @@ -444,7 +443,7 @@ func TestAccConfigRSAlertConfiguration_withDataDog(t *testing.T) { var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ddAPIKey = dummy32CharKey ddRegion = "US" alert = &admin.GroupAlertsConfig{} @@ -470,7 +469,7 @@ func TestAccConfigRSAlertConfiguration_withPagerDuty(t *testing.T) { var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() serviceKey = dummy32CharKey alert = &admin.GroupAlertsConfig{} ) @@ -495,7 +494,7 @@ func TestAccConfigRSAlertConfiguration_withOpsGenie(t *testing.T) { var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() apiKey = dummy36CharKey alert = &admin.GroupAlertsConfig{} ) @@ -520,7 +519,7 @@ func TestAccConfigRSAlertConfiguration_withVictorOps(t *testing.T) { var ( resourceName = "mongodbatlas_alert_configuration.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() apiKey = dummy36CharKey alert = &admin.GroupAlertsConfig{} ) diff --git a/internal/service/apikey/data_source_api_key_test.go b/internal/service/apikey/data_source_api_key_test.go index af64df43ab..3ca711e069 100644 --- a/internal/service/apikey/data_source_api_key_test.go +++ b/internal/service/apikey/data_source_api_key_test.go @@ -5,17 +5,18 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) func TestAccConfigDSAPIKey_basic(t *testing.T) { - resourceName := "mongodbatlas_api_key.test" - dataSourceName := "data.mongodbatlas_api_key.test" - orgID := os.Getenv("MONGODB_ATLAS_ORG_ID") - description := fmt.Sprintf("test-acc-api_key-%s", acctest.RandString(5)) - roleName := "ORG_MEMBER" + var ( + resourceName = "mongodbatlas_api_key.test" + dataSourceName = "data.mongodbatlas_api_key.test" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + description = acc.RandomName() + roleName = "ORG_MEMBER" + ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, diff --git a/internal/service/apikey/data_source_api_keys_test.go b/internal/service/apikey/data_source_api_keys_test.go index a9d273aa80..6b200cc630 100644 --- a/internal/service/apikey/data_source_api_keys_test.go +++ b/internal/service/apikey/data_source_api_keys_test.go @@ -5,17 +5,18 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) func TestAccConfigDSAPIKeys_basic(t *testing.T) { - resourceName := "mongodbatlas_api_key.test" - dataSourceName := "data.mongodbatlas_api_keys.test" - orgID := os.Getenv("MONGODB_ATLAS_ORG_ID") - description := fmt.Sprintf("test-acc-api_key-%s", acctest.RandString(5)) - roleName := "ORG_MEMBER" + var ( + resourceName = "mongodbatlas_api_key.test" + dataSourceName = "data.mongodbatlas_api_keys.test" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + description = acc.RandomName() + roleName = "ORG_MEMBER" + ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, diff --git a/internal/service/apikey/resource_api_key_migration_test.go b/internal/service/apikey/resource_api_key_migration_test.go index defebba483..402aebcb66 100644 --- a/internal/service/apikey/resource_api_key_migration_test.go +++ b/internal/service/apikey/resource_api_key_migration_test.go @@ -1,13 +1,10 @@ package apikey_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" ) @@ -16,8 +13,9 @@ func TestAccMigrationConfigAPIKey_basic(t *testing.T) { var ( resourceName = "mongodbatlas_api_key.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - description = fmt.Sprintf("test-acc-api_key-%s", acctest.RandString(5)) + description = acc.RandomName() roleName = "ORG_MEMBER" + config = configBasic(orgID, description, roleName) ) resource.ParallelTest(t, resource.TestCase{ @@ -25,7 +23,7 @@ func TestAccMigrationConfigAPIKey_basic(t *testing.T) { CheckDestroy: checkDestroy, Steps: []resource.TestStep{ { - Config: configBasic(orgID, description, roleName), + Config: config, ExternalProviders: mig.ExternalProviders(), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), @@ -33,16 +31,7 @@ func TestAccMigrationConfigAPIKey_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "description", description), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: configBasic(orgID, description, roleName), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/apikey/resource_api_key_test.go b/internal/service/apikey/resource_api_key_test.go index ecf1260418..36f26a92a0 100644 --- a/internal/service/apikey/resource_api_key_test.go +++ b/internal/service/apikey/resource_api_key_test.go @@ -6,7 +6,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -17,8 +16,8 @@ func TestAccConfigRSAPIKey_basic(t *testing.T) { var ( resourceName = "mongodbatlas_api_key.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - description = fmt.Sprintf("test-acc-api_key-%s", acctest.RandString(5)) - descriptionUpdate = fmt.Sprintf("test-acc-api_key-%s", acctest.RandString(5)) + description = acc.RandomName() + descriptionUpdate = acc.RandomName() roleName = "ORG_MEMBER" roleNameUpdated = "ORG_BILLING_ADMIN" ) @@ -52,7 +51,7 @@ func TestAccConfigRSAPIKey_importBasic(t *testing.T) { var ( resourceName = "mongodbatlas_api_key.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - description = fmt.Sprintf("test-acc-import-api_key-%s", acctest.RandString(5)) + description = acc.RandomName() roleName = "ORG_MEMBER" ) diff --git a/internal/service/atlasuser/data_source_atlas_users_test.go b/internal/service/atlasuser/data_source_atlas_users_test.go index 9bb48758aa..e4c431527e 100644 --- a/internal/service/atlasuser/data_source_atlas_users_test.go +++ b/internal/service/atlasuser/data_source_atlas_users_test.go @@ -7,7 +7,6 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/atlasuser" @@ -40,7 +39,7 @@ func TestAccConfigDSAtlasUsers_ByOrgID(t *testing.T) { func TestAccConfigDSAtlasUsers_ByProjectID(t *testing.T) { var ( dataSourceName = "data.mongodbatlas_atlas_users.test" - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") projectOwnerID = os.Getenv("MONGODB_ATLAS_PROJECT_OWNER_ID") ) @@ -73,7 +72,7 @@ func TestAccConfigDSAtlasUsers_ByTeamID(t *testing.T) { dataSourceName = "data.mongodbatlas_atlas_users.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") username = os.Getenv("MONGODB_ATLAS_USERNAME") - teamName = acctest.RandomWithPrefix("team-name") + teamName = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -105,7 +104,7 @@ func TestAccConfigDSAtlasUsers_UsingPagination(t *testing.T) { dataSourceName = "data.mongodbatlas_atlas_users.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") username = os.Getenv("MONGODB_ATLAS_USERNAME") - teamName = acctest.RandomWithPrefix("team-name") + teamName = acc.RandomName() pageNum = 2 itemsPerPage = 1 ) diff --git a/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_migration_test.go b/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_migration_test.go index a95e478daf..44192b96e5 100644 --- a/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_migration_test.go +++ b/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_migration_test.go @@ -4,7 +4,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" @@ -38,7 +37,7 @@ func TestAccMigrationBackupRSCloudBackupSnapshot_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "retention_in_days", retentionInDays), ), }, - mig.TestStep(config), + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -46,7 +45,7 @@ func TestAccMigrationBackupRSCloudBackupSnapshot_basic(t *testing.T) { func TestAccMigrationBackupRSCloudBackupSnapshot_sharded(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() description = "My description in my cluster" retentionInDays = "4" config = configSharded(orgID, projectName, description, retentionInDays) @@ -69,7 +68,7 @@ func TestAccMigrationBackupRSCloudBackupSnapshot_sharded(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "retention_in_days", retentionInDays), ), }, - mig.TestStep(config), + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_test.go b/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_test.go index bb2197fbe3..527b915578 100644 --- a/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_test.go +++ b/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_test.go @@ -6,7 +6,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -71,7 +70,7 @@ func TestAccBackupRSCloudBackupSnapshot_basic(t *testing.T) { func TestAccBackupRSCloudBackupSnapshot_sharded(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() description = "My description in my cluster" retentionInDays = "4" ) diff --git a/internal/service/cloudbackupsnapshotrestorejob/resource_cloud_backup_snapshot_restore_job_test.go b/internal/service/cloudbackupsnapshotrestorejob/resource_cloud_backup_snapshot_restore_job_test.go index 41777ed783..0c90ca2ff7 100644 --- a/internal/service/cloudbackupsnapshotrestorejob/resource_cloud_backup_snapshot_restore_job_test.go +++ b/internal/service/cloudbackupsnapshotrestorejob/resource_cloud_backup_snapshot_restore_job_test.go @@ -8,7 +8,6 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -24,12 +23,11 @@ func TestAccBackupRSCloudBackupSnapshotRestoreJob_basic(t *testing.T) { snapshotsDataSourcePaginationName = "data.mongodbatlas_cloud_backup_snapshot_restore_jobs.pagination" dataSourceName = "data.mongodbatlas_cloud_backup_snapshot_restore_job.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-snapshot-acc") - targetProjectName = acctest.RandomWithPrefix("test-acc") - clusterName = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() description = fmt.Sprintf("My description in %s", clusterName) retentionInDays = "1" - targetClusterName = fmt.Sprintf("test-acc-target-%s", acctest.RandString(10)) + targetClusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -38,7 +36,7 @@ func TestAccBackupRSCloudBackupSnapshotRestoreJob_basic(t *testing.T) { CheckDestroy: testAccCheckMongoDBAtlasCloudBackupSnapshotRestoreJobDestroy, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasCloudBackupSnapshotRestoreJobConfigAutomated(orgID, projectName, clusterName, description, retentionInDays, targetProjectName, targetClusterName), + Config: testAccMongoDBAtlasCloudBackupSnapshotRestoreJobConfigAutomated(orgID, projectName, clusterName, description, retentionInDays, targetClusterName), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasCloudBackupSnapshotRestoreJobExists(resourceName, &cloudBackupSnapshotRestoreJob), testAccCheckMongoDBAtlasCloudBackupSnapshotRestoreJobAttributes(&cloudBackupSnapshotRestoreJob, "automated"), @@ -65,8 +63,8 @@ func TestAccBackupRSCloudBackupSnapshotRestoreJob_basicDownload(t *testing.T) { cloudBackupSnapshotRestoreJob = matlas.CloudProviderSnapshotRestoreJob{} resourceName = "mongodbatlas_cloud_backup_snapshot_restore_job.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - clusterName = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() description = fmt.Sprintf("My description in %s", clusterName) retentionInDays = "1" useSnapshotID = true @@ -97,9 +95,9 @@ func TestAccBackupRSCloudBackupSnapshotRestoreJobWithPointTime_basic(t *testing. acc.SkipTestForCI(t) var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - targetProjectName = acctest.RandomWithPrefix("test-acc-target") - clusterName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + targetProjectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() description = fmt.Sprintf("My description in %s", clusterName) retentionInDays = "1" timeUtc = int64(1) @@ -181,15 +179,14 @@ func testAccCheckMongoDBAtlasCloudBackupSnapshotRestoreJobImportStateIDFunc(reso } } -func testAccMongoDBAtlasCloudBackupSnapshotRestoreJobConfigAutomated(orgID, projectName, clusterName, description, retentionInDays, targetProjectName, targetClusterName string) string { +func testAccMongoDBAtlasCloudBackupSnapshotRestoreJobConfigAutomated(orgID, projectName, clusterName, description, retentionInDays, targetClusterName string) string { return fmt.Sprintf(` resource "mongodbatlas_project" "backup_project" { - name = %[2]q org_id = %[1]q + name = %[2]q } - resource "mongodbatlas_cluster" "my_cluster" { project_id = mongodbatlas_project.backup_project.id name = %[3]q @@ -203,7 +200,7 @@ resource "mongodbatlas_cluster" "my_cluster" { resource "mongodbatlas_cluster" "targer_cluster" { project_id = mongodbatlas_project.backup_project.id - name = %[7]q + name = %[6]q // Provider Settings "block" provider_name = "AWS" @@ -249,7 +246,7 @@ data "mongodbatlas_cloud_backup_snapshot_restore_jobs" "pagination" { items_per_page = 5 } - `, orgID, projectName, clusterName, description, retentionInDays, targetProjectName, targetClusterName) + `, orgID, projectName, clusterName, description, retentionInDays, targetClusterName) } func testAccMongoDBAtlasCloudBackupSnapshotRestoreJobConfigDownload(orgID, projectName, clusterName, description, retentionInDays string, useSnapshotID bool) string { @@ -296,13 +293,13 @@ func testAccMongoDBAtlasCloudBackupSnapshotRestoreJobConfigPointInTime(orgID, pr return fmt.Sprintf(` resource "mongodbatlas_project" "backup_project" { - name = %[2]q org_id = %[1]q + name = %[2]q } resource "mongodbatlas_project" "target_project" { - name = %[6]q org_id = %[1]q + name = %[6]q } resource "mongodbatlas_cluster" "target_cluster" { diff --git a/internal/service/cloudprovideraccess/resource_cloud_provider_access_authorization_test.go b/internal/service/cloudprovideraccess/resource_cloud_provider_access_authorization_test.go index 6a812adeb6..7c81cbc893 100644 --- a/internal/service/cloudprovideraccess/resource_cloud_provider_access_authorization_test.go +++ b/internal/service/cloudprovideraccess/resource_cloud_provider_access_authorization_test.go @@ -6,7 +6,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -19,9 +18,9 @@ func TestAccConfigRSCloudProviderAccessAuthorizationAWS_basic(t *testing.T) { acc.SkipTestForCI(t) var ( projectID = os.Getenv("MONGODB_ATLAS_PROJECT_ID") - policyName = acctest.RandomWithPrefix("tf-acc") - roleName = acctest.RandomWithPrefix("tf-acc") - roleNameUpdated = acctest.RandomWithPrefix("tf-acc") + policyName = acc.RandomName() + roleName = acc.RandomName() + roleNameUpdated = acc.RandomName() ) resource.Test(t, resource.TestCase{ @@ -45,10 +44,10 @@ func TestAccConfigRSCloudProviderAccessAuthorizationAWS_basic(t *testing.T) { func TestAccConfigRSCloudProviderAccessAuthorizationAzure_basic(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("tf-acc") atlasAzureAppID = os.Getenv("AZURE_ATLAS_APP_ID") servicePrincipalID = os.Getenv("AZURE_SERVICE_PRINCIPAL_ID") tenantID = os.Getenv("AZURE_TENANT_ID") + projectName = acc.RandomProjectName() ) resource.Test(t, resource.TestCase{ diff --git a/internal/service/cloudprovideraccess/resource_cloud_provider_access_setup_test.go b/internal/service/cloudprovideraccess/resource_cloud_provider_access_setup_test.go index 602c7fe0dc..b7cd4fcca5 100644 --- a/internal/service/cloudprovideraccess/resource_cloud_provider_access_setup_test.go +++ b/internal/service/cloudprovideraccess/resource_cloud_provider_access_setup_test.go @@ -6,7 +6,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -20,7 +19,7 @@ func TestAccConfigRSCloudProviderAccessSetupAWS_basic(t *testing.T) { resourceName = "mongodbatlas_cloud_provider_access_setup.test" dataSourceName = "data.mongodbatlas_cloud_provider_access_setup.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() targetRole = matlas.CloudProviderAccessRole{} ) @@ -48,7 +47,7 @@ func TestAccConfigRSCloudProviderAccessSetupAWS_importBasic(t *testing.T) { var ( resourceName = "mongodbatlas_cloud_provider_access_setup.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() targetRole = matlas.CloudProviderAccessRole{} ) @@ -86,7 +85,7 @@ func TestAccConfigRSCloudProviderAccessSetupAzure_basic(t *testing.T) { atlasAzureAppID = os.Getenv("AZURE_ATLAS_APP_ID") servicePrincipalID = os.Getenv("AZURE_SERVICE_PRINCIPAL_ID") tenantID = os.Getenv("AZURE_TENANT_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() targetRole = matlas.CloudProviderAccessRole{} ) diff --git a/internal/service/cluster/resource_cluster_test.go b/internal/service/cluster/resource_cluster_test.go index 26d6d5b9c5..7562187647 100644 --- a/internal/service/cluster/resource_cluster_test.go +++ b/internal/service/cluster/resource_cluster_test.go @@ -9,7 +9,6 @@ import ( "regexp" "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/hashicorp/terraform-plugin-testing/terraform" @@ -24,8 +23,8 @@ func TestAccClusterRSCluster_basicAWS_simple(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -34,12 +33,12 @@ func TestAccClusterRSCluster_basicAWS_simple(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigAWS(orgID, projectName, name, true, true), + Config: testAccMongoDBAtlasClusterConfigAWS(orgID, projectName, clusterName, true, true), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "100"), resource.TestCheckResourceAttr(resourceName, "pit_enabled", "true"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), @@ -57,12 +56,12 @@ func TestAccClusterRSCluster_basicAWS_simple(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigAWS(orgID, projectName, name, false, false), + Config: testAccMongoDBAtlasClusterConfigAWS(orgID, projectName, clusterName, false, false), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "100"), resource.TestCheckResourceAttr(resourceName, "pit_enabled", "false"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), @@ -82,8 +81,8 @@ func TestAccClusterRSCluster_basicAWS_instanceScale(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -92,23 +91,23 @@ func TestAccClusterRSCluster_basicAWS_instanceScale(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigAWSNVMEInstance(orgID, projectName, name, "M40_NVME"), + Config: testAccMongoDBAtlasClusterConfigAWSNVMEInstance(orgID, projectName, clusterName, "M40_NVME"), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "provider_instance_size_name", "M40_NVME"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), ), }, { - Config: testAccMongoDBAtlasClusterConfigAWSNVMEInstance(orgID, projectName, name, "M50_NVME"), + Config: testAccMongoDBAtlasClusterConfigAWSNVMEInstance(orgID, projectName, clusterName, "M50_NVME"), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "provider_instance_size_name", "M50_NVME"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), ), @@ -124,8 +123,8 @@ func TestAccClusterRSCluster_basic_Partial_AdvancedConf(t *testing.T) { dataSourceName = "data.mongodbatlas_cluster.test" dataSourceClustersName = "data.mongodbatlas_clusters.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -134,7 +133,7 @@ func TestAccClusterRSCluster_basic_Partial_AdvancedConf(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigAdvancedConf(orgID, projectName, name, "false", &matlas.ProcessArgs{ + Config: testAccMongoDBAtlasClusterConfigAdvancedConf(orgID, projectName, clusterName, "false", &matlas.ProcessArgs{ FailIndexKeyTooLong: conversion.Pointer(false), JavascriptEnabled: conversion.Pointer(true), MinimumEnabledTLSProtocol: "TLS1_1", @@ -146,7 +145,7 @@ func TestAccClusterRSCluster_basic_Partial_AdvancedConf(t *testing.T) { }), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.minimum_enabled_tls_protocol", "TLS1_1"), @@ -155,7 +154,7 @@ func TestAccClusterRSCluster_basic_Partial_AdvancedConf(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.sample_refresh_interval_bi_connector", "310"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.sample_size_bi_connector", "110"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.transaction_lifetime_limit_seconds", "300"), - resource.TestCheckResourceAttr(dataSourceName, "name", name), + resource.TestCheckResourceAttr(dataSourceName, "name", clusterName), resource.TestCheckResourceAttr(dataSourceName, "disk_size_gb", "10"), resource.TestCheckResourceAttrSet(dataSourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(dataSourceName, "replication_specs.#"), @@ -171,12 +170,12 @@ func TestAccClusterRSCluster_basic_Partial_AdvancedConf(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigAdvancedConfPartial(orgID, projectName, name, "false", &matlas.ProcessArgs{ + Config: testAccMongoDBAtlasClusterConfigAdvancedConfPartial(orgID, projectName, clusterName, "false", &matlas.ProcessArgs{ MinimumEnabledTLSProtocol: "TLS1_2", }), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.minimum_enabled_tls_protocol", "TLS1_2"), @@ -195,8 +194,8 @@ func TestAccClusterRSCluster_basic_DefaultWriteRead_AdvancedConf(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.advance_conf" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -205,7 +204,7 @@ func TestAccClusterRSCluster_basic_DefaultWriteRead_AdvancedConf(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigAdvancedConfDefaultWriteRead(orgID, projectName, name, "false", &matlas.ProcessArgs{ + Config: testAccMongoDBAtlasClusterConfigAdvancedConfDefaultWriteRead(orgID, projectName, clusterName, "false", &matlas.ProcessArgs{ DefaultReadConcern: "available", DefaultWriteConcern: "1", FailIndexKeyTooLong: conversion.Pointer(false), @@ -219,7 +218,7 @@ func TestAccClusterRSCluster_basic_DefaultWriteRead_AdvancedConf(t *testing.T) { }), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_read_concern", "available"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_write_concern", "1"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), @@ -231,12 +230,12 @@ func TestAccClusterRSCluster_basic_DefaultWriteRead_AdvancedConf(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigAdvancedConfPartialDefault(orgID, projectName, name, "false", &matlas.ProcessArgs{ + Config: testAccMongoDBAtlasClusterConfigAdvancedConfPartialDefault(orgID, projectName, clusterName, "false", &matlas.ProcessArgs{ MinimumEnabledTLSProtocol: "TLS1_2", }), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_read_concern", "available"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.default_write_concern", "1"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), @@ -255,8 +254,8 @@ func TestAccClusterRSCluster_emptyAdvancedConf(t *testing.T) { var ( resourceName = "mongodbatlas_cluster.advance_conf" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -265,12 +264,12 @@ func TestAccClusterRSCluster_emptyAdvancedConf(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigAdvancedConfPartial(orgID, projectName, name, "false", &matlas.ProcessArgs{ + Config: testAccMongoDBAtlasClusterConfigAdvancedConfPartial(orgID, projectName, clusterName, "false", &matlas.ProcessArgs{ MinimumEnabledTLSProtocol: "TLS1_2", }), }, { - Config: testAccMongoDBAtlasClusterConfigAdvancedConf(orgID, projectName, name, "false", &matlas.ProcessArgs{ + Config: testAccMongoDBAtlasClusterConfigAdvancedConf(orgID, projectName, clusterName, "false", &matlas.ProcessArgs{ FailIndexKeyTooLong: conversion.Pointer(false), JavascriptEnabled: conversion.Pointer(true), MinimumEnabledTLSProtocol: "TLS1_1", @@ -300,8 +299,8 @@ func TestAccClusterRSCluster_basicAdvancedConf(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.advance_conf" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -310,7 +309,7 @@ func TestAccClusterRSCluster_basicAdvancedConf(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigAdvancedConf(orgID, projectName, name, "false", &matlas.ProcessArgs{ + Config: testAccMongoDBAtlasClusterConfigAdvancedConf(orgID, projectName, clusterName, "false", &matlas.ProcessArgs{ FailIndexKeyTooLong: conversion.Pointer(false), JavascriptEnabled: conversion.Pointer(true), MinimumEnabledTLSProtocol: "TLS1_2", @@ -322,7 +321,7 @@ func TestAccClusterRSCluster_basicAdvancedConf(t *testing.T) { }), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.minimum_enabled_tls_protocol", "TLS1_2"), @@ -334,7 +333,7 @@ func TestAccClusterRSCluster_basicAdvancedConf(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigAdvancedConf(orgID, projectName, name, "false", &matlas.ProcessArgs{ + Config: testAccMongoDBAtlasClusterConfigAdvancedConf(orgID, projectName, clusterName, "false", &matlas.ProcessArgs{ FailIndexKeyTooLong: conversion.Pointer(false), JavascriptEnabled: conversion.Pointer(false), MinimumEnabledTLSProtocol: "TLS1_1", @@ -346,7 +345,7 @@ func TestAccClusterRSCluster_basicAdvancedConf(t *testing.T) { }), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.fail_index_key_too_long", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.javascript_enabled", "false"), resource.TestCheckResourceAttr(resourceName, "advanced_configuration.0.minimum_enabled_tls_protocol", "TLS1_1"), @@ -366,8 +365,8 @@ func TestAccClusterRSCluster_basicAzure(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.basic_azure" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -376,24 +375,24 @@ func TestAccClusterRSCluster_basicAzure(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigAzure(orgID, projectName, name, "true", "M30", true), + Config: testAccMongoDBAtlasClusterConfigAzure(orgID, projectName, clusterName, "true", "M30", true), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.regions_config.#"), ), }, { - Config: testAccMongoDBAtlasClusterConfigAzure(orgID, projectName, name, "false", "M30", true), + Config: testAccMongoDBAtlasClusterConfigAzure(orgID, projectName, clusterName, "false", "M30", true), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.regions_config.#"), @@ -408,8 +407,8 @@ func TestAccClusterRSCluster_AzureUpdateToNVME(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.basic_azure" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, @@ -417,12 +416,12 @@ func TestAccClusterRSCluster_AzureUpdateToNVME(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigAzure(orgID, projectName, name, "true", "M60", true), + Config: testAccMongoDBAtlasClusterConfigAzure(orgID, projectName, clusterName, "true", "M60", true), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "provider_instance_size_name", "M60"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -430,12 +429,12 @@ func TestAccClusterRSCluster_AzureUpdateToNVME(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigAzure(orgID, projectName, name, "true", "M60_NVME", false), + Config: testAccMongoDBAtlasClusterConfigAzure(orgID, projectName, clusterName, "true", "M60_NVME", false), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "provider_instance_size_name", "M60_NVME"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -451,8 +450,8 @@ func TestAccClusterRSCluster_basicGCP(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.basic_gcp" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -461,12 +460,12 @@ func TestAccClusterRSCluster_basicGCP(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigGCP(orgID, projectName, name, "true"), + Config: testAccMongoDBAtlasClusterConfigGCP(orgID, projectName, clusterName, "true"), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "40"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -474,12 +473,12 @@ func TestAccClusterRSCluster_basicGCP(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigGCP(orgID, projectName, name, "false"), + Config: testAccMongoDBAtlasClusterConfigGCP(orgID, projectName, clusterName, "false"), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "40"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -495,8 +494,8 @@ func TestAccClusterRSCluster_WithBiConnectorGCP(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.basic_gcp" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -505,12 +504,12 @@ func TestAccClusterRSCluster_WithBiConnectorGCP(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigGCPWithBiConnector(orgID, projectName, name, "true", false), + Config: testAccMongoDBAtlasClusterConfigGCPWithBiConnector(orgID, projectName, clusterName, "true", false), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "40"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -519,12 +518,12 @@ func TestAccClusterRSCluster_WithBiConnectorGCP(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigGCPWithBiConnector(orgID, projectName, name, "false", true), + Config: testAccMongoDBAtlasClusterConfigGCPWithBiConnector(orgID, projectName, clusterName, "false", true), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "40"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -541,8 +540,8 @@ func TestAccClusterRSCluster_MultiRegion(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.multi_region" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-multi-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) createRegionsConfig := `regions_config { @@ -577,15 +576,15 @@ func TestAccClusterRSCluster_MultiRegion(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigMultiRegion(orgID, projectName, name, "true", createRegionsConfig), + Config: testAccMongoDBAtlasClusterConfigMultiRegion(orgID, projectName, clusterName, "true", createRegionsConfig), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.regions_config.#"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "100"), resource.TestCheckResourceAttr(resourceName, "cluster_type", "REPLICASET"), resource.TestCheckResourceAttr(resourceName, "replication_specs.#", "1"), @@ -593,15 +592,15 @@ func TestAccClusterRSCluster_MultiRegion(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigMultiRegion(orgID, projectName, name, "false", updatedRegionsConfig), + Config: testAccMongoDBAtlasClusterConfigMultiRegion(orgID, projectName, clusterName, "false", updatedRegionsConfig), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.regions_config.#"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "100"), resource.TestCheckResourceAttr(resourceName, "cluster_type", "REPLICASET"), resource.TestCheckResourceAttr(resourceName, "replication_specs.#", "1"), @@ -617,8 +616,8 @@ func TestAccClusterRSCluster_ProviderRegionName(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.multi_region" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-multi-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) updatedRegionsConfig := `regions_config { @@ -646,19 +645,19 @@ func TestAccClusterRSCluster_ProviderRegionName(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigMultiRegionWithProviderRegionNameInvalid(orgID, projectName, name, "false", updatedRegionsConfig), + Config: testAccMongoDBAtlasClusterConfigMultiRegionWithProviderRegionNameInvalid(orgID, projectName, clusterName, "false", updatedRegionsConfig), ExpectError: regexp.MustCompile("attribute must be set ONLY for single-region clusters"), }, { - Config: testAccMongoDBAtlasClusterConfigSingleRegionWithProviderRegionName(orgID, projectName, name, "false"), + Config: testAccMongoDBAtlasClusterConfigSingleRegionWithProviderRegionName(orgID, projectName, clusterName, "false"), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.regions_config.#"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "100"), resource.TestCheckResourceAttr(resourceName, "cluster_type", "REPLICASET"), resource.TestCheckResourceAttr(resourceName, "replication_specs.#", "1"), @@ -666,15 +665,15 @@ func TestAccClusterRSCluster_ProviderRegionName(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigMultiRegion(orgID, projectName, name, "false", updatedRegionsConfig), + Config: testAccMongoDBAtlasClusterConfigMultiRegion(orgID, projectName, clusterName, "false", updatedRegionsConfig), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.regions_config.#"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "100"), resource.TestCheckResourceAttr(resourceName, "cluster_type", "REPLICASET"), resource.TestCheckResourceAttr(resourceName, "replication_specs.#", "1"), @@ -682,7 +681,7 @@ func TestAccClusterRSCluster_ProviderRegionName(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigMultiRegion(orgID, projectName, name, "false", updatedRegionsConfig), + Config: testAccMongoDBAtlasClusterConfigMultiRegion(orgID, projectName, clusterName, "false", updatedRegionsConfig), ConfigPlanChecks: resource.ConfigPlanChecks{ PreApply: []plancheck.PlanCheck{ acc.DebugPlan(), @@ -700,8 +699,8 @@ func TestAccClusterRSCluster_Global(t *testing.T) { resourceSuffix = "global_cluster" resourceName = fmt.Sprintf("mongodbatlas_cluster.%s", resourceSuffix) orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-global-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -710,16 +709,16 @@ func TestAccClusterRSCluster_Global(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: acc.ConfigClusterGlobal(resourceSuffix, orgID, projectName, name, "false"), + Config: acc.ConfigClusterGlobal(resourceSuffix, orgID, projectName, clusterName, "false"), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.0.regions_config.#"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.1.regions_config.#"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "80"), resource.TestCheckResourceAttr(resourceName, "cluster_type", "GEOSHARDED"), resource.TestCheckResourceAttr(resourceName, "replication_specs.#", "2"), @@ -736,8 +735,8 @@ func TestAccClusterRSCluster_AWSWithLabels(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.aws_with_labels" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("testAcc-%s-%s-%s", "AWS", "M10", acctest.RandString(1)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -746,19 +745,19 @@ func TestAccClusterRSCluster_AWSWithLabels(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterAWSConfigdWithLabels(orgID, projectName, name, "false", "M10", "EU_CENTRAL_1", []matlas.Label{}), + Config: testAccMongoDBAtlasClusterAWSConfigdWithLabels(orgID, projectName, clusterName, "false", "M10", "EU_CENTRAL_1", []matlas.Label{}), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "10"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttr(resourceName, "labels.#", "0"), ), }, { - Config: testAccMongoDBAtlasClusterAWSConfigdWithLabels(orgID, projectName, name, "false", "M10", "EU_CENTRAL_1", + Config: testAccMongoDBAtlasClusterAWSConfigdWithLabels(orgID, projectName, clusterName, "false", "M10", "EU_CENTRAL_1", []matlas.Label{ { Key: "key 4", @@ -776,16 +775,16 @@ func TestAccClusterRSCluster_AWSWithLabels(t *testing.T) { ), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "10"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttr(resourceName, "labels.#", "3"), ), }, { - Config: testAccMongoDBAtlasClusterAWSConfigdWithLabels(orgID, projectName, name, "false", "M10", "EU_CENTRAL_1", + Config: testAccMongoDBAtlasClusterAWSConfigdWithLabels(orgID, projectName, clusterName, "false", "M10", "EU_CENTRAL_1", []matlas.Label{ { Key: "key 1", @@ -799,9 +798,9 @@ func TestAccClusterRSCluster_AWSWithLabels(t *testing.T) { ), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "10"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttr(resourceName, "labels.#", "2"), @@ -818,8 +817,8 @@ func TestAccClusterRSCluster_WithTags(t *testing.T) { dataSourceName = "data.mongodbatlas_cluster.test" dataSourceClustersName = "data.mongodbatlas_clusters.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("testAcc-%s-%s-%s", "AWS", "M10", acctest.RandString(1)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -828,12 +827,12 @@ func TestAccClusterRSCluster_WithTags(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigWithTags(orgID, projectName, name, "false", "M10", "EU_CENTRAL_1", []matlas.Tag{}), + Config: testAccMongoDBAtlasClusterConfigWithTags(orgID, projectName, clusterName, "false", "M10", "EU_CENTRAL_1", []matlas.Tag{}), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttr(resourceName, "tags.#", "0"), resource.TestCheckResourceAttr(dataSourceName, "tags.#", "0"), @@ -841,7 +840,7 @@ func TestAccClusterRSCluster_WithTags(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigWithTags(orgID, projectName, name, "false", "M10", "EU_CENTRAL_1", + Config: testAccMongoDBAtlasClusterConfigWithTags(orgID, projectName, clusterName, "false", "M10", "EU_CENTRAL_1", []matlas.Tag{ { Key: "key 1", @@ -855,9 +854,9 @@ func TestAccClusterRSCluster_WithTags(t *testing.T) { ), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttr(resourceName, "tags.#", "2"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tags.*", acc.ClusterTagsMap1), @@ -871,7 +870,7 @@ func TestAccClusterRSCluster_WithTags(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigWithTags(orgID, projectName, name, "false", "M10", "EU_CENTRAL_1", + Config: testAccMongoDBAtlasClusterConfigWithTags(orgID, projectName, clusterName, "false", "M10", "EU_CENTRAL_1", []matlas.Tag{ { Key: "key 3", @@ -881,9 +880,9 @@ func TestAccClusterRSCluster_WithTags(t *testing.T) { ), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttr(resourceName, "tags.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "tags.*", acc.ClusterTagsMap3), @@ -913,7 +912,7 @@ func TestAccClusterRSCluster_withPrivateEndpointLink(t *testing.T) { vpcID = os.Getenv("AWS_VPC_ID") subnetID = os.Getenv("AWS_SUBNET_ID") securityGroupID = os.Getenv("AWS_SECURITY_GROUP_ID") - clusterName = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + clusterName = acc.RandomClusterName() ) resource.Test(t, resource.TestCase{ @@ -948,7 +947,7 @@ func TestAccClusterRSCluster_withAzureNetworkPeering(t *testing.T) { region = os.Getenv("AZURE_REGION") atlasCidrBlock = "192.168.208.0/21" - clusterName = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + clusterName = acc.RandomClusterName() ) resource.Test(t, resource.TestCase{ @@ -977,8 +976,8 @@ func TestAccClusterRSCluster_withGCPNetworkPeering(t *testing.T) { gcpRegion = os.Getenv("GCP_REGION_NAME") gcpProjectID = os.Getenv("GCP_PROJECT_ID") providerName = "GCP" - gcpPeeringName = fmt.Sprintf("test-acc-%s", acctest.RandString(3)) - clusterName = fmt.Sprintf("test-acc-%s", acctest.RandString(3)) + gcpPeeringName = acc.RandomName() + clusterName = acc.RandomClusterName() gcpClusterRegion = os.Getenv("GCP_CLUSTER_REGION_NAME") ) @@ -1009,7 +1008,7 @@ func TestAccClusterRSCluster_withAzureAndContainerID(t *testing.T) { var ( resourceName = "mongodbatlas_cluster.test" projectID = os.Getenv("MONGODB_ATLAS_PROJECT_ID") - clusterName = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + clusterName = acc.RandomClusterName() providerName = "AZURE" region = os.Getenv("AZURE_REGION") directoryID = os.Getenv("AZURE_DIRECTORY_ID") @@ -1044,7 +1043,7 @@ func TestAccClusterRSCluster_withAWSAndContainerID(t *testing.T) { awsSecretKey = os.Getenv("AWS_SECRET_ACCESS_KEY") projectID = os.Getenv("MONGODB_ATLAS_PROJECT_ID") - clusterName = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + clusterName = acc.RandomClusterName() providerName = "AWS" awsRegion = os.Getenv("AWS_REGION") vpcCIDRBlock = os.Getenv("AWS_VPC_CIDR_BLOCK") @@ -1075,10 +1074,10 @@ func TestAccClusterRSCluster_withGCPAndContainerID(t *testing.T) { gcpProjectID = os.Getenv("GCP_PROJECT_ID") gcpRegion = os.Getenv("GCP_REGION_NAME") projectID = os.Getenv("MONGODB_ATLAS_PROJECT_ID") - clusterName = fmt.Sprintf("test-acc-%s", acctest.RandString(3)) + clusterName = acc.RandomClusterName() providerName = "GCP" gcpClusterRegion = os.Getenv("GCP_CLUSTER_REGION_NAME") - gcpPeeringName = fmt.Sprintf("test-acc-%s", acctest.RandString(3)) + gcpPeeringName = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -1108,8 +1107,8 @@ func TestAccClusterRSCluster_withAutoScalingAWS(t *testing.T) { dataSourceName = "data.mongodbatlas_cluster.test" dataSourceClustersName = "data.mongodbatlas_clusters.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() instanceSize = "M30" minSize = "" @@ -1126,15 +1125,15 @@ func TestAccClusterRSCluster_withAutoScalingAWS(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigAWSWithAutoscaling(orgID, projectName, name, "true", "false", "true", "false", minSize, maxSize, instanceSize), + Config: testAccMongoDBAtlasClusterConfigAWSWithAutoscaling(orgID, projectName, clusterName, "true", "false", "true", "false", minSize, maxSize, instanceSize), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "auto_scaling_compute_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "provider_auto_scaling_compute_max_instance_size", maxSize), - resource.TestCheckResourceAttr(dataSourceName, "name", name), + resource.TestCheckResourceAttr(dataSourceName, "name", clusterName), resource.TestCheckResourceAttr(dataSourceName, "auto_scaling_compute_enabled", "true"), resource.TestCheckResourceAttr(dataSourceName, "provider_auto_scaling_compute_max_instance_size", maxSize), resource.TestCheckResourceAttrSet(dataSourceName, "mongo_uri"), @@ -1151,12 +1150,12 @@ func TestAccClusterRSCluster_withAutoScalingAWS(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigAWSWithAutoscaling(orgID, projectName, name, "false", "true", "true", "true", minSizeUpdated, maxSizeUpdated, instanceSizeUpdated), + Config: testAccMongoDBAtlasClusterConfigAWSWithAutoscaling(orgID, projectName, clusterName, "false", "true", "true", "true", minSizeUpdated, maxSizeUpdated, instanceSizeUpdated), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "auto_scaling_compute_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "auto_scaling_compute_scale_down_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "provider_auto_scaling_compute_min_instance_size", minSizeUpdated), @@ -1171,8 +1170,8 @@ func TestAccClusterRSCluster_importBasic(t *testing.T) { var ( resourceName = "mongodbatlas_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - clusterName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -1199,8 +1198,8 @@ func TestAccClusterRSCluster_tenant(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.tenant" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) dbMajorVersion := testAccGetMongoDBAtlasMajorVersion() @@ -1211,23 +1210,23 @@ func TestAccClusterRSCluster_tenant(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigTenant(orgID, projectName, name, "M2", "2", dbMajorVersion), + Config: testAccMongoDBAtlasClusterConfigTenant(orgID, projectName, clusterName, "M2", "2", dbMajorVersion), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "2"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), ), }, { - Config: testAccMongoDBAtlasClusterConfigTenantUpdated(orgID, projectName, name), + Config: testAccMongoDBAtlasClusterConfigTenantUpdated(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "10"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), ), @@ -1237,13 +1236,14 @@ func TestAccClusterRSCluster_tenant(t *testing.T) { } func TestAccClusterRSCluster_tenant_m5(t *testing.T) { - var cluster matlas.Cluster - - resourceName := "mongodbatlas_cluster.tenant" - orgID := os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName := acctest.RandomWithPrefix("test-acc") - name := fmt.Sprintf("test-acc-%s", acctest.RandString(10)) - dbMajorVersion := testAccGetMongoDBAtlasMajorVersion() + var ( + cluster matlas.Cluster + resourceName = "mongodbatlas_cluster.tenant" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + dbMajorVersion = testAccGetMongoDBAtlasMajorVersion() + ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, @@ -1251,12 +1251,12 @@ func TestAccClusterRSCluster_tenant_m5(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigTenant(orgID, projectName, name, "M5", "5", dbMajorVersion), + Config: testAccMongoDBAtlasClusterConfigTenant(orgID, projectName, clusterName, "M5", "5", dbMajorVersion), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "5"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), ), @@ -1269,8 +1269,8 @@ func TestAccClusterRSCluster_basicGCPRegionNameWesternUS(t *testing.T) { var ( resourceName = "mongodbatlas_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - clusterName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() regionName = "WESTERN_US" ) @@ -1295,8 +1295,8 @@ func TestAccClusterRSCluster_basicGCPRegionNameUSWest2(t *testing.T) { var ( resourceName = "mongodbatlas_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - clusterName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() regionName = "US_WEST_2" ) @@ -1321,8 +1321,8 @@ func TestAccClusterRSCluster_RegionsConfig(t *testing.T) { var ( resourceName = "mongodbatlas_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - clusterName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) replications := `replication_specs { @@ -1443,8 +1443,8 @@ func TestAccClusterRSCluster_basicAWS_UnpauseToPaused(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -1453,12 +1453,12 @@ func TestAccClusterRSCluster_basicAWS_UnpauseToPaused(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigAWSPaused(orgID, projectName, name, true, false), + Config: testAccMongoDBAtlasClusterConfigAWSPaused(orgID, projectName, clusterName, true, false), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "100"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -1467,12 +1467,12 @@ func TestAccClusterRSCluster_basicAWS_UnpauseToPaused(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigAWSPaused(orgID, projectName, name, false, true), + Config: testAccMongoDBAtlasClusterConfigAWSPaused(orgID, projectName, clusterName, false, true), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "100"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -1496,8 +1496,8 @@ func TestAccClusterRSCluster_basicAWS_PausedToUnpaused(t *testing.T) { cluster matlas.Cluster resourceName = "mongodbatlas_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -1506,12 +1506,12 @@ func TestAccClusterRSCluster_basicAWS_PausedToUnpaused(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: testAccMongoDBAtlasClusterConfigAWSPaused(orgID, projectName, name, true, true), + Config: testAccMongoDBAtlasClusterConfigAWSPaused(orgID, projectName, clusterName, true, true), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "100"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -1520,12 +1520,12 @@ func TestAccClusterRSCluster_basicAWS_PausedToUnpaused(t *testing.T) { ), }, { - Config: testAccMongoDBAtlasClusterConfigAWSPaused(orgID, projectName, name, false, false), + Config: testAccMongoDBAtlasClusterConfigAWSPaused(orgID, projectName, clusterName, false, false), Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), resource.TestCheckResourceAttr(resourceName, "disk_size_gb", "100"), resource.TestCheckResourceAttrSet(resourceName, "mongo_uri"), resource.TestCheckResourceAttrSet(resourceName, "replication_specs.#"), @@ -1542,9 +1542,9 @@ func TestAccClusterRSCluster_withDefaultBiConnectorAndAdvancedConfiguration_main cluster matlas.Cluster resourceName = "mongodbatlas_cluster.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) - cfg = testAccMongoDBAtlasClusterConfigAWS(orgID, projectName, name, true, true) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + cfg = testAccMongoDBAtlasClusterConfigAWS(orgID, projectName, clusterName, true, true) ) resource.ParallelTest(t, resource.TestCase{ @@ -1556,9 +1556,9 @@ func TestAccClusterRSCluster_withDefaultBiConnectorAndAdvancedConfiguration_main Config: cfg, Check: resource.ComposeTestCheckFunc( testAccCheckMongoDBAtlasClusterExists(resourceName, &cluster), - testAccCheckMongoDBAtlasClusterAttributes(&cluster, name), + testAccCheckMongoDBAtlasClusterAttributes(&cluster, clusterName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), - resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "name", clusterName), ), }, { diff --git a/internal/service/customdbrole/data_source_custom_db_role_test.go b/internal/service/customdbrole/data_source_custom_db_role_test.go index b8dbe7bfe4..2249fbf6a4 100644 --- a/internal/service/customdbrole/data_source_custom_db_role_test.go +++ b/internal/service/customdbrole/data_source_custom_db_role_test.go @@ -5,17 +5,19 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) func TestAccConfigDSCustomDBRole_basic(t *testing.T) { - resourceName := "mongodbatlas_custom_db_role.test" - dataSourceName := "data.mongodbatlas_custom_db_role.test" - orgID := os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName := acctest.RandomWithPrefix("test-acc") - roleName := fmt.Sprintf("test-acc-custom_role-%s", acctest.RandString(5)) + var ( + resourceName = "mongodbatlas_custom_db_role.test" + dataSourceName = "data.mongodbatlas_custom_db_role.test" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + roleName = acc.RandomName() + databaseName = acc.RandomClusterName() + ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, @@ -23,7 +25,7 @@ func TestAccConfigDSCustomDBRole_basic(t *testing.T) { CheckDestroy: acc.CheckDestroyNetworkPeering, Steps: []resource.TestStep{ { - Config: configDS(orgID, projectName, roleName, "INSERT", fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + Config: configDS(orgID, projectName, roleName, "INSERT", databaseName), Check: resource.ComposeTestCheckFunc( // Test for Resource checkExists(resourceName), diff --git a/internal/service/customdbrole/data_source_custom_db_roles_test.go b/internal/service/customdbrole/data_source_custom_db_roles_test.go index 74e5411840..ab45d7fbed 100644 --- a/internal/service/customdbrole/data_source_custom_db_roles_test.go +++ b/internal/service/customdbrole/data_source_custom_db_roles_test.go @@ -5,17 +5,19 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) func TestAccConfigDSCustomDBRoles_basic(t *testing.T) { - resourceName := "mongodbatlas_custom_db_role.test" - dataSourceName := "data.mongodbatlas_custom_db_roles.test" - orgID := os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName := acctest.RandomWithPrefix("test-acc") - roleName := fmt.Sprintf("test-acc-custom_role-%s", acctest.RandString(5)) + var ( + resourceName = "mongodbatlas_custom_db_role.test" + dataSourceName = "data.mongodbatlas_custom_db_roles.test" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + roleName = acc.RandomName() + databaseName = acc.RandomClusterName() + ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, @@ -23,7 +25,7 @@ func TestAccConfigDSCustomDBRoles_basic(t *testing.T) { CheckDestroy: acc.CheckDestroyNetworkPeering, Steps: []resource.TestStep{ { - Config: configDSPlural(orgID, projectName, roleName, "INSERT", fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + Config: configDSPlural(orgID, projectName, roleName, "INSERT", databaseName), Check: resource.ComposeTestCheckFunc( // Test for Resource checkExists(resourceName), diff --git a/internal/service/customdbrole/resource_custom_db_role_migration_test.go b/internal/service/customdbrole/resource_custom_db_role_migration_test.go index 23f9943302..ff91b3a461 100644 --- a/internal/service/customdbrole/resource_custom_db_role_migration_test.go +++ b/internal/service/customdbrole/resource_custom_db_role_migration_test.go @@ -1,13 +1,10 @@ package customdbrole_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" ) @@ -15,9 +12,10 @@ import ( func TestAccMigrationConfigCustomDBRoles_Basic(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - roleName = fmt.Sprintf("test-acc-custom_role-%s", acctest.RandString(5)) - databaseName = fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5)) + projectName = acc.RandomProjectName() + roleName = acc.RandomName() + databaseName = acc.RandomClusterName() + config = configBasic(orgID, projectName, roleName, "INSERT", databaseName) ) resource.ParallelTest(t, resource.TestCase{ @@ -26,7 +24,7 @@ func TestAccMigrationConfigCustomDBRoles_Basic(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: configBasic(orgID, projectName, roleName, "INSERT", databaseName), + Config: config, Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), @@ -36,16 +34,7 @@ func TestAccMigrationConfigCustomDBRoles_Basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "actions.0.resources.#", "1"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: configBasic(orgID, projectName, roleName, "INSERT", databaseName), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/customdbrole/resource_custom_db_role_test.go b/internal/service/customdbrole/resource_custom_db_role_test.go index e78d979604..3db0d313c0 100644 --- a/internal/service/customdbrole/resource_custom_db_role_test.go +++ b/internal/service/customdbrole/resource_custom_db_role_test.go @@ -6,7 +6,6 @@ import ( "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/hashicorp/terraform-plugin-testing/terraform" @@ -20,9 +19,11 @@ const resourceName = "mongodbatlas_custom_db_role.test" func TestAccConfigRSCustomDBRoles_Basic(t *testing.T) { var ( - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - roleName = fmt.Sprintf("test-acc-custom_role-%s", acctest.RandString(5)) + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + roleName = acc.RandomName() + databaseName1 = acc.RandomClusterName() + databaseName2 = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -31,7 +32,7 @@ func TestAccConfigRSCustomDBRoles_Basic(t *testing.T) { CheckDestroy: checkDestroy, Steps: []resource.TestStep{ { - Config: configBasic(orgID, projectName, roleName, "INSERT", fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + Config: configBasic(orgID, projectName, roleName, "INSERT", databaseName1), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), @@ -42,7 +43,7 @@ func TestAccConfigRSCustomDBRoles_Basic(t *testing.T) { ), }, { - Config: configBasic(orgID, projectName, roleName, "UPDATE", fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + Config: configBasic(orgID, projectName, roleName, "UPDATE", databaseName2), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), @@ -57,24 +58,26 @@ func TestAccConfigRSCustomDBRoles_Basic(t *testing.T) { } func TestAccConfigRSCustomDBRoles_WithInheritedRoles(t *testing.T) { - testRoleResourceName := "mongodbatlas_custom_db_role.test_role" - InheritedRoleResourceNameOne := "mongodbatlas_custom_db_role.inherited_role_one" - InheritedRoleResourceNameTwo := "mongodbatlas_custom_db_role.inherited_role_two" - orgID := os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName := acctest.RandomWithPrefix("test-acc") + var ( + testRoleResourceName = "mongodbatlas_custom_db_role.test_role" + InheritedRoleResourceNameOne = "mongodbatlas_custom_db_role.inherited_role_one" + InheritedRoleResourceNameTwo = "mongodbatlas_custom_db_role.inherited_role_two" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectName = acc.RandomProjectName() + ) inheritRole := []matlas.CustomDBRole{ { - RoleName: fmt.Sprintf("test-acc-INHERITED_ROLE-%s", acctest.RandString(5)), + RoleName: acc.RandomName(), Actions: []matlas.Action{{ Action: "INSERT", Resources: []matlas.Resource{{ - DB: conversion.Pointer(fmt.Sprintf("b_test-acc-ddb_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }}, }}, }, { - RoleName: fmt.Sprintf("test-acc-INHERITED_ROLE-%s", acctest.RandString(5)), + RoleName: acc.RandomName(), Actions: []matlas.Action{{ Action: "SERVER_STATUS", Resources: []matlas.Resource{{ @@ -85,11 +88,11 @@ func TestAccConfigRSCustomDBRoles_WithInheritedRoles(t *testing.T) { } testRole := &matlas.CustomDBRole{ - RoleName: fmt.Sprintf("test-acc-TEST_ROLE-%s", acctest.RandString(5)), + RoleName: acc.RandomName(), Actions: []matlas.Action{{ Action: "UPDATE", Resources: []matlas.Resource{{ - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }}, }}, } @@ -100,7 +103,7 @@ func TestAccConfigRSCustomDBRoles_WithInheritedRoles(t *testing.T) { Actions: []matlas.Action{{ Action: "FIND", Resources: []matlas.Resource{{ - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }}, }}, }, @@ -120,7 +123,7 @@ func TestAccConfigRSCustomDBRoles_WithInheritedRoles(t *testing.T) { Actions: []matlas.Action{{ Action: "REMOVE", Resources: []matlas.Resource{{ - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }}, }}, } @@ -201,20 +204,20 @@ func TestAccConfigRSCustomDBRoles_MultipleCustomRoles(t *testing.T) { testRoleResourceName = "mongodbatlas_custom_db_role.test_role" InheritedRoleResourceName = "mongodbatlas_custom_db_role.inherited_role" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) inheritRole := &matlas.CustomDBRole{ - RoleName: fmt.Sprintf("test-acc-INHERITED_ROLE-%s", acctest.RandString(5)), + RoleName: acc.RandomName(), Actions: []matlas.Action{ { Action: "REMOVE", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -222,7 +225,7 @@ func TestAccConfigRSCustomDBRoles_MultipleCustomRoles(t *testing.T) { Action: "FIND", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -230,16 +233,16 @@ func TestAccConfigRSCustomDBRoles_MultipleCustomRoles(t *testing.T) { } testRole := &matlas.CustomDBRole{ - RoleName: fmt.Sprintf("test-acc-TEST_ROLE-%s", acctest.RandString(5)), + RoleName: acc.RandomName(), Actions: []matlas.Action{ { Action: "UPDATE", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -247,7 +250,7 @@ func TestAccConfigRSCustomDBRoles_MultipleCustomRoles(t *testing.T) { Action: "INSERT", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -267,7 +270,7 @@ func TestAccConfigRSCustomDBRoles_MultipleCustomRoles(t *testing.T) { Action: "UPDATE", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -275,10 +278,10 @@ func TestAccConfigRSCustomDBRoles_MultipleCustomRoles(t *testing.T) { Action: "FIND", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -286,10 +289,10 @@ func TestAccConfigRSCustomDBRoles_MultipleCustomRoles(t *testing.T) { Action: "INSERT", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -303,7 +306,7 @@ func TestAccConfigRSCustomDBRoles_MultipleCustomRoles(t *testing.T) { Action: "REMOVE", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -375,7 +378,7 @@ func TestAccConfigRSCustomDBRoles_MultipleResources(t *testing.T) { for i := 0; i < 5; i++ { roleName := fmt.Sprintf("test-acc-custom_role-%d", i) - projectName := acctest.RandomWithPrefix("test-acc") + projectName := acc.RandomProjectName() t.Run(roleName, func(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, @@ -383,7 +386,7 @@ func TestAccConfigRSCustomDBRoles_MultipleResources(t *testing.T) { CheckDestroy: checkDestroy, Steps: []resource.TestStep{ { - Config: configBasic(orgID, projectName, roleName, "INSERT", fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + Config: configBasic(orgID, projectName, roleName, "INSERT", acc.RandomClusterName()), Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), @@ -402,9 +405,9 @@ func TestAccConfigRSCustomDBRoles_MultipleResources(t *testing.T) { func TestAccConfigRSCustomDBRoles_importBasic(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - roleName = fmt.Sprintf("test-acc-custom_role-%s", acctest.RandString(5)) - databaseName = fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5)) + projectName = acc.RandomProjectName() + roleName = acc.RandomName() + databaseName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -440,20 +443,20 @@ func TestAccConfigRSCustomDBRoles_UpdatedInheritRoles(t *testing.T) { testRoleResourceName = "mongodbatlas_custom_db_role.test_role" InheritedRoleResourceName = "mongodbatlas_custom_db_role.inherited_role" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) inheritRole := &matlas.CustomDBRole{ - RoleName: fmt.Sprintf("test-acc-INHERITED_ROLE-%s", acctest.RandString(5)), + RoleName: acc.RandomName(), Actions: []matlas.Action{ { Action: "REMOVE", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -461,7 +464,7 @@ func TestAccConfigRSCustomDBRoles_UpdatedInheritRoles(t *testing.T) { Action: "FIND", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -475,7 +478,7 @@ func TestAccConfigRSCustomDBRoles_UpdatedInheritRoles(t *testing.T) { Action: "UPDATE", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -483,10 +486,10 @@ func TestAccConfigRSCustomDBRoles_UpdatedInheritRoles(t *testing.T) { Action: "FIND", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -494,10 +497,10 @@ func TestAccConfigRSCustomDBRoles_UpdatedInheritRoles(t *testing.T) { Action: "INSERT", Resources: []matlas.Resource{ { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, { - DB: conversion.Pointer(fmt.Sprintf("test-acc-db_name-%s", acctest.RandString(5))), + DB: conversion.Pointer(acc.RandomClusterName()), }, }, }, @@ -505,7 +508,7 @@ func TestAccConfigRSCustomDBRoles_UpdatedInheritRoles(t *testing.T) { } testRole := &matlas.CustomDBRole{ - RoleName: fmt.Sprintf("test-acc-TEST_ROLE-%s", acctest.RandString(5)), + RoleName: acc.RandomName(), InheritedRoles: []matlas.InheritedRole{ { Role: inheritRole.RoleName, diff --git a/internal/service/customdnsconfigurationclusteraws/data_source_custom_dns_configuration_cluster_aws_test.go b/internal/service/customdnsconfigurationclusteraws/data_source_custom_dns_configuration_cluster_aws_test.go index d6f0cc062d..591d8c8811 100644 --- a/internal/service/customdnsconfigurationclusteraws/data_source_custom_dns_configuration_cluster_aws_test.go +++ b/internal/service/customdnsconfigurationclusteraws/data_source_custom_dns_configuration_cluster_aws_test.go @@ -5,7 +5,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) @@ -14,7 +13,7 @@ const dataSourceName = "data.mongodbatlas_custom_dns_configuration_cluster_aws.t func TestAccConfigDSCustomDNSConfigurationAWS_basic(t *testing.T) { orgID := os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName := acctest.RandomWithPrefix("test-acc") + projectName := acc.RandomProjectName() resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, diff --git a/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws_migration_test.go b/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws_migration_test.go index ce1507cc65..0fd0a2399f 100644 --- a/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws_migration_test.go +++ b/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws_migration_test.go @@ -4,15 +4,15 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" ) func TestAccMigrationConfigRSCustomDNSConfigurationAWS_basic(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() config = configBasic(orgID, projectName, true) ) @@ -29,7 +29,7 @@ func TestAccMigrationConfigRSCustomDNSConfigurationAWS_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "enabled", "true"), ), }, - mig.TestStep(config), + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws_test.go b/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws_test.go index 9e9457fa1e..bf105a8e07 100644 --- a/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws_test.go +++ b/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws_test.go @@ -6,7 +6,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" @@ -17,7 +16,7 @@ const resourceName = "mongodbatlas_custom_dns_configuration_cluster_aws.test" func TestAccConfigRSCustomDNSConfigurationAWS_basic(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -56,7 +55,7 @@ func TestAccConfigRSCustomDNSConfigurationAWS_basic(t *testing.T) { func TestAccConfigRSCustomDNSConfigurationAWS_importBasic(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ diff --git a/internal/service/databaseuser/data_source_database_user_test.go b/internal/service/databaseuser/data_source_database_user_test.go index 8e1ee27d78..dc040afb7b 100644 --- a/internal/service/databaseuser/data_source_database_user_test.go +++ b/internal/service/databaseuser/data_source_database_user_test.go @@ -5,20 +5,20 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "go.mongodb.org/atlas-sdk/v20231115006/admin" ) func TestAccConfigDSDatabaseUser_basic(t *testing.T) { - var dbUser admin.CloudDatabaseUser - - resourceName := "data.mongodbatlas_database_user.test" - orgID := os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName := acctest.RandomWithPrefix("test-acc") - roleName := "atlasAdmin" - username := fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + var ( + dbUser admin.CloudDatabaseUser + resourceName = "data.mongodbatlas_database_user.test" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + roleName = "atlasAdmin" + projectName = acc.RandomProjectName() + username = acc.RandomName() + ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, diff --git a/internal/service/databaseuser/data_source_database_users_test.go b/internal/service/databaseuser/data_source_database_users_test.go index 7977977776..6e4bfa365b 100644 --- a/internal/service/databaseuser/data_source_database_users_test.go +++ b/internal/service/databaseuser/data_source_database_users_test.go @@ -5,18 +5,18 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) func TestAccConfigDSDatabaseUsers_basic(t *testing.T) { - resourceName := "data.mongodbatlas_database_users.test" - orgID := os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName := acctest.RandomWithPrefix("test-acc") - - username := fmt.Sprintf("test-acc-%s", acctest.RandString(10)) - roleName := "atlasAdmin" + var ( + resourceName = "data.mongodbatlas_database_users.test" + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + roleName = "atlasAdmin" + projectName = acc.RandomProjectName() + username = acc.RandomName() + ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, diff --git a/internal/service/databaseuser/resource_database_user_migration_test.go b/internal/service/databaseuser/resource_database_user_migration_test.go index 5f8581536a..65eb35c789 100644 --- a/internal/service/databaseuser/resource_database_user_migration_test.go +++ b/internal/service/databaseuser/resource_database_user_migration_test.go @@ -6,9 +6,7 @@ import ( "go.mongodb.org/atlas-sdk/v20231115006/admin" - "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/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" @@ -17,9 +15,10 @@ import ( func TestAccMigrationConfigRSDatabaseUser_Basic(t *testing.T) { var ( resourceName = "mongodbatlas_database_user.basic_ds" - username = acctest.RandomWithPrefix("dbUser") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + username = acc.RandomName() + config = acc.ConfigDatabaseUserBasic(projectName, orgID, "atlasAdmin", username, "First Key", "First value") ) resource.ParallelTest(t, resource.TestCase{ @@ -27,7 +26,7 @@ func TestAccMigrationConfigRSDatabaseUser_Basic(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: acc.ConfigDatabaseUserBasic(projectName, orgID, "atlasAdmin", username, "First Key", "First value"), + Config: config, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "username", username), @@ -37,16 +36,7 @@ func TestAccMigrationConfigRSDatabaseUser_Basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "roles.#", "1"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: acc.ConfigDatabaseUserBasic(projectName, orgID, "atlasAdmin", username, "First Key", "First value"), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -57,7 +47,8 @@ func TestAccMigrationConfigRSDatabaseUser_withX509TypeCustomer(t *testing.T) { username = "CN=ellen@example.com,OU=users,DC=example,DC=com" x509Type = "CUSTOMER" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + config = acc.ConfigDatabaseUserWithX509Type(projectName, orgID, "atlasAdmin", username, "First Key", "First value", x509Type) ) resource.ParallelTest(t, resource.TestCase{ @@ -65,7 +56,7 @@ func TestAccMigrationConfigRSDatabaseUser_withX509TypeCustomer(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: acc.ConfigDatabaseUserWithX509Type(projectName, orgID, "atlasAdmin", username, "First Key", "First value", x509Type), + Config: config, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "username", username), @@ -74,16 +65,7 @@ func TestAccMigrationConfigRSDatabaseUser_withX509TypeCustomer(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "labels.#", "1"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: acc.ConfigDatabaseUserWithX509Type(projectName, orgID, "atlasAdmin", username, "First Key", "First value", x509Type), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -92,7 +74,8 @@ func TestAccMigrationConfigRSDatabaseUser_withAWSIAMType(t *testing.T) { resourceName = "mongodbatlas_database_user.test" username = "arn:aws:iam::358363220050:user/mongodb-aws-iam-auth-test-user" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + config = acc.ConfigDatabaseUserWithAWSIAMType(projectName, orgID, "atlasAdmin", username, "First Key", "First value") ) resource.ParallelTest(t, resource.TestCase{ @@ -100,7 +83,7 @@ func TestAccMigrationConfigRSDatabaseUser_withAWSIAMType(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: acc.ConfigDatabaseUserWithAWSIAMType(projectName, orgID, "atlasAdmin", username, "First Key", "First value"), + Config: config, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "username", username), @@ -109,16 +92,7 @@ func TestAccMigrationConfigRSDatabaseUser_withAWSIAMType(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "labels.#", "1"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: acc.ConfigDatabaseUserWithAWSIAMType(projectName, orgID, "atlasAdmin", username, "First Key", "First value"), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -127,9 +101,21 @@ func TestAccMigrationConfigRSDatabaseUser_withLabels(t *testing.T) { var ( dbUser admin.CloudDatabaseUser resourceName = "mongodbatlas_database_user.test" - username = acctest.RandomWithPrefix("test-acc") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + username = acc.RandomName() + config = acc.ConfigDatabaseUserWithLabels(projectName, orgID, "atlasAdmin", username, + []admin.ComponentLabel{ + { + Key: conversion.StringPtr("key 1"), + Value: conversion.StringPtr("value 1"), + }, + { + Key: conversion.StringPtr("key 2"), + Value: conversion.StringPtr("value 2"), + }, + }, + ) ) resource.ParallelTest(t, resource.TestCase{ @@ -138,18 +124,7 @@ func TestAccMigrationConfigRSDatabaseUser_withLabels(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: acc.ConfigDatabaseUserWithLabels(projectName, orgID, "atlasAdmin", username, - []admin.ComponentLabel{ - { - Key: conversion.StringPtr("key 1"), - Value: conversion.StringPtr("value 1"), - }, - { - Key: conversion.StringPtr("key 2"), - Value: conversion.StringPtr("value 2"), - }, - }, - ), + Config: config, Check: resource.ComposeTestCheckFunc( acc.CheckDatabaseUserExists(resourceName, &dbUser), acc.CheckDatabaseUserAttributes(&dbUser, username), @@ -160,36 +135,18 @@ func TestAccMigrationConfigRSDatabaseUser_withLabels(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "labels.#", "2"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: acc.ConfigDatabaseUserWithLabels(projectName, orgID, "atlasAdmin", username, - []admin.ComponentLabel{ - { - Key: conversion.StringPtr("key 1"), - Value: conversion.StringPtr("value 1"), - }, - { - Key: conversion.StringPtr("key 2"), - Value: conversion.StringPtr("value 2"), - }, - }, - ), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } + func TestAccMigrationConfigRSDatabaseUser_withEmptyLabels(t *testing.T) { var ( resourceName = "mongodbatlas_database_user.test" - username = acctest.RandomWithPrefix("test-acc") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + username = acc.RandomName() + config = acc.ConfigDatabaseUserWithLabels(projectName, orgID, "atlasAdmin", username, nil) ) resource.ParallelTest(t, resource.TestCase{ @@ -197,7 +154,7 @@ func TestAccMigrationConfigRSDatabaseUser_withEmptyLabels(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: acc.ConfigDatabaseUserWithLabels(projectName, orgID, "atlasAdmin", username, nil), + Config: config, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "username", username), @@ -206,16 +163,7 @@ func TestAccMigrationConfigRSDatabaseUser_withEmptyLabels(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "labels.#", "0"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: acc.ConfigDatabaseUserWithLabels(projectName, orgID, "atlasAdmin", username, nil), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -223,10 +171,24 @@ func TestAccMigrationConfigRSDatabaseUser_withEmptyLabels(t *testing.T) { func TestAccMigrationConfigRSDatabaseUser_withRoles(t *testing.T) { var ( resourceName = "mongodbatlas_database_user.test" - username = acctest.RandomWithPrefix("test-acc-user") - password = acctest.RandomWithPrefix("test-acc-pass") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + username = acc.RandomName() + password = acc.RandomName() + config = acc.ConfigDatabaseUserWithRoles(username, password, projectName, orgID, + []*admin.DatabaseUserRole{ + { + RoleName: "read", + DatabaseName: "admin", + CollectionName: conversion.StringPtr("stir"), + }, + { + RoleName: "read", + DatabaseName: "admin", + CollectionName: conversion.StringPtr("unpledged"), + }, + }, + ) ) resource.ParallelTest(t, resource.TestCase{ @@ -234,20 +196,7 @@ func TestAccMigrationConfigRSDatabaseUser_withRoles(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: acc.ConfigDatabaseUserWithRoles(username, password, projectName, orgID, - []*admin.DatabaseUserRole{ - { - RoleName: "read", - DatabaseName: "admin", - CollectionName: conversion.StringPtr("stir"), - }, - { - RoleName: "read", - DatabaseName: "admin", - CollectionName: conversion.StringPtr("unpledged"), - }, - }, - ), + Config: config, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "username", username), @@ -256,29 +205,7 @@ func TestAccMigrationConfigRSDatabaseUser_withRoles(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "roles.#", "2"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: acc.ConfigDatabaseUserWithRoles(username, password, projectName, orgID, - []*admin.DatabaseUserRole{ - { - RoleName: "read", - DatabaseName: "admin", - CollectionName: conversion.StringPtr("stir"), - }, - { - RoleName: "read", - DatabaseName: "admin", - CollectionName: conversion.StringPtr("unpledged"), - }, - }, - ), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -286,11 +213,19 @@ func TestAccMigrationConfigRSDatabaseUser_withRoles(t *testing.T) { func TestAccMigrationConfigRSDatabaseUser_withScopes(t *testing.T) { var ( resourceName = "mongodbatlas_database_user.test" - username = acctest.RandomWithPrefix("test-acc-user") - password = acctest.RandomWithPrefix("test-acc-pass") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - clusterName = acctest.RandomWithPrefix("test-acc-clu") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + username = acc.RandomName() + password = acc.RandomName() + config = acc.ConfigDatabaseUserWithScopes(username, password, "atlasAdmin", projectName, orgID, + []*admin.UserScope{ + { + Name: clusterName, + Type: "CLUSTER", + }, + }, + ) ) resource.ParallelTest(t, resource.TestCase{ @@ -298,14 +233,7 @@ func TestAccMigrationConfigRSDatabaseUser_withScopes(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: acc.ConfigDatabaseUserWithScopes(username, password, "atlasAdmin", projectName, orgID, - []*admin.UserScope{ - { - Name: clusterName, - Type: "CLUSTER", - }, - }, - ), + Config: config, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "username", username), @@ -316,23 +244,7 @@ func TestAccMigrationConfigRSDatabaseUser_withScopes(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "scopes.0.type", "CLUSTER"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: acc.ConfigDatabaseUserWithScopes(username, password, "atlasAdmin", projectName, orgID, - []*admin.UserScope{ - { - Name: clusterName, - Type: "CLUSTER", - }, - }, - ), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -340,10 +252,11 @@ func TestAccMigrationConfigRSDatabaseUser_withScopes(t *testing.T) { func TestAccMigrationConfigRSDatabaseUser_withEmptyScopes(t *testing.T) { var ( resourceName = "mongodbatlas_database_user.test" - username = acctest.RandomWithPrefix("test-acc-user") - password = acctest.RandomWithPrefix("test-acc-pass") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + username = acc.RandomName() + password = acc.RandomName() + config = acc.ConfigDatabaseUserWithScopes(username, password, "atlasAdmin", projectName, orgID, nil) ) resource.ParallelTest(t, resource.TestCase{ @@ -351,7 +264,7 @@ func TestAccMigrationConfigRSDatabaseUser_withEmptyScopes(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: acc.ConfigDatabaseUserWithScopes(username, password, "atlasAdmin", projectName, orgID, nil), + Config: config, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "username", username), @@ -360,16 +273,7 @@ func TestAccMigrationConfigRSDatabaseUser_withEmptyScopes(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "scopes.#", "0"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: acc.ConfigDatabaseUserWithScopes(username, password, "atlasAdmin", projectName, orgID, nil), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } @@ -379,7 +283,8 @@ func TestAccMigrationConfigRSDatabaseUser_withLDAPAuthType(t *testing.T) { resourceName = "mongodbatlas_database_user.test" username = "CN=david@example.com,OU=users,DC=example,DC=com" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + config = acc.ConfigDatabaseUserWithLDAPAuthType(projectName, orgID, "atlasAdmin", username, "First Key", "First value") ) resource.ParallelTest(t, resource.TestCase{ @@ -387,7 +292,7 @@ func TestAccMigrationConfigRSDatabaseUser_withLDAPAuthType(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: acc.ConfigDatabaseUserWithLDAPAuthType(projectName, orgID, "atlasAdmin", username, "First Key", "First value"), + Config: config, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(resourceName, "project_id"), resource.TestCheckResourceAttr(resourceName, "username", username), @@ -396,16 +301,7 @@ func TestAccMigrationConfigRSDatabaseUser_withLDAPAuthType(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "labels.#", "1"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: acc.ConfigDatabaseUserWithLDAPAuthType(projectName, orgID, "atlasAdmin", username, "First Key", "First value"), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/databaseuser/resource_database_user_test.go b/internal/service/databaseuser/resource_database_user_test.go index 15eb543fc1..7523e2b0c4 100644 --- a/internal/service/databaseuser/resource_database_user_test.go +++ b/internal/service/databaseuser/resource_database_user_test.go @@ -5,7 +5,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -17,9 +16,9 @@ func TestAccConfigRSDatabaseUser_basic(t *testing.T) { var ( dbUser admin.CloudDatabaseUser resourceName = "mongodbatlas_database_user.basic_ds" - username = acctest.RandomWithPrefix("dbUser") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + username = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -70,7 +69,7 @@ func TestAccConfigRSDatabaseUser_withX509TypeCustomer(t *testing.T) { username = "CN=ellen@example.com,OU=users,DC=example,DC=com" x509Type = "CUSTOMER" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -98,10 +97,10 @@ func TestAccConfigRSDatabaseUser_withX509TypeManaged(t *testing.T) { var ( dbUser admin.CloudDatabaseUser resourceName = "mongodbatlas_database_user.test" - username = acctest.RandomWithPrefix("test-acc") x509Type = "MANAGED" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + username = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -131,7 +130,7 @@ func TestAccConfigRSDatabaseUser_withAWSIAMType(t *testing.T) { resourceName = "mongodbatlas_database_user.test" username = "arn:aws:iam::358363220050:user/mongodb-aws-iam-auth-test-user" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -161,7 +160,7 @@ func TestAccConfigRSDatabaseUser_withAWSIAMType_import(t *testing.T) { resourceName = "mongodbatlas_database_user.test" username = os.Getenv("TEST_DB_USER_IAM_ARN") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) if username == "" { @@ -200,9 +199,9 @@ func TestAccConfigRSDatabaseUser_withLabels(t *testing.T) { var ( dbUser admin.CloudDatabaseUser resourceName = "mongodbatlas_database_user.test" - username = acctest.RandomWithPrefix("test-acc") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + username = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -280,10 +279,10 @@ func TestAccConfigRSDatabaseUser_withRoles(t *testing.T) { var ( dbUser admin.CloudDatabaseUser resourceName = "mongodbatlas_database_user.test" - username = acctest.RandomWithPrefix("test-acc-user") - password = acctest.RandomWithPrefix("test-acc-pass") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + username = acc.RandomName() + password = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -345,11 +344,11 @@ func TestAccConfigRSDatabaseUser_withScopes(t *testing.T) { var ( dbUser admin.CloudDatabaseUser resourceName = "mongodbatlas_database_user.test" - username = acctest.RandomWithPrefix("test-acc-user") - password = acctest.RandomWithPrefix("test-acc-pass") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - clusterName = acctest.RandomWithPrefix("test-acc-clu") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + username = acc.RandomName() + password = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -413,11 +412,11 @@ func TestAccConfigRSDatabaseUser_updateToEmptyScopes(t *testing.T) { var ( dbUser admin.CloudDatabaseUser resourceName = "mongodbatlas_database_user.test" - username = acctest.RandomWithPrefix("test-acc-user") - password = acctest.RandomWithPrefix("test-acc-pass") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - clusterName = acctest.RandomWithPrefix("test-acc-clu") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() + username = acc.RandomName() + password = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -472,9 +471,9 @@ func TestAccConfigRSDatabaseUser_updateToEmptyLabels(t *testing.T) { var ( dbUser admin.CloudDatabaseUser resourceName = "mongodbatlas_database_user.test" - username = acctest.RandomWithPrefix("test-acc") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + username = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -523,7 +522,7 @@ func TestAccConfigRSDatabaseUser_withLDAPAuthType(t *testing.T) { resourceName = "mongodbatlas_database_user.test" username = "CN=david@example.com,OU=users,DC=example,DC=com" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -549,10 +548,10 @@ func TestAccConfigRSDatabaseUser_withLDAPAuthType(t *testing.T) { func TestAccConfigRSDatabaseUser_importBasic(t *testing.T) { var ( - username = fmt.Sprintf("test-username-%s", acctest.RandString(5)) resourceName = "mongodbatlas_database_user.basic_ds" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() + username = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -588,7 +587,7 @@ func TestAccConfigRSDatabaseUser_importX509TypeCustomer(t *testing.T) { username = "CN=ellen@example.com,OU=users,DC=example,DC=com" x509Type = "CUSTOMER" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -625,7 +624,7 @@ func TestAccConfigRSDatabaseUser_importLDAPAuthType(t *testing.T) { resourceName = "mongodbatlas_database_user.test" username = "CN=david@example.com,OU=users,DC=example,DC=com" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ diff --git a/internal/service/maintenancewindow/data_source_maintenance_window_test.go b/internal/service/maintenancewindow/data_source_maintenance_window_test.go index 0ba8e19c60..91127f694e 100644 --- a/internal/service/maintenancewindow/data_source_maintenance_window_test.go +++ b/internal/service/maintenancewindow/data_source_maintenance_window_test.go @@ -5,7 +5,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/spf13/cast" @@ -16,7 +15,7 @@ const dataSourceName = "mongodbatlas_maintenance_window.test" func TestAccConfigDSMaintenanceWindow_basic(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() dayOfWeek = 7 hourOfDay = 3 ) diff --git a/internal/service/maintenancewindow/resource_maintenance_window_migration_test.go b/internal/service/maintenancewindow/resource_maintenance_window_migration_test.go index 79a3ba5117..da83e01078 100644 --- a/internal/service/maintenancewindow/resource_maintenance_window_migration_test.go +++ b/internal/service/maintenancewindow/resource_maintenance_window_migration_test.go @@ -4,8 +4,8 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" "github.com/spf13/cast" ) @@ -13,7 +13,7 @@ import ( func TestAccMigrationConfigMaintenanceWindow_basic(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() dayOfWeek = 7 hourOfDay = 3 config = configBasic(orgID, projectName, dayOfWeek, hourOfDay) @@ -33,7 +33,7 @@ func TestAccMigrationConfigMaintenanceWindow_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "number_of_deferrals", "0"), ), }, - mig.TestStep(config), + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/maintenancewindow/resource_maintenance_window_test.go b/internal/service/maintenancewindow/resource_maintenance_window_test.go index c91e98e263..aee2a884af 100644 --- a/internal/service/maintenancewindow/resource_maintenance_window_test.go +++ b/internal/service/maintenancewindow/resource_maintenance_window_test.go @@ -7,7 +7,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" @@ -19,7 +18,7 @@ const resourceName = "mongodbatlas_maintenance_window.test" func TestAccConfigRSMaintenanceWindow_basic(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() dayOfWeek = 7 hourOfDay = 3 dayOfWeekUpdated = 4 @@ -57,7 +56,7 @@ func TestAccConfigRSMaintenanceWindow_basic(t *testing.T) { func TestAccConfigRSMaintenanceWindow_importBasic(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() dayOfWeek = 1 hourOfDay = 3 ) @@ -90,7 +89,7 @@ func TestAccConfigRSMaintenanceWindow_importBasic(t *testing.T) { func TestAccConfigRSMaintenanceWindow_autoDeferActivated(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() dayOfWeek = 7 hourOfDay = 3 ) diff --git a/internal/service/networkcontainer/data_source_network_container_test.go b/internal/service/networkcontainer/data_source_network_container_test.go index a69cb59c10..63d7c11f72 100644 --- a/internal/service/networkcontainer/data_source_network_container_test.go +++ b/internal/service/networkcontainer/data_source_network_container_test.go @@ -4,7 +4,6 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) @@ -15,7 +14,7 @@ var ( func TestAccNetworkContainerDS_basicAWS(t *testing.T) { var ( - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, @@ -36,7 +35,7 @@ func TestAccNetworkContainerDS_basicAWS(t *testing.T) { func TestAccNetworkContainerDS_basicAzure(t *testing.T) { var ( - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, @@ -57,7 +56,7 @@ func TestAccNetworkContainerDS_basicAzure(t *testing.T) { func TestAccNetworkContainerDS_basicGCP(t *testing.T) { var ( - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t) }, diff --git a/internal/service/networkcontainer/data_source_network_containers_test.go b/internal/service/networkcontainer/data_source_network_containers_test.go index 106280e83a..a3e17db385 100644 --- a/internal/service/networkcontainer/data_source_network_containers_test.go +++ b/internal/service/networkcontainer/data_source_network_containers_test.go @@ -4,14 +4,13 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) func TestAccNetworkContainerDSPlural_basicAWS(t *testing.T) { var ( - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t) }, @@ -34,7 +33,7 @@ func TestAccNetworkContainerDSPlural_basicAWS(t *testing.T) { func TestAccNetworkContainerDSPlural_basicAzure(t *testing.T) { var ( - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t) }, @@ -57,7 +56,7 @@ func TestAccNetworkContainerDSPlural_basicAzure(t *testing.T) { func TestAccNetworkContainerDSPlural_basicGCP(t *testing.T) { var ( - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheck(t) }, diff --git a/internal/service/networkcontainer/resource_network_container_migration_test.go b/internal/service/networkcontainer/resource_network_container_migration_test.go index 408a9e006d..00092a53b1 100644 --- a/internal/service/networkcontainer/resource_network_container_migration_test.go +++ b/internal/service/networkcontainer/resource_network_container_migration_test.go @@ -3,7 +3,6 @@ package networkcontainer_test import ( "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" @@ -11,7 +10,7 @@ import ( func TestAccMigrationNetworkContainerRS_basicAWS(t *testing.T) { var ( - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() configAWS = configAWS(projectName, orgID, cidrBlock, providerNameAws, "US_EAST_1") ) @@ -29,14 +28,14 @@ func TestAccMigrationNetworkContainerRS_basicAWS(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "provisioned"), ), }, - mig.TestStep(configAWS), + mig.TestStepCheckEmptyPlan(configAWS), }, }) } func TestAccMigrationNetworkContainerRS_basicAzure(t *testing.T) { var ( - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() configAzure = configAzure(projectName, orgID, cidrBlock, providerNameAzure) ) @@ -54,14 +53,14 @@ func TestAccMigrationNetworkContainerRS_basicAzure(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "provisioned"), ), }, - mig.TestStep(configAzure), + mig.TestStepCheckEmptyPlan(configAzure), }, }) } func TestAccMigrationNetworkContainerRS_basicGCP(t *testing.T) { var ( - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() configGCP = configGCP(projectName, orgID, gcpCidrBlock, providerNameGCP) ) @@ -79,7 +78,7 @@ func TestAccMigrationNetworkContainerRS_basicGCP(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "provisioned"), ), }, - mig.TestStep(configGCP), + mig.TestStepCheckEmptyPlan(configGCP), }, }) } diff --git a/internal/service/networkcontainer/resource_network_container_test.go b/internal/service/networkcontainer/resource_network_container_test.go index 9409ccb933..a4e339b963 100644 --- a/internal/service/networkcontainer/resource_network_container_test.go +++ b/internal/service/networkcontainer/resource_network_container_test.go @@ -29,7 +29,7 @@ func TestAccNetworkContainerRS_basicAWS(t *testing.T) { var ( randIntUpdated = acctest.RandIntRange(0, 255) cidrBlockUpdated = fmt.Sprintf("10.8.%d.0/24", randIntUpdated) - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -63,7 +63,7 @@ func TestAccNetworkContainerRS_basicAzure(t *testing.T) { var ( randIntUpdated = acctest.RandIntRange(0, 255) cidrBlockUpdated = fmt.Sprintf("192.168.%d.0/24", randIntUpdated) - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -97,7 +97,7 @@ func TestAccNetworkContainerRS_basicGCP(t *testing.T) { var ( randIntUpdated = acctest.RandIntRange(0, 255) cidrBlockUpdated = fmt.Sprintf("10.%d.0.0/18", randIntUpdated) - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ @@ -129,7 +129,7 @@ func TestAccNetworkContainerRS_basicGCP(t *testing.T) { func TestAccNetworkContainerRS_WithRegionsGCP(t *testing.T) { var ( - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() gcpWithRegionsCidrBlock = fmt.Sprintf("10.%d.0.0/21", randInt) ) resource.ParallelTest(t, resource.TestCase{ @@ -158,7 +158,7 @@ func TestAccNetworkContainerRS_WithRegionsGCP(t *testing.T) { func TestAccNetworkContainerRS_importBasic(t *testing.T) { var ( - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, diff --git a/internal/service/networkpeering/resource_network_peering_test.go b/internal/service/networkpeering/resource_network_peering_test.go index b26226e8c5..7457a0ff59 100644 --- a/internal/service/networkpeering/resource_network_peering_test.go +++ b/internal/service/networkpeering/resource_network_peering_test.go @@ -8,7 +8,6 @@ import ( "strings" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -28,7 +27,7 @@ func TestAccNetworkNetworkPeering_basicAWS(t *testing.T) { awsAccountID = os.Getenv("AWS_ACCOUNT_ID") awsRegion = os.Getenv("AWS_REGION") providerName = "AWS" - projectName = acctest.RandomWithPrefix("test-acc-project-aws") + projectName = acc.RandomProjectName() ) resource.Test(t, resource.TestCase{ @@ -117,7 +116,7 @@ func TestAccNetworkRSNetworkPeering_basicGCP(t *testing.T) { projectID = os.Getenv("MONGODB_ATLAS_PROJECT_ID") providerName = "GCP" gcpProjectID = os.Getenv("GCP_PROJECT_ID") - networkName = fmt.Sprintf("test-acc-name-%s", acctest.RandString(5)) + networkName = acc.RandomName() ) resource.Test(t, resource.TestCase{ diff --git a/internal/service/onlinearchive/resource_online_archive_migration_test.go b/internal/service/onlinearchive/resource_online_archive_migration_test.go index abd7843c3e..872dee1852 100644 --- a/internal/service/onlinearchive/resource_online_archive_migration_test.go +++ b/internal/service/onlinearchive/resource_online_archive_migration_test.go @@ -1,15 +1,12 @@ package onlinearchive_test import ( - "fmt" "os" "testing" matlas "go.mongodb.org/atlas/mongodbatlas" - "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" @@ -21,13 +18,14 @@ func TestAccMigrationBackupRSOnlineArchiveWithNoChangeBetweenVersions(t *testing resourceName = "mongodbatlas_cluster.online_archive_test" onlineArchiveResourceName = "mongodbatlas_online_archive.users_archive" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() deleteExpirationDays = 0 ) if mig.IsProviderVersionAtLeast("1.12.2") { deleteExpirationDays = 7 } + config := configWithDailySchedule(orgID, projectName, clusterName, 1, deleteExpirationDays) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { mig.PreCheckBasic(t) }, @@ -35,28 +33,19 @@ func TestAccMigrationBackupRSOnlineArchiveWithNoChangeBetweenVersions(t *testing Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: configFirstStep(orgID, projectName, name), + Config: configFirstStep(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( populateWithSampleData(resourceName, &cluster), ), }, { ExternalProviders: mig.ExternalProviders(), - Config: configWithDailySchedule(orgID, projectName, name, 1, deleteExpirationDays), + Config: config, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(onlineArchiveResourceName, "partition_fields.0.field_name", "last_review"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: configWithDailySchedule(orgID, projectName, name, 1, deleteExpirationDays), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/onlinearchive/resource_online_archive_test.go b/internal/service/onlinearchive/resource_online_archive_test.go index cbbc19974e..1a502e7e2d 100644 --- a/internal/service/onlinearchive/resource_online_archive_test.go +++ b/internal/service/onlinearchive/resource_online_archive_test.go @@ -11,7 +11,6 @@ import ( matlas "go.mongodb.org/atlas/mongodbatlas" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -26,8 +25,8 @@ func TestAccBackupRSOnlineArchive(t *testing.T) { onlineArchiveDataSourceName = "data.mongodbatlas_online_archive.read_archive" onlineArchivesDataSourceName = "data.mongodbatlas_online_archives.all" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -38,13 +37,13 @@ func TestAccBackupRSOnlineArchive(t *testing.T) { { // We need this step to pupulate the cluster with Sample Data // The online archive won't work if the cluster does not have data - Config: configFirstStep(orgID, projectName, name), + Config: configFirstStep(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( populateWithSampleData(resourceName, &cluster), ), }, { - Config: configWithDailySchedule(orgID, projectName, name, 1, 7), + Config: configWithDailySchedule(orgID, projectName, clusterName, 1, 7), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "state"), resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "archive_id"), @@ -60,7 +59,7 @@ func TestAccBackupRSOnlineArchive(t *testing.T) { ), }, { - Config: configWithDailySchedule(orgID, projectName, name, 2, 8), + Config: configWithDailySchedule(orgID, projectName, clusterName, 2, 8), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "state"), resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "archive_id"), @@ -76,7 +75,7 @@ func TestAccBackupRSOnlineArchive(t *testing.T) { ), }, { - Config: testAccBackupRSOnlineArchiveConfigWithWeeklySchedule(orgID, projectName, name, 2), + Config: testAccBackupRSOnlineArchiveConfigWithWeeklySchedule(orgID, projectName, clusterName, 2), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "state"), resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "archive_id"), @@ -89,7 +88,7 @@ func TestAccBackupRSOnlineArchive(t *testing.T) { ), }, { - Config: testAccBackupRSOnlineArchiveConfigWithMonthlySchedule(orgID, projectName, name, 2), + Config: testAccBackupRSOnlineArchiveConfigWithMonthlySchedule(orgID, projectName, clusterName, 2), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "state"), resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "archive_id"), @@ -102,7 +101,7 @@ func TestAccBackupRSOnlineArchive(t *testing.T) { ), }, { - Config: configWithoutSchedule(orgID, projectName, name), + Config: configWithoutSchedule(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "state"), resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "archive_id"), @@ -111,7 +110,7 @@ func TestAccBackupRSOnlineArchive(t *testing.T) { ), }, { - Config: configWithoutSchedule(orgID, projectName, name), + Config: configWithoutSchedule(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(onlineArchiveResourceName, "partition_fields.0.field_name", "last_review"), ), @@ -126,8 +125,8 @@ func TestAccBackupRSOnlineArchiveBasic(t *testing.T) { resourceName = "mongodbatlas_cluster.online_archive_test" onlineArchiveResourceName = "mongodbatlas_online_archive.users_archive" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -138,13 +137,13 @@ func TestAccBackupRSOnlineArchiveBasic(t *testing.T) { { // We need this step to pupulate the cluster with Sample Data // The online archive won't work if the cluster does not have data - Config: configFirstStep(orgID, projectName, name), + Config: configFirstStep(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( populateWithSampleData(resourceName, &cluster), ), }, { - Config: configWithoutSchedule(orgID, projectName, name), + Config: configWithoutSchedule(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "state"), resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "archive_id"), @@ -152,7 +151,7 @@ func TestAccBackupRSOnlineArchiveBasic(t *testing.T) { ), }, { - Config: configWithDailySchedule(orgID, projectName, name, 1, 1), + Config: configWithDailySchedule(orgID, projectName, clusterName, 1, 1), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "state"), resource.TestCheckResourceAttrSet(onlineArchiveResourceName, "archive_id"), @@ -175,8 +174,8 @@ func TestAccBackupRSOnlineArchiveWithProcessRegion(t *testing.T) { onlineArchiveResourceName = "mongodbatlas_online_archive.users_archive" onlineArchiveDataSourceName = "data.mongodbatlas_online_archive.read_archive" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() cloudProvider = "AWS" processRegion = "US_EAST_1" ) @@ -189,13 +188,13 @@ func TestAccBackupRSOnlineArchiveWithProcessRegion(t *testing.T) { { // We need this step to pupulate the cluster with Sample Data // The online archive won't work if the cluster does not have data - Config: configFirstStep(orgID, projectName, name), + Config: configFirstStep(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( populateWithSampleData(resourceName, &cluster), ), }, { - Config: configWithDataProcessRegion(orgID, projectName, name, cloudProvider, processRegion), + Config: configWithDataProcessRegion(orgID, projectName, clusterName, cloudProvider, processRegion), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(onlineArchiveResourceName, "data_process_region.0.cloud_provider", cloudProvider), resource.TestCheckResourceAttr(onlineArchiveResourceName, "data_process_region.0.region", processRegion), @@ -204,11 +203,11 @@ func TestAccBackupRSOnlineArchiveWithProcessRegion(t *testing.T) { ), }, { - Config: configWithDataProcessRegion(orgID, projectName, name, cloudProvider, "AP_SOUTH_1"), + Config: configWithDataProcessRegion(orgID, projectName, clusterName, cloudProvider, "AP_SOUTH_1"), ExpectError: regexp.MustCompile("data_process_region can't be modified"), }, { - Config: configWithoutSchedule(orgID, projectName, name), + Config: configWithoutSchedule(orgID, projectName, clusterName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(onlineArchiveResourceName, "data_process_region.0.cloud_provider", cloudProvider), resource.TestCheckResourceAttr(onlineArchiveResourceName, "data_process_region.0.region", processRegion), @@ -221,8 +220,8 @@ func TestAccBackupRSOnlineArchiveWithProcessRegion(t *testing.T) { func TestAccBackupRSOnlineArchiveInvalidProcessRegion(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() cloudProvider = "AWS" ) @@ -232,7 +231,7 @@ func TestAccBackupRSOnlineArchiveInvalidProcessRegion(t *testing.T) { CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ { - Config: configWithDataProcessRegion(orgID, projectName, name, cloudProvider, "UNKNOWN"), + Config: configWithDataProcessRegion(orgID, projectName, clusterName, cloudProvider, "UNKNOWN"), ExpectError: regexp.MustCompile("INVALID_ATTRIBUTE"), }, }, @@ -491,7 +490,7 @@ func configFirstStep(orgID, projectName, clusterName string) string { } labels { key = "Owner" - value = "acctest" + value = "test" } } diff --git a/internal/service/orginvitation/resource_org_invitation_migration_test.go b/internal/service/orginvitation/resource_org_invitation_migration_test.go index 18fa2444d8..4adfdbdda8 100644 --- a/internal/service/orginvitation/resource_org_invitation_migration_test.go +++ b/internal/service/orginvitation/resource_org_invitation_migration_test.go @@ -7,7 +7,6 @@ import ( "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" ) @@ -18,6 +17,7 @@ func TestAccMigrationConfigOrgInvitation_basic(t *testing.T) { orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") name = fmt.Sprintf("test-acc-%s@mongodb.com", acctest.RandString(10)) roles = []string{"ORG_GROUP_CREATOR", "ORG_BILLING_ADMIN"} + config = configBasic(orgID, name, roles) ) resource.ParallelTest(t, resource.TestCase{ @@ -26,7 +26,7 @@ func TestAccMigrationConfigOrgInvitation_basic(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: configBasic(orgID, name, roles), + Config: config, Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "invitation_id"), @@ -37,16 +37,7 @@ func TestAccMigrationConfigOrgInvitation_basic(t *testing.T) { resource.TestCheckTypeSetElemAttr(resourceName, "roles.*", roles[1]), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: configBasic(orgID, name, roles), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode_test.go b/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode_test.go index df38ec2ddc..47166e0ab9 100644 --- a/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode_test.go +++ b/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode_test.go @@ -8,7 +8,6 @@ import ( "strings" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" @@ -20,18 +19,15 @@ func TestAccNetworkRSPrivateEndpointRegionalMode_conn(t *testing.T) { endpointResourceSuffix = "atlasple" resourceSuffix = "atlasrm" resourceName = fmt.Sprintf("mongodbatlas_private_endpoint_regional_mode.%s", resourceSuffix) - - awsAccessKey = os.Getenv("AWS_ACCESS_KEY_ID") - awsSecretKey = os.Getenv("AWS_SECRET_ACCESS_KEY") - - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectID = os.Getenv("MONGODB_ATLAS_PROJECT_ID") - projectName = acctest.RandomWithPrefix("test-acc") - providerName = "AWS" - region = os.Getenv("AWS_REGION") - - clusterName = fmt.Sprintf("test-acc-global-%s", acctest.RandString(10)) - clusterResourceName = "global_cluster" + awsAccessKey = os.Getenv("AWS_ACCESS_KEY_ID") + awsSecretKey = os.Getenv("AWS_SECRET_ACCESS_KEY") + orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") + projectID = os.Getenv("MONGODB_ATLAS_PROJECT_ID") + projectName = acc.RandomProjectName() + providerName = "AWS" + region = os.Getenv("AWS_REGION") + clusterName = acc.RandomClusterName() + clusterResourceName = "global_cluster" ) clusterResource := acc.ConfigClusterGlobal(clusterResourceName, orgID, projectName, clusterName, "false") diff --git a/internal/service/privatelinkendpoint/resource_privatelink_endpoint_migration_test.go b/internal/service/privatelinkendpoint/resource_privatelink_endpoint_migration_test.go index 6c00f49847..9d61d99f1b 100644 --- a/internal/service/privatelinkendpoint/resource_privatelink_endpoint_migration_test.go +++ b/internal/service/privatelinkendpoint/resource_privatelink_endpoint_migration_test.go @@ -4,9 +4,7 @@ import ( "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" ) @@ -15,9 +13,10 @@ func TestAccMigrationNetworkPrivateLinkEndpoint_basic(t *testing.T) { var ( resourceName = "mongodbatlas_privatelink_endpoint.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() region = "us-east-1" providerName = "AWS" + config = configBasic(orgID, projectName, providerName, region) ) resource.ParallelTest(t, resource.TestCase{ @@ -26,7 +25,7 @@ func TestAccMigrationNetworkPrivateLinkEndpoint_basic(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: configBasic(orgID, projectName, providerName, region), + Config: config, Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "project_id"), @@ -34,16 +33,7 @@ func TestAccMigrationNetworkPrivateLinkEndpoint_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "region", region), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: configBasic(orgID, projectName, providerName, region), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/privatelinkendpoint/resource_privatelink_endpoint_test.go b/internal/service/privatelinkendpoint/resource_privatelink_endpoint_test.go index efdf7be7e9..9d8b387645 100644 --- a/internal/service/privatelinkendpoint/resource_privatelink_endpoint_test.go +++ b/internal/service/privatelinkendpoint/resource_privatelink_endpoint_test.go @@ -6,7 +6,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -17,7 +16,7 @@ func TestAccNetworkRSPrivateLinkEndpointAWS_basic(t *testing.T) { var ( resourceName = "mongodbatlas_privatelink_endpoint.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() region = "us-east-1" providerName = "AWS" ) @@ -46,7 +45,7 @@ func TestAccNetworkRSPrivateLinkEndpointAWS_import(t *testing.T) { var ( resourceName = "mongodbatlas_privatelink_endpoint.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() region = "us-east-1" providerName = "AWS" ) @@ -80,7 +79,7 @@ func TestAccNetworkRSPrivateLinkEndpointAzure_basic(t *testing.T) { var ( resourceName = "mongodbatlas_privatelink_endpoint.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() region = "US_EAST_2" providerName = "AZURE" ) @@ -109,7 +108,7 @@ func TestAccNetworkRSPrivateLinkEndpointAzure_import(t *testing.T) { var ( resourceName = "mongodbatlas_privatelink_endpoint.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() region = "US_EAST_2" providerName = "AZURE" ) @@ -144,7 +143,7 @@ func TestAccNetworkRSPrivateLinkEndpointGCP_basic(t *testing.T) { var ( resourceName = "mongodbatlas_privatelink_endpoint.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() region = "us-central1" providerName = "GCP" ) diff --git a/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless_migration_test.go b/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless_migration_test.go index f310fbc0d8..f79b0a9cc2 100644 --- a/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless_migration_test.go +++ b/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless_migration_test.go @@ -4,9 +4,7 @@ import ( "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" ) @@ -15,8 +13,9 @@ func TestAccMigrationServerlessPrivateLinkEndpoint_basic(t *testing.T) { var ( resourceName = "mongodbatlas_privatelink_endpoint_serverless.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-serverless") - instanceName = "serverlessplink" + projectName = acc.RandomProjectName() + instanceName = acc.RandomClusterName() + config = configBasic(orgID, projectName, instanceName, true) ) resource.Test(t, resource.TestCase{ @@ -25,22 +24,13 @@ func TestAccMigrationServerlessPrivateLinkEndpoint_basic(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: configBasic(orgID, projectName, instanceName, true), + Config: config, Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttr(resourceName, "instance_name", instanceName), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: configBasic(orgID, projectName, instanceName, true), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless_test.go b/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless_test.go index 6039d8e752..305ecd7000 100644 --- a/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless_test.go +++ b/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless_test.go @@ -6,7 +6,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -17,8 +16,8 @@ func TestAccServerlessPrivateLinkEndpoint_basic(t *testing.T) { var ( resourceName = "mongodbatlas_privatelink_endpoint_serverless.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-serverless") - instanceName = "serverlessplink" + projectName = acc.RandomProjectName() + instanceName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ @@ -41,8 +40,8 @@ func TestAccServerlessPrivateLinkEndpoint_importBasic(t *testing.T) { var ( resourceName = "mongodbatlas_privatelink_endpoint_serverless.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-serverless") - instanceName = "serverlessimport" + projectName = acc.RandomProjectName() + instanceName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, diff --git a/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless_migration_test.go b/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless_migration_test.go index 0c6c259e02..0379000fd3 100644 --- a/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless_migration_test.go +++ b/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless_migration_test.go @@ -4,8 +4,8 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" ) @@ -14,8 +14,8 @@ func TestAccMigrationServerlessPrivateLinkEndpointService_basic(t *testing.T) { resourceName = "mongodbatlas_privatelink_endpoint_service_serverless.test" datasourceName = "data.mongodbatlas_privatelink_endpoint_service_serverless.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-serverless") - instanceName = acctest.RandomWithPrefix("test-acc-serverless") + projectName = acc.RandomProjectName() + instanceName = acc.RandomClusterName() commentOrigin = "this is a comment for serverless private link endpoint" config = configBasic(orgID, projectName, instanceName, commentOrigin) ) @@ -34,7 +34,7 @@ func TestAccMigrationServerlessPrivateLinkEndpointService_basic(t *testing.T) { resource.TestCheckResourceAttr(datasourceName, "comment", commentOrigin), ), }, - mig.TestStep(config), + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless_test.go b/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless_test.go index 8c37490620..c28188ec62 100644 --- a/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless_test.go +++ b/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless_test.go @@ -6,7 +6,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -19,8 +18,8 @@ func TestAccServerlessPrivateLinkEndpointService_basic(t *testing.T) { datasourceName = "data.mongodbatlas_privatelink_endpoint_service_serverless.test" datasourceEndpointsName = "data.mongodbatlas_privatelink_endpoints_service_serverless.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-serverless") - instanceName = acctest.RandomWithPrefix("test-acc-serverless") + projectName = acc.RandomProjectName() + instanceName = acc.RandomClusterName() commentOrigin = "this is a comment for serverless private link endpoint" ) @@ -49,8 +48,8 @@ func TestAccServerlessPrivateLinkEndpointService_importBasic(t *testing.T) { var ( resourceName = "mongodbatlas_privatelink_endpoint_service_serverless.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-serverless") - instanceName = acctest.RandomWithPrefix("test-acc-serverless") + projectName = acc.RandomProjectName() + instanceName = acc.RandomClusterName() commentOrigin = "this is a comment for serverless private link endpoint" ) resource.ParallelTest(t, resource.TestCase{ diff --git a/internal/service/projectapikey/resource_project_api_key_migration_test.go b/internal/service/projectapikey/resource_project_api_key_migration_test.go index c7c650e8a4..78b901dfc4 100644 --- a/internal/service/projectapikey/resource_project_api_key_migration_test.go +++ b/internal/service/projectapikey/resource_project_api_key_migration_test.go @@ -1,11 +1,9 @@ package projectapikey_test import ( - "fmt" "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) @@ -14,8 +12,8 @@ func TestAccMigrationConfigRSProjectAPIKey_RemovingOptionalRootProjectID(t *test var ( resourceName = "mongodbatlas_project_api_key.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - description = fmt.Sprintf("test-acc-project-api_key-%s", acctest.RandString(5)) + projectName = acc.RandomProjectName() + description = acc.RandomName() roleName = "GROUP_OWNER" ) diff --git a/internal/service/projectapikey/resource_project_api_key_test.go b/internal/service/projectapikey/resource_project_api_key_test.go index 5cfc72e412..e29a7d7033 100644 --- a/internal/service/projectapikey/resource_project_api_key_test.go +++ b/internal/service/projectapikey/resource_project_api_key_test.go @@ -20,8 +20,8 @@ func TestAccConfigRSProjectAPIKey_Basic(t *testing.T) { var ( resourceName = "mongodbatlas_project_api_key.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - description = fmt.Sprintf("test-acc-project-api_key-%s", acctest.RandString(5)) + projectName = acc.RandomProjectName() + description = acc.RandomName() roleName = "GROUP_OWNER" ) @@ -46,8 +46,8 @@ func TestAccConfigRSProjectAPIKey_BasicWithLegacyRootProjectID(t *testing.T) { var ( resourceName = "mongodbatlas_project_api_key.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - description = fmt.Sprintf("test-acc-project-api_key-%s", acctest.RandString(5)) + projectName = acc.RandomProjectName() + description = acc.RandomName() roleName = "GROUP_OWNER" ) @@ -73,9 +73,9 @@ func TestAccConfigRSProjectAPIKey_ChangingSingleProject(t *testing.T) { var ( resourceName = "mongodbatlas_project_api_key.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName1 = acctest.RandomWithPrefix("test-acc") - projectName2 = acctest.RandomWithPrefix("test-acc") - description = fmt.Sprintf("test-acc-project-api_key-%s", acctest.RandString(5)) + projectName1 = acc.RandomProjectName() + projectName2 = acc.RandomProjectName() + description = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -107,8 +107,8 @@ func TestAccConfigRSProjectAPIKey_RemovingOptionalRootProjectID(t *testing.T) { var ( resourceName = "mongodbatlas_project_api_key.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - description = fmt.Sprintf("test-acc-project-api_key-%s", acctest.RandString(5)) + projectName = acc.RandomProjectName() + description = acc.RandomName() roleName = "GROUP_OWNER" ) @@ -144,8 +144,8 @@ func TestAccConfigRSProjectAPIKey_Multiple(t *testing.T) { dataSourceName = "data.mongodbatlas_project_api_key.test" dataSourcesName = "data.mongodbatlas_project_api_keys.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - description = fmt.Sprintf("test-acc-project-api_key-%s", acctest.RandString(5)) + projectName = acc.RandomProjectName() + description = acc.RandomName() roleName = "GROUP_OWNER" ) @@ -177,9 +177,9 @@ func TestAccConfigRSProjectAPIKey_UpdateDescription(t *testing.T) { var ( resourceName = "mongodbatlas_project_api_key.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - description = fmt.Sprintf("test-acc-project-api_key-%s", acctest.RandString(5)) - updatedDescription = fmt.Sprintf("test-acc-project-api_key-updated-%s", acctest.RandString(5)) + projectName = acc.RandomProjectName() + description = acc.RandomName() + updatedDescription = acc.RandomName() roleName = "GROUP_OWNER" ) @@ -210,8 +210,8 @@ func TestAccConfigRSProjectAPIKey_importBasic(t *testing.T) { var ( resourceName = "mongodbatlas_project_api_key.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - description = fmt.Sprintf("test-acc-import-project-api_key-%s", acctest.RandString(5)) + projectName = acc.RandomProjectName() + description = acc.RandomName() roleName = "GROUP_OWNER" ) @@ -274,9 +274,9 @@ func TestAccConfigRSProjectAPIKey_DeleteProjectAndAssignment(t *testing.T) { var ( resourceName = "mongodbatlas_project_api_key.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") - secondProjectName = acctest.RandomWithPrefix("test-acc") - description = fmt.Sprintf("%s-%s", "test-acc-project", acctest.RandString(5)) + projectName = acc.RandomProjectName() + secondProjectName = acc.RandomProjectName() + description = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -338,7 +338,7 @@ func testAccCheckMongoDBAtlasProjectAPIKeyDestroy(s *terraform.State) error { func TestAccConfigRSProjectAPIKey_Invalid_Role(t *testing.T) { var ( orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc") + projectName = acc.RandomProjectName() description = projectName roleName = "INVALID_ROLE" ) diff --git a/internal/service/searchdeployment/resource_search_deployment_migration_test.go b/internal/service/searchdeployment/resource_search_deployment_migration_test.go index 3fba86d30a..0835b769d3 100644 --- a/internal/service/searchdeployment/resource_search_deployment_migration_test.go +++ b/internal/service/searchdeployment/resource_search_deployment_migration_test.go @@ -4,9 +4,7 @@ import ( "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" ) @@ -15,10 +13,11 @@ func TestAccMigrationSearchDeployment_basic(t *testing.T) { var ( resourceName = "mongodbatlas_search_deployment.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-search-dep") - clusterName = acctest.RandomWithPrefix("test-acc-search-dep") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() instanceSize = "S30_HIGHCPU_NVME" searchNodeCount = 3 + config = configBasic(orgID, projectName, clusterName, instanceSize, searchNodeCount) ) mig.SkipIfVersionBelow(t, "1.13.0") resource.ParallelTest(t, resource.TestCase{ @@ -27,18 +26,10 @@ func TestAccMigrationSearchDeployment_basic(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: configBasic(orgID, projectName, clusterName, instanceSize, searchNodeCount), + Config: config, Check: resource.ComposeTestCheckFunc(searchNodeChecks(resourceName, clusterName, instanceSize, searchNodeCount)...), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: configBasic(orgID, projectName, clusterName, instanceSize, searchNodeCount), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/searchdeployment/resource_search_deployment_test.go b/internal/service/searchdeployment/resource_search_deployment_test.go index 747e37b602..c6538a2b7e 100644 --- a/internal/service/searchdeployment/resource_search_deployment_test.go +++ b/internal/service/searchdeployment/resource_search_deployment_test.go @@ -6,7 +6,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" @@ -16,8 +15,8 @@ func TestAccSearchDeployment_basic(t *testing.T) { var ( resourceName = "mongodbatlas_search_deployment.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-search-dep") - clusterName = acctest.RandomWithPrefix("test-acc-search-dep") + projectName = acc.RandomProjectName() + clusterName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, diff --git a/internal/service/serverlessinstance/resource_serverless_instance_migration_test.go b/internal/service/serverlessinstance/resource_serverless_instance_migration_test.go index 2c134ba6ce..812c1ee62f 100644 --- a/internal/service/serverlessinstance/resource_serverless_instance_migration_test.go +++ b/internal/service/serverlessinstance/resource_serverless_instance_migration_test.go @@ -4,7 +4,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" @@ -12,9 +11,9 @@ import ( func TestAccMigrationServerlessInstance_basic(t *testing.T) { var ( - instanceName = acctest.RandomWithPrefix("test-acc-serverless") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-serverless") + projectName = acc.RandomProjectName() + instanceName = acc.RandomClusterName() config = acc.ConfigServerlessInstanceBasic(orgID, projectName, instanceName, true) ) resource.ParallelTest(t, resource.TestCase{ @@ -31,7 +30,7 @@ func TestAccMigrationServerlessInstance_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "termination_protection_enabled", "false"), ), }, - mig.TestStep(config), + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/serverlessinstance/resource_serverless_instance_test.go b/internal/service/serverlessinstance/resource_serverless_instance_test.go index 23f832192e..5a534c6074 100644 --- a/internal/service/serverlessinstance/resource_serverless_instance_test.go +++ b/internal/service/serverlessinstance/resource_serverless_instance_test.go @@ -6,7 +6,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -22,9 +21,9 @@ const ( func TestAccServerlessInstance_basic(t *testing.T) { var ( - instanceName = acctest.RandomWithPrefix("test-acc-serverless") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-serverless") + projectName = acc.RandomProjectName() + instanceName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, @@ -60,9 +59,9 @@ func TestAccServerlessInstance_basic(t *testing.T) { func TestAccServerlessInstance_WithTags(t *testing.T) { var ( - instanceName = acctest.RandomWithPrefix("test-acc-serverless") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-serverless") + projectName = acc.RandomProjectName() + instanceName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, @@ -130,9 +129,9 @@ func TestAccServerlessInstance_WithTags(t *testing.T) { func TestAccServerlessInstance_importBasic(t *testing.T) { var ( - instanceName = acctest.RandomWithPrefix("test-acc-serverless") orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acctest.RandomWithPrefix("test-acc-serverless") + projectName = acc.RandomProjectName() + instanceName = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ diff --git a/internal/service/teams/data_source_teams_test.go b/internal/service/teams/data_source_teams_test.go index 26770b527b..f46381a0c8 100644 --- a/internal/service/teams/data_source_teams_test.go +++ b/internal/service/teams/data_source_teams_test.go @@ -5,7 +5,6 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) @@ -14,8 +13,8 @@ func TestAccConfigDSTeam_basic(t *testing.T) { var ( dataSourceName = "data.mongodbatlas_teams.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) username = os.Getenv("MONGODB_ATLAS_USERNAME") + name = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -40,8 +39,8 @@ func TestAccConfigDSTeamByName_basic(t *testing.T) { var ( dataSourceName = "data.mongodbatlas_teams.test2" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) username = os.Getenv("MONGODB_ATLAS_USERNAME") + name = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ diff --git a/internal/service/teams/resource_teams_migration_test.go b/internal/service/teams/resource_teams_migration_test.go index 63611de06f..e5707e2809 100644 --- a/internal/service/teams/resource_teams_migration_test.go +++ b/internal/service/teams/resource_teams_migration_test.go @@ -1,13 +1,10 @@ package teams_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" ) @@ -16,8 +13,9 @@ func TestAccMigrationConfigTeams_basic(t *testing.T) { var ( resourceName = "mongodbatlas_teams.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) username = os.Getenv("MONGODB_ATLAS_USERNAME") + name = acc.RandomName() + config = configBasic(orgID, name, []string{username}) ) resource.Test(t, resource.TestCase{ @@ -26,7 +24,7 @@ func TestAccMigrationConfigTeams_basic(t *testing.T) { Steps: []resource.TestStep{ { ExternalProviders: mig.ExternalProviders(), - Config: configBasic(orgID, name, []string{username}), + Config: config, Check: resource.ComposeTestCheckFunc( checkExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "org_id"), @@ -34,16 +32,7 @@ func TestAccMigrationConfigTeams_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "usernames.#", "1"), ), }, - { - ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, - Config: configBasic(orgID, name, []string{username}), - ConfigPlanChecks: resource.ConfigPlanChecks{ - PreApply: []plancheck.PlanCheck{ - acc.DebugPlan(), - plancheck.ExpectEmptyPlan(), - }, - }, - }, + mig.TestStepCheckEmptyPlan(config), }, }) } diff --git a/internal/service/teams/resource_teams_test.go b/internal/service/teams/resource_teams_test.go index 85160360f2..f8abe55705 100644 --- a/internal/service/teams/resource_teams_test.go +++ b/internal/service/teams/resource_teams_test.go @@ -8,7 +8,6 @@ import ( "strings" "testing" - "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" @@ -19,9 +18,9 @@ func TestAccConfigRSTeam_basic(t *testing.T) { var ( resourceName = "mongodbatlas_teams.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) - updatedName = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) usernames = []string{os.Getenv("MONGODB_ATLAS_USERNAME")} + name = acc.RandomName() + updatedName = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -65,7 +64,7 @@ func TestAccConfigRSTeam_importBasic(t *testing.T) { resourceName = "mongodbatlas_teams.test" orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") username = os.Getenv("MONGODB_ATLAS_USERNAME") - name = fmt.Sprintf("test-acc-%s", acctest.RandString(10)) + name = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ From 6732903e61bddaeb30ba086a2479e269f15a5214 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Tue, 20 Feb 2024 18:19:14 +0100 Subject: [PATCH 51/52] revert acc and mig config --- .github/workflows/acceptance-tests-runner.yml | 12 ++++++------ .github/workflows/migration-tests.yml | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.github/workflows/acceptance-tests-runner.yml b/.github/workflows/acceptance-tests-runner.yml index ab4d26a6e7..938780945f 100644 --- a/.github/workflows/acceptance-tests-runner.yml +++ b/.github/workflows/acceptance-tests-runner.yml @@ -123,15 +123,15 @@ jobs: outputs: cluster_outage_simulation: ${{ steps.filter.outputs.cluster_outage_simulation == 'true' || env.mustTrigger == 'true' }} advanced_cluster: ${{ steps.filter.outputs.advanced_cluster == 'true' || env.mustTrigger == 'true' }} - cluster: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE - search_deployment: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + cluster: ${{ steps.filter.outputs.cluster == 'true' || env.mustTrigger == 'true' }} + search_deployment: ${{ steps.filter.outputs.search_deployment == 'true' || env.mustTrigger == 'true' }} stream: ${{ steps.filter.outputs.stream == 'true' || env.mustTrigger == 'true' }} generic: ${{ steps.filter.outputs.generic == 'true' || env.mustTrigger == 'true' }} - backup: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + backup: ${{ steps.filter.outputs.backup == 'true' || env.mustTrigger == 'true' }} project: ${{ steps.filter.outputs.project == 'true' || env.mustTrigger == 'true' }} - serverless: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE - network: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE - config: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} + network: ${{ steps.filter.outputs.network == 'true' || env.mustTrigger == 'true' }} + config: ${{ steps.filter.outputs.config == 'true' || env.mustTrigger == 'true' }} assume_role: ${{ steps.filter.outputs.assume_role == 'true' || env.mustTrigger == 'true' }} event_trigger: ${{ steps.filter.outputs.event_trigger == 'true' || env.mustTrigger == 'true' }} search_index: ${{ steps.filter.outputs.search_index == 'true' || env.mustTrigger == 'true' }} diff --git a/.github/workflows/migration-tests.yml b/.github/workflows/migration-tests.yml index 743594fc31..a93b4ed873 100644 --- a/.github/workflows/migration-tests.yml +++ b/.github/workflows/migration-tests.yml @@ -55,19 +55,19 @@ jobs: mustTrigger: ${{ github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.test_group == '') }} outputs: project: ${{ steps.filter.outputs.project == 'true' || env.mustTrigger == 'true' }} - config: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + config: ${{ steps.filter.outputs.config == 'true' || env.mustTrigger == 'true' }} advanced_cluster: ${{ steps.filter.outputs.advanced_cluster == 'true' || env.mustTrigger == 'true' }} - backup: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + backup: ${{ steps.filter.outputs.backup == 'true' || env.mustTrigger == 'true' }} stream: ${{ steps.filter.outputs.stream == 'true' || env.mustTrigger == 'true' }} federated: ${{ steps.filter.outputs.federated == 'true' || env.mustTrigger == 'true' }} - search_deployment: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + search_deployment: ${{ steps.filter.outputs.search_deployment == 'true' || env.mustTrigger == 'true' }} generic: ${{ steps.filter.outputs.generic == 'true' || env.mustTrigger == 'true' }} - network: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + network: ${{ steps.filter.outputs.network == 'true' || env.mustTrigger == 'true' }} encryption: ${{ steps.filter.outputs.encryption == 'true' || env.mustTrigger == 'true' }} - serverless: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} data_lake: ${{ steps.filter.outputs.data_lake == 'true' || env.mustTrigger == 'true' }} cluster_outage_simulation: ${{ steps.filter.outputs.cluster_outage_simulation == 'true' || env.mustTrigger == 'true' }} - cluster: false # TEMPORARY, WILL BE REVERTED BEFORE MERGE + cluster: ${{ steps.filter.outputs.cluster == 'true' || env.mustTrigger == 'true' }} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 - uses: dorny/paths-filter@0bc4621a3135347011ad047f9ecf449bf72ce2bd From 5db5eeec413d76018a13e24c98220b3132193b0a Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Tue, 20 Feb 2024 19:58:11 +0100 Subject: [PATCH 52/52] fix test --- internal/service/cluster/resource_cluster_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/cluster/resource_cluster_test.go b/internal/service/cluster/resource_cluster_test.go index 7562187647..d890a9aeab 100644 --- a/internal/service/cluster/resource_cluster_test.go +++ b/internal/service/cluster/resource_cluster_test.go @@ -1430,8 +1430,8 @@ func TestAccClusterRSCluster_RegionsConfig(t *testing.T) { // necessarily match the one used to insert the configuration in the .tf file. // In fact, the num_shards field is used in the custom hash algorithm hence it affects the ordering. // https://github.com/mongodb/terraform-provider-mongodbatlas/blob/059cd565e7aafd59eb8be30bbc9372b56ce2ffa4/internal/service/cluster/resource_cluster.go#L274 - resource.TestCheckResourceAttr(resourceName, "replication_specs.0.num_shards", "1"), - resource.TestCheckResourceAttr(resourceName, "replication_specs.1.num_shards", "2"), + resource.TestCheckResourceAttr(resourceName, "replication_specs.0.num_shards", "2"), + resource.TestCheckResourceAttr(resourceName, "replication_specs.1.num_shards", "1"), ), }, },