From 21c8fb85cddb6c0d72062edf1cb83d09cb3a8f34 Mon Sep 17 00:00:00 2001 From: Zuhair Ahmed Date: Sat, 19 Oct 2024 13:24:30 -0400 Subject: [PATCH 01/35] doc: Advanced Cluster Differences and TF Core Upgrades (#2633) * adv cluster differences doc updates * Update docs/index.md * Update index.md * Update advanced_cluster.md * Update advanced_cluster.md * Update advanced_cluster.md * Update cluster.md * Update docs/index.md Co-authored-by: maastha <122359335+maastha@users.noreply.github.com> * Update docs/resources/cluster.md Co-authored-by: maastha <122359335+maastha@users.noreply.github.com> * Update docs/resources/cluster.md Co-authored-by: Melissa Plunkett * Update advanced_cluster.md * Update cluster-to-advanced-cluster-migration-guide.md --------- Co-authored-by: maastha <122359335+maastha@users.noreply.github.com> Co-authored-by: Melissa Plunkett --- docs/guides/cluster-to-advanced-cluster-migration-guide.md | 2 ++ docs/index.md | 2 ++ docs/resources/advanced_cluster.md | 2 +- docs/resources/cluster.md | 3 +-- 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/guides/cluster-to-advanced-cluster-migration-guide.md b/docs/guides/cluster-to-advanced-cluster-migration-guide.md index ccade2d6dc..3f04a41f0a 100644 --- a/docs/guides/cluster-to-advanced-cluster-migration-guide.md +++ b/docs/guides/cluster-to-advanced-cluster-migration-guide.md @@ -6,6 +6,8 @@ page_title: "Migration Guide: Cluster to Advanced Cluster" **Objective**: This guide explains how to replace the `mongodbatlas_cluster` resource with the `mongodbatlas_advanced_cluster` resource. The data source(s) migration only requires [output changes](#output-changes) as data sources only read clusters. +**Note**: In addition to below options, we are also actively exploring additional migration paths that do not involve Terraform State modifications. If interested to learn more or to test out directly please contact zuhair.ahmed@mongodb.com. + ## Main Changes Between `mongodbatlas_cluster` and `mongodbatlas_advanced_cluster` 1. Replication Spec Configuration: Supports different node types (electable, analytics, read_only) where hardware configuration can differ between node types. diff --git a/docs/index.md b/docs/index.md index 9a756001c8..9000ef48ba 100644 --- a/docs/index.md +++ b/docs/index.md @@ -8,6 +8,8 @@ Use the navigation to the left to read about the available provider resources an You may want to consider pinning the [provider version](https://www.terraform.io/docs/configuration/providers.html#provider-versions) to ensure you have a chance to review and prepare for changes. Speaking of changes, see [CHANGELOG](https://github.com/mongodb/terraform-provider-mongodbatlas/blob/master/CHANGELOG.md) for current version information. +For the best experience, we recommend using the latest [HashiCorp Terraform Core Version](https://github.com/hashicorp/terraform). For more details see [HashiCorp Terraform Version Compatibility Matrix](https://registry.terraform.io/providers/mongodb/mongodbatlas/latest/docs#hashicorp-terraform-versionhttpswwwterraformiodownloadshtml-compatibility-matrix). + ## Example Usage ```terraform diff --git a/docs/resources/advanced_cluster.md b/docs/resources/advanced_cluster.md index 0166a8229a..3b209860b2 100644 --- a/docs/resources/advanced_cluster.md +++ b/docs/resources/advanced_cluster.md @@ -4,7 +4,7 @@ More information on considerations for using advanced clusters please see [Considerations](https://docs.atlas.mongodb.com/reference/api/cluster-advanced/create-one-cluster-advanced/#considerations) -~> **IMPORTANT:** The primary difference between [`mongodbatlas_cluster`](cluster) and [`mongodbatlas_advanced_cluster`](advanced_cluster) is that `mongodbatlas_advanced_cluster` supports multi-cloud clusters. We recommend new users start with the `mongodbatlas_advanced_cluster` resource. +~> **IMPORTANT:** We recommend all new MongoDB Atlas Terraform users start with the [`mongodbatlas_advanced_cluster`](advanced_cluster) resource. Key differences between [`mongodbatlas_cluster`](cluster) and [`mongodbatlas_advanced_cluster`](advanced_cluster) include support for [Multi-Cloud Clusters](https://www.mongodb.com/blog/post/introducing-multicloud-clusters-on-mongodb-atlas), [Asymmetric Sharding](https://registry.terraform.io/providers/mongodb/mongodbatlas/latest/docs/guides/advanced-cluster-new-sharding-schema), and [Independent Scaling of Analytics Node Tiers](https://www.mongodb.com/blog/post/introducing-ability-independently-scale-atlas-analytics-node-tiers). For existing [`mongodbatlas_cluster`](cluster) resource users see our [Migration Guide](https://registry.terraform.io/providers/mongodb/mongodbatlas/latest/docs/guides/cluster-to-advanced-cluster-migration-guide). -> **NOTE:** If Backup Compliance Policy is enabled for the project for which this backup schedule is defined, you cannot modify the backup schedule for an individual cluster below the minimum requirements set in the Backup Compliance Policy. See [Backup Compliance Policy Prohibited Actions and Considerations](https://www.mongodb.com/docs/atlas/backup/cloud-backup/backup-compliance-policy/#configure-a-backup-compliance-policy). diff --git a/docs/resources/cluster.md b/docs/resources/cluster.md index d102bae353..1cb95bb2c7 100644 --- a/docs/resources/cluster.md +++ b/docs/resources/cluster.md @@ -2,8 +2,7 @@ `mongodbatlas_cluster` provides a Cluster resource. The resource lets you create, edit and delete clusters. The resource requires your Project ID. -~> **IMPORTANT:** -
• New Users: If you are not already using `mongodbatlas_cluster` for your deployment we recommend starting with the [`mongodbatlas_advanced_cluster`](https://registry.terraform.io/providers/mongodb/mongodbatlas/latest/docs/resources/advanced_cluster). `mongodbatlas_advanced_cluster` has the same functionality as `mongodbatlas_cluster` but also supports multi-cloud clusters. +~> **IMPORTANT:** We recommend all new MongoDB Atlas Terraform users start with the [`mongodbatlas_advanced_cluster`](advanced_cluster) resource. Key differences between [`mongodbatlas_cluster`](cluster) and [`mongodbatlas_advanced_cluster`](advanced_cluster) include support for [Multi-Cloud Clusters](https://www.mongodb.com/blog/post/introducing-multicloud-clusters-on-mongodb-atlas), [Asymmetric Sharding](https://registry.terraform.io/providers/mongodb/mongodbatlas/latest/docs/guides/advanced-cluster-new-sharding-schema), and [Independent Scaling of Analytics Node Tiers](https://www.mongodb.com/blog/post/introducing-ability-independently-scale-atlas-analytics-node-tiers). For existing [`mongodbatlas_cluster`](cluster) resource users see our [Migration Guide](https://registry.terraform.io/providers/mongodb/mongodbatlas/latest/docs/guides/cluster-to-advanced-cluster-migration-guide). -> **NOTE:** Groups and projects are synonymous terms. You may find group_id in the official documentation. From d90311164b8d29395b33e2ecdf7c2e504963a814 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 21 Oct 2024 09:44:11 +0200 Subject: [PATCH 02/35] revert SDK preview changes (#2719) --- go.mod | 1 - go.sum | 2 -- internal/config/client.go | 22 ---------------------- scripts/update-sdk.sh | 3 --- 4 files changed, 28 deletions(-) diff --git a/go.mod b/go.mod index 235142099d..39ed58da67 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,6 @@ require ( github.com/hashicorp/terraform-plugin-sdk/v2 v2.34.0 github.com/hashicorp/terraform-plugin-testing v1.9.0 github.com/mongodb-forks/digest v1.1.0 - github.com/mongodb/atlas-sdk-go v1.0.1-0.20241018083659-a287665cc1d3 github.com/spf13/cast v1.6.0 github.com/stretchr/testify v1.9.0 github.com/zclconf/go-cty v1.15.0 diff --git a/go.sum b/go.sum index 13b486cf23..307e6d65da 100644 --- a/go.sum +++ b/go.sum @@ -635,8 +635,6 @@ github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx github.com/mmcloughlin/avo v0.5.0/go.mod h1:ChHFdoV7ql95Wi7vuq2YT1bwCJqiWdZrQ1im3VujLYM= github.com/mongodb-forks/digest v1.1.0 h1:7eUdsR1BtqLv0mdNm4OXs6ddWvR4X2/OsLwdKksrOoc= github.com/mongodb-forks/digest v1.1.0/go.mod h1:rb+EX8zotClD5Dj4NdgxnJXG9nwrlx3NWKJ8xttz1Dg= -github.com/mongodb/atlas-sdk-go v1.0.1-0.20241018083659-a287665cc1d3 h1:iK3OmXqUqkYsPCUwPlTXqylKTK7seP6U+I11OySwkcc= -github.com/mongodb/atlas-sdk-go v1.0.1-0.20241018083659-a287665cc1d3/go.mod h1:CE0qO1AJFrP9ajK/KnRUwKzoPKVoqAmZVFnsofvTwRE= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= diff --git a/internal/config/client.go b/internal/config/client.go index 5e6b5aacd2..7b4aa4db77 100644 --- a/internal/config/client.go +++ b/internal/config/client.go @@ -9,7 +9,6 @@ import ( "strings" "time" - adminpreview "github.com/mongodb/atlas-sdk-go/admin" admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" "go.mongodb.org/atlas-sdk/v20240805005/admin" matlasClient "go.mongodb.org/atlas/mongodbatlas" @@ -33,7 +32,6 @@ type MongoDBClient struct { Atlas *matlasClient.Client AtlasV2 *admin.APIClient AtlasV220240530 *admin20240530.APIClient // used in advanced_cluster and cloud_backup_schedule for avoiding breaking changes - AtlasPreview *adminpreview.APIClient // used for preview features, don't use in resources exposed in the provider list Config *Config } @@ -112,16 +110,10 @@ func (c *Config) NewClient(ctx context.Context) (any, error) { return nil, err } - sdkPreviewClient, err := c.newSDKPreviewClient(client) - if err != nil { - return nil, err - } - clients := &MongoDBClient{ Atlas: atlasClient, AtlasV2: sdkV2Client, AtlasV220240530: sdkV220240530Client, - AtlasPreview: sdkPreviewClient, Config: c, } return clients, nil @@ -155,20 +147,6 @@ func (c *Config) newSDKV220240530Client(client *http.Client) (*admin20240530.API return sdk, nil } -func (c *Config) newSDKPreviewClient(client *http.Client) (*adminpreview.APIClient, error) { - opts := []adminpreview.ClientModifier{ - adminpreview.UseHTTPClient(client), - adminpreview.UseUserAgent(userAgent(c)), - adminpreview.UseBaseURL(c.BaseURL), - adminpreview.UseDebug(false)} - - sdk, err := adminpreview.NewClient(opts...) - if err != nil { - return nil, err - } - return sdk, nil -} - func (c *MongoDBClient) GetRealmClient(ctx context.Context) (*realm.Client, error) { // Realm if c.Config.PublicKey == "" && c.Config.PrivateKey == "" { diff --git a/scripts/update-sdk.sh b/scripts/update-sdk.sh index e56ce8095a..5023a9cea1 100755 --- a/scripts/update-sdk.sh +++ b/scripts/update-sdk.sh @@ -32,8 +32,5 @@ echo "==> Updating SDK ${CURRENT_SDK_RELEASE} to latest major version ${LATEST_ gomajor get --rewrite "go.mongodb.org/atlas-sdk/${CURRENT_SDK_RELEASE}" "go.mongodb.org/atlas-sdk/${LATEST_SDK_RELEASE}@${LATEST_SDK_TAG}" -echo "==> Updating SDK Preview version" -go get github.com/mongodb/atlas-sdk-go@preview-latest - go mod tidy echo "Done" From 637dc07f8b811e06c3519084613bdfce3edbdb0b Mon Sep 17 00:00:00 2001 From: Espen Albert Date: Tue, 22 Oct 2024 11:52:25 +0100 Subject: [PATCH 03/35] fix: Fixes inconsistent result when using a multi-region cluster by always using a single spec (#2685) * fix: Initial workaround for multiple specs issuing a warning of spec missmatch * fix: can only use multiple specs in data source (schema limitation) * test: Add a test to confirm multi-region cluster can be used with search deployment * chore: changelog file * chore: fix test enum value * chore: revert timeout changes * Update .changelog/2685.txt Co-authored-by: kanchana-mongodb <54281287+kanchana-mongodb@users.noreply.github.com> --------- Co-authored-by: Leo Antoli <430982+lantoli@users.noreply.github.com> Co-authored-by: kanchana-mongodb <54281287+kanchana-mongodb@users.noreply.github.com> --- .changelog/2685.txt | 3 + .../data_source_search_deployment.go | 2 +- .../model_search_deployment.go | 11 +-- .../model_search_deployment_test.go | 2 +- .../resource_search_deployment.go | 6 +- .../resource_search_deployment_test.go | 67 ++++++++++++++++--- 6 files changed, 73 insertions(+), 18 deletions(-) create mode 100644 .changelog/2685.txt diff --git a/.changelog/2685.txt b/.changelog/2685.txt new file mode 100644 index 0000000000..6a3d0d441e --- /dev/null +++ b/.changelog/2685.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/mongodbatlas_search_deployment: Fixes inconsistent result for a multi-region cluster that always uses a single spec. +``` diff --git a/internal/service/searchdeployment/data_source_search_deployment.go b/internal/service/searchdeployment/data_source_search_deployment.go index 8de650498f..35486d4ec3 100644 --- a/internal/service/searchdeployment/data_source_search_deployment.go +++ b/internal/service/searchdeployment/data_source_search_deployment.go @@ -44,7 +44,7 @@ func (d *searchDeploymentDS) Read(ctx context.Context, req datasource.ReadReques return } - newSearchDeploymentModel, diagnostics := NewTFSearchDeployment(ctx, clusterName, deploymentResp, nil) + newSearchDeploymentModel, diagnostics := NewTFSearchDeployment(ctx, clusterName, deploymentResp, nil, true) resp.Diagnostics.Append(diagnostics...) if resp.Diagnostics.HasError() { return diff --git a/internal/service/searchdeployment/model_search_deployment.go b/internal/service/searchdeployment/model_search_deployment.go index 97ebdf0a90..d8ce3d143c 100644 --- a/internal/service/searchdeployment/model_search_deployment.go +++ b/internal/service/searchdeployment/model_search_deployment.go @@ -25,7 +25,7 @@ func NewSearchDeploymentReq(ctx context.Context, searchDeploymentPlan *TFSearchD } } -func NewTFSearchDeployment(ctx context.Context, clusterName string, deployResp *admin.ApiSearchDeploymentResponse, timeout *timeouts.Value) (*TFSearchDeploymentRSModel, diag.Diagnostics) { +func NewTFSearchDeployment(ctx context.Context, clusterName string, deployResp *admin.ApiSearchDeploymentResponse, timeout *timeouts.Value, allowMultipleSpecs bool) (*TFSearchDeploymentRSModel, diag.Diagnostics) { result := TFSearchDeploymentRSModel{ ID: types.StringPointerValue(deployResp.Id), ClusterName: types.StringValue(clusterName), @@ -37,13 +37,16 @@ func NewTFSearchDeployment(ctx context.Context, clusterName string, deployResp * result.Timeouts = *timeout } - specsList, diagnostics := types.ListValueFrom(ctx, SpecObjectType, newTFSpecsModel(deployResp.GetSpecs())) + specs := deployResp.GetSpecs() + if !allowMultipleSpecs && len(specs) > 1 { + specs = specs[:1] + } + specsList, diagnostics := types.ListValueFrom(ctx, SpecObjectType, newTFSpecsModel(specs)) if diagnostics.HasError() { return nil, diagnostics } - result.Specs = specsList - return &result, nil + return &result, diagnostics } func newTFSpecsModel(specs []admin.ApiSearchDeploymentSpec) []TFSearchNodeSpecModel { diff --git a/internal/service/searchdeployment/model_search_deployment_test.go b/internal/service/searchdeployment/model_search_deployment_test.go index 62711afa16..a51ec2b08f 100644 --- a/internal/service/searchdeployment/model_search_deployment_test.go +++ b/internal/service/searchdeployment/model_search_deployment_test.go @@ -55,7 +55,7 @@ func TestSearchDeploymentSDKToTFModel(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - resultModel, diags := searchdeployment.NewTFSearchDeployment(context.Background(), tc.clusterName, tc.SDKResp, nil) + resultModel, diags := searchdeployment.NewTFSearchDeployment(context.Background(), tc.clusterName, tc.SDKResp, nil, false) if diags.HasError() { t.Errorf("unexpected errors found: %s", diags.Errors()[0].Summary()) } diff --git a/internal/service/searchdeployment/resource_search_deployment.go b/internal/service/searchdeployment/resource_search_deployment.go index 5ef8029c32..1695650233 100644 --- a/internal/service/searchdeployment/resource_search_deployment.go +++ b/internal/service/searchdeployment/resource_search_deployment.go @@ -75,7 +75,7 @@ func (r *searchDeploymentRS) Create(ctx context.Context, req resource.CreateRequ resp.Diagnostics.AddError("error during search deployment creation", err.Error()) return } - newSearchNodeModel, diagnostics := NewTFSearchDeployment(ctx, clusterName, deploymentResp, &searchDeploymentPlan.Timeouts) + newSearchNodeModel, diagnostics := NewTFSearchDeployment(ctx, clusterName, deploymentResp, &searchDeploymentPlan.Timeouts, false) resp.Diagnostics.Append(diagnostics...) if resp.Diagnostics.HasError() { return @@ -103,7 +103,7 @@ func (r *searchDeploymentRS) Read(ctx context.Context, req resource.ReadRequest, return } - newSearchNodeModel, diagnostics := NewTFSearchDeployment(ctx, clusterName, deploymentResp, &searchDeploymentPlan.Timeouts) + newSearchNodeModel, diagnostics := NewTFSearchDeployment(ctx, clusterName, deploymentResp, &searchDeploymentPlan.Timeouts, false) resp.Diagnostics.Append(diagnostics...) if resp.Diagnostics.HasError() { return @@ -138,7 +138,7 @@ func (r *searchDeploymentRS) Update(ctx context.Context, req resource.UpdateRequ resp.Diagnostics.AddError("error during search deployment update", err.Error()) return } - newSearchNodeModel, diagnostics := NewTFSearchDeployment(ctx, clusterName, deploymentResp, &searchDeploymentPlan.Timeouts) + newSearchNodeModel, diagnostics := NewTFSearchDeployment(ctx, clusterName, deploymentResp, &searchDeploymentPlan.Timeouts, false) resp.Diagnostics.Append(diagnostics...) if resp.Diagnostics.HasError() { return diff --git a/internal/service/searchdeployment/resource_search_deployment_test.go b/internal/service/searchdeployment/resource_search_deployment_test.go index 8e1ad8da5a..5bba1437d8 100644 --- a/internal/service/searchdeployment/resource_search_deployment_test.go +++ b/internal/service/searchdeployment/resource_search_deployment_test.go @@ -11,24 +11,28 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" ) +const ( + resourceID = "mongodbatlas_search_deployment.test" + dataSourceID = "data.mongodbatlas_search_deployment.test" +) + func TestAccSearchDeployment_basic(t *testing.T) { var ( - resourceName = "mongodbatlas_search_deployment.test" - orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") - projectName = acc.RandomProjectName() - clusterName = acc.RandomClusterName() + 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: checkDestroy, Steps: []resource.TestStep{ - newSearchNodeTestStep(resourceName, orgID, projectName, clusterName, "S20_HIGHCPU_NVME", 3), - newSearchNodeTestStep(resourceName, orgID, projectName, clusterName, "S30_HIGHCPU_NVME", 4), + newSearchNodeTestStep(resourceID, orgID, projectName, clusterName, "S20_HIGHCPU_NVME", 3), + newSearchNodeTestStep(resourceID, orgID, projectName, clusterName, "S30_HIGHCPU_NVME", 4), { Config: configBasic(orgID, projectName, clusterName, "S30_HIGHCPU_NVME", 4), - ResourceName: resourceName, - ImportStateIdFunc: importStateIDFunc(resourceName), + ResourceName: resourceID, + ImportStateIdFunc: importStateIDFunc(resourceID), ImportState: true, ImportStateVerify: true, }, @@ -36,9 +40,39 @@ func TestAccSearchDeployment_basic(t *testing.T) { }) } +func TestAccSearchDeployment_multiRegion(t *testing.T) { + var ( + clusterInfo = acc.GetClusterInfo(t, &acc.ClusterRequest{ + ClusterName: "multi-region-cluster", + ReplicationSpecs: []acc.ReplicationSpecRequest{ + { + Region: "US_EAST_1", + ExtraRegionConfigs: []acc.ReplicationSpecRequest{ + {Region: "US_WEST_2", Priority: 6, InstanceSize: "M10", NodeCount: 2}, + }, + }, + }, + }) + ) + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acc.PreCheckBasic(t) }, + ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, + CheckDestroy: checkDestroy, + Steps: []resource.TestStep{ + { + Config: clusterInfo.TerraformStr + configSearchDeployment(clusterInfo.ProjectID, clusterInfo.TerraformNameRef, "S20_HIGHCPU_NVME", 2), + Check: resource.ComposeAggregateTestCheckFunc( + checkExists(resourceID), + resource.TestCheckResourceAttr(resourceID, "specs.#", "1"), + ), + }, + }, + }) +} + func newSearchNodeTestStep(resourceName, orgID, projectName, clusterName, instanceSize string, searchNodeCount int) resource.TestStep { resourceChecks := searchNodeChecks(resourceName, clusterName, instanceSize, searchNodeCount) - dataSourceChecks := searchNodeChecks(fmt.Sprintf("data.%s", resourceName), clusterName, instanceSize, searchNodeCount) + dataSourceChecks := searchNodeChecks(dataSourceID, clusterName, instanceSize, searchNodeCount) return resource.TestStep{ Config: configBasic(orgID, projectName, clusterName, instanceSize, searchNodeCount), Check: resource.ComposeAggregateTestCheckFunc(append(resourceChecks, dataSourceChecks...)...), @@ -80,6 +114,21 @@ func configBasic(orgID, projectName, clusterName, instanceSize string, searchNod `, clusterConfig, instanceSize, searchNodeCount) } +func configSearchDeployment(projectID, clusterNameRef, instanceSize string, searchNodeCount int) string { + return fmt.Sprintf(` + resource "mongodbatlas_search_deployment" "test" { + project_id = %[1]q + cluster_name = %[2]s + specs = [ + { + instance_size = %[3]q + node_count = %[4]d + } + ] + } + `, projectID, clusterNameRef, instanceSize, searchNodeCount) +} + func advancedClusterConfig(orgID, projectName, clusterName string) string { return fmt.Sprintf(` resource "mongodbatlas_project" "test" { From 1883f824026442a4b343719d724aad664e935b4b Mon Sep 17 00:00:00 2001 From: svc-apix-bot Date: Tue, 22 Oct 2024 10:54:17 +0000 Subject: [PATCH 04/35] chore: Updates CHANGELOG.md for #2685 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 995ec024e5..77006bd8ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ BUG FIXES: * resource/mongodbatlas_event_trigger: Always includes `disabled` in the PUT payload ([#2690](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2690)) * resource/mongodbatlas_organization: Avoids inconsistent result returned by provider when `USER_NOT_FOUND` ([#2684](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2684)) +* resource/mongodbatlas_search_deployment: Fixes inconsistent result for a multi-region cluster that always uses a single spec. ([#2685](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2685)) ## 1.21.1 (October 09, 2024) From fc28bf48d47df525be73833fc18481688a61df90 Mon Sep 17 00:00:00 2001 From: svc-apix-bot Date: Tue, 22 Oct 2024 12:35:29 +0000 Subject: [PATCH 05/35] chore: Updates examples link in index.md for v1.21.2 release --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index 9000ef48ba..9ef95749b7 100644 --- a/docs/index.md +++ b/docs/index.md @@ -220,7 +220,7 @@ We ship binaries but do not prioritize fixes for the following operating system ## Examples from MongoDB and the Community -We have [example configurations](https://github.com/mongodb/terraform-provider-mongodbatlas/tree/v1.21.1/examples) +We have [example configurations](https://github.com/mongodb/terraform-provider-mongodbatlas/tree/v1.21.2/examples) in our GitHub repo that will help both beginner and more advanced users. Have a good example you've created and want to share? From d5372d8f0a5f734f4a6124f158f9701310acf1e2 Mon Sep 17 00:00:00 2001 From: svc-apix-bot Date: Tue, 22 Oct 2024 12:35:50 +0000 Subject: [PATCH 06/35] chore: Updates CHANGELOG.md header for v1.21.2 release --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77006bd8ac..d5dba5a7d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ ## (Unreleased) +## 1.21.2 (October 22, 2024) + ENHANCEMENTS: * data-source/mongodbatlas_advanced_cluster: Adds new `config_server_management_mode` and `config_server_type` fields ([#2670](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2670)) From aa35d0ede1970bd68068d05d6174524fcfab3078 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Tue, 22 Oct 2024 17:32:57 +0200 Subject: [PATCH 07/35] fix TestAccBackupSnapshotExportJob_basic (#2723) --- .../resource_cloud_backup_snapshot_export_job_test.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job_test.go b/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job_test.go index 9785d63bc4..7d4579b98a 100644 --- a/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job_test.go +++ b/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job_test.go @@ -63,10 +63,11 @@ func basicTestCase(tb testing.TB) *resource.TestCase { Check: resource.ComposeAggregateTestCheckFunc(checks...), }, { - ResourceName: resourceName, - ImportStateIdFunc: importStateIDFunc(resourceName), - ImportState: true, - ImportStateVerify: true, + ResourceName: resourceName, + ImportStateIdFunc: importStateIDFunc(resourceName), + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"state"}, // state can change from Queued to InProgress }, }, } From 166a58ae28000e50037eecf4ec6ce68a65a27516 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 23 Oct 2024 05:26:17 +0200 Subject: [PATCH 08/35] chore: Bump github.com/hashicorp/terraform-plugin-framework-validators (#2727) Bumps [github.com/hashicorp/terraform-plugin-framework-validators](https://github.com/hashicorp/terraform-plugin-framework-validators) from 0.13.0 to 0.14.0. - [Release notes](https://github.com/hashicorp/terraform-plugin-framework-validators/releases) - [Changelog](https://github.com/hashicorp/terraform-plugin-framework-validators/blob/main/CHANGELOG.md) - [Commits](https://github.com/hashicorp/terraform-plugin-framework-validators/compare/v0.13.0...v0.14.0) --- updated-dependencies: - dependency-name: github.com/hashicorp/terraform-plugin-framework-validators dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 39ed58da67..f98101a916 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/hashicorp/hcl/v2 v2.22.0 github.com/hashicorp/terraform-plugin-framework v1.12.0 github.com/hashicorp/terraform-plugin-framework-timeouts v0.4.1 - github.com/hashicorp/terraform-plugin-framework-validators v0.13.0 + github.com/hashicorp/terraform-plugin-framework-validators v0.14.0 github.com/hashicorp/terraform-plugin-go v0.24.0 github.com/hashicorp/terraform-plugin-log v0.9.0 github.com/hashicorp/terraform-plugin-mux v0.16.0 diff --git a/go.sum b/go.sum index 307e6d65da..0a39999bd8 100644 --- a/go.sum +++ b/go.sum @@ -520,8 +520,8 @@ github.com/hashicorp/terraform-plugin-framework v1.12.0 h1:7HKaueHPaikX5/7cbC1r9 github.com/hashicorp/terraform-plugin-framework v1.12.0/go.mod h1:N/IOQ2uYjW60Jp39Cp3mw7I/OpC/GfZ0385R0YibmkE= github.com/hashicorp/terraform-plugin-framework-timeouts v0.4.1 h1:gm5b1kHgFFhaKFhm4h2TgvMUlNzFAtUqlcOWnWPm+9E= github.com/hashicorp/terraform-plugin-framework-timeouts v0.4.1/go.mod h1:MsjL1sQ9L7wGwzJ5RjcI6FzEMdyoBnw+XK8ZnOvQOLY= -github.com/hashicorp/terraform-plugin-framework-validators v0.13.0 h1:bxZfGo9DIUoLLtHMElsu+zwqI4IsMZQBRRy4iLzZJ8E= -github.com/hashicorp/terraform-plugin-framework-validators v0.13.0/go.mod h1:wGeI02gEhj9nPANU62F2jCaHjXulejm/X+af4PdZaNo= +github.com/hashicorp/terraform-plugin-framework-validators v0.14.0 h1:3PCn9iyzdVOgHYOBmncpSSOxjQhCTYmc+PGvbdlqSaI= +github.com/hashicorp/terraform-plugin-framework-validators v0.14.0/go.mod h1:LwDKNdzxrDY/mHBrlC6aYfE2fQ3Dk3gaJD64vNiXvo4= github.com/hashicorp/terraform-plugin-go v0.24.0 h1:2WpHhginCdVhFIrWHxDEg6RBn3YaWzR2o6qUeIEat2U= github.com/hashicorp/terraform-plugin-go v0.24.0/go.mod h1:tUQ53lAsOyYSckFGEefGC5C8BAaO0ENqzFd3bQeuYQg= github.com/hashicorp/terraform-plugin-log v0.9.0 h1:i7hOA+vdAItN1/7UrfBqBwvYPQ9TFvymaRGZED3FCV0= From af5c9155e61433124507725693b846318f7c77c4 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Thu, 24 Oct 2024 12:31:28 +0200 Subject: [PATCH 09/35] fix: Fixes `mongodbatlas_project` when user doesn't have project owner permission (#2731) * update doc * add deprecated message * changelog * deprecate params * initial TestAccProject_slowOperationNotOwner * update version to 1.24.0 * changeRoles * Revert "changeRoles" This reverts commit c8ba3c84c2e419d468be1135b5bf408961f8f92a. * Revert "initial TestAccProject_slowOperationNotOwner" This reverts commit d1473711e888887ab5e3991f3cd7314ec52a23e2. * don't update the value if it's in Create so value is unknown * pass warnings * Update internal/service/project/resource_project.go Co-authored-by: Marco Suma * apply feedback in doc * clarify docs --------- Co-authored-by: Marco Suma --- .changelog/2731.txt | 23 ++++++++++++++++ docs/data-sources/project.md | 3 +-- docs/data-sources/projects.md | 2 +- docs/resources/project.md | 2 +- internal/common/constant/deprecation.go | 1 + .../service/project/data_source_project.go | 5 ++-- .../service/project/data_source_projects.go | 7 ++--- internal/service/project/resource_project.go | 26 ++++++++++++------- .../service/project/resource_project_test.go | 2 +- 9 files changed, 52 insertions(+), 19 deletions(-) create mode 100644 .changelog/2731.txt diff --git a/.changelog/2731.txt b/.changelog/2731.txt new file mode 100644 index 0000000000..073ff2e2d5 --- /dev/null +++ b/.changelog/2731.txt @@ -0,0 +1,23 @@ +```release-note:bug +resource/mongodbatlas_project: Avoids error when user doesn't have project owner permission +``` + +```release-note:bug +data-source/mongodbatlas_project: Avoids error when user doesn't have project owner permission +``` + +```release-note:bug +data-source/mongodbatlas_projects: Avoids error when user doesn't have project owner permission +``` + +```release-note:note +resource/mongodbatlas_project: Deprecates `is_slow_operation_thresholding_enabled`. Attribute will be supported in a separate resource as it requires different set of permissions +``` + +```release-note:note +data-source/mongodbatlas_project: Deprecates `is_slow_operation_thresholding_enabled`. Attribute will be supported in a separate data source as it requires different set of permissions +``` + +```release-note:note +data-source/mongodbatlas_projects: Deprecates `is_slow_operation_thresholding_enabled`. Attribute will be supported in a separate data source as it requires different set of permissions +``` diff --git a/docs/data-sources/project.md b/docs/data-sources/project.md index a5df84461b..b888f46a74 100644 --- a/docs/data-sources/project.md +++ b/docs/data-sources/project.md @@ -90,8 +90,7 @@ In addition to all arguments above, the following attributes are exported: * `is_realtime_performance_panel_enabled` - Flag that indicates whether to enable Real Time Performance Panel for the project. If enabled, you can see real time metrics from your MongoDB database. * `is_schema_advisor_enabled` - Flag that indicates whether to enable Schema Advisor for the project. If enabled, you receive customized recommendations to optimize your data model and enhance performance. Disable this setting to disable schema suggestions in the [Performance Advisor](https://www.mongodb.com/docs/atlas/performance-advisor/#std-label-performance-advisor) and the [Data Explorer](https://www.mongodb.com/docs/atlas/atlas-ui/#std-label-atlas-ui). * `region_usage_restrictions` - If GOV_REGIONS_ONLY the project can be used for government regions only, otherwise defaults to standard regions. For more information see [MongoDB Atlas for Government](https://www.mongodb.com/docs/atlas/government/api/#creating-a-project). -* `is_slow_operation_thresholding_enabled` - Flag that enables MongoDB Cloud to use its slow operation threshold for the specified project. The threshold determines which operations the Performance Advisor and Query Profiler considers slow. When enabled, MongoDB Cloud uses the average execution time for operations on your cluster to determine slow-running queries. As a result, the threshold is more pertinent to your cluster workload. The slow operation threshold is enabled by default for dedicated clusters (M10+). When disabled, MongoDB Cloud considers any operation that takes longer than 100 milliseconds to be slow. To use this resource, the requesting API Key must have the Project Owner role. - +* `is_slow_operation_thresholding_enabled` - (Deprecated) Flag that enables MongoDB Cloud to use its slow operation threshold for the specified project. The threshold determines which operations the Performance Advisor and Query Profiler considers slow. When enabled, MongoDB Cloud uses the average execution time for operations on your cluster to determine slow-running queries. As a result, the threshold is more pertinent to your cluster workload. The slow operation threshold is enabled by default for dedicated clusters (M10+). When disabled, MongoDB Cloud considers any operation that takes longer than 100 milliseconds to be slow. **Note**: To use this attribute, the requesting API Key must have the Project Owner role, if not it will show a warning and will return `false`. If you are not using this field, you don't need to take any action. ### Teams diff --git a/docs/data-sources/projects.md b/docs/data-sources/projects.md index 413ccbad35..95aeca36f0 100644 --- a/docs/data-sources/projects.md +++ b/docs/data-sources/projects.md @@ -65,7 +65,7 @@ data "mongodbatlas_projects" "test" { * `is_realtime_performance_panel_enabled` - Flag that indicates whether to enable Real Time Performance Panel for the project. If enabled, you can see real time metrics from your MongoDB database. * `is_schema_advisor_enabled` - Flag that indicates whether to enable Schema Advisor for the project. If enabled, you receive customized recommendations to optimize your data model and enhance performance. Disable this setting to disable schema suggestions in the [Performance Advisor](https://www.mongodb.com/docs/atlas/performance-advisor/#std-label-performance-advisor) and the [Data Explorer](https://www.mongodb.com/docs/atlas/atlas-ui/#std-label-atlas-ui). * `region_usage_restrictions` - If GOV_REGIONS_ONLY the project can be used for government regions only, otherwise defaults to standard regions. For more information see [MongoDB Atlas for Government](https://www.mongodb.com/docs/atlas/government/api/#creating-a-project). -* `is_slow_operation_thresholding_enabled` - Flag that enables MongoDB Cloud to use its slow operation threshold for the specified project. The threshold determines which operations the Performance Advisor and Query Profiler considers slow. When enabled, MongoDB Cloud uses the average execution time for operations on your cluster to determine slow-running queries. As a result, the threshold is more pertinent to your cluster workload. The slow operation threshold is enabled by default for dedicated clusters (M10+). When disabled, MongoDB Cloud considers any operation that takes longer than 100 milliseconds to be slow. To use this resource, the requesting API Key must have the Project Owner role. +* `is_slow_operation_thresholding_enabled` - (Deprecated) Flag that enables MongoDB Cloud to use its slow operation threshold for the specified project. The threshold determines which operations the Performance Advisor and Query Profiler considers slow. When enabled, MongoDB Cloud uses the average execution time for operations on your cluster to determine slow-running queries. As a result, the threshold is more pertinent to your cluster workload. The slow operation threshold is enabled by default for dedicated clusters (M10+). When disabled, MongoDB Cloud considers any operation that takes longer than 100 milliseconds to be slow. **Note**: To use this attribute, the requesting API Key must have the Project Owner role, if not it will show a warning and will return `false`. If you are not using this field, you don't need to take any action. ### Teams diff --git a/docs/resources/project.md b/docs/resources/project.md index 9e4a4965dc..65405b37ae 100644 --- a/docs/resources/project.md +++ b/docs/resources/project.md @@ -59,7 +59,7 @@ resource "mongodbatlas_project" "test" { * `is_realtime_performance_panel_enabled` - (Optional) Flag that indicates whether to enable Real Time Performance Panel for the project. If enabled, you can see real time metrics from your MongoDB database. By default, this flag is set to true. * `is_schema_advisor_enabled` - (Optional) Flag that indicates whether to enable Schema Advisor for the project. If enabled, you receive customized recommendations to optimize your data model and enhance performance. Disable this setting to disable schema suggestions in the [Performance Advisor](https://www.mongodb.com/docs/atlas/performance-advisor/#std-label-performance-advisor) and the [Data Explorer](https://www.mongodb.com/docs/atlas/atlas-ui/#std-label-atlas-ui). By default, this flag is set to true. * `region_usage_restrictions` - (Optional - set value to GOV_REGIONS_ONLY) Designates that this project can be used for government regions only. If not set the project will default to standard regions. You cannot deploy clusters across government and standard regions in the same project. AWS is the only cloud provider for AtlasGov. For more information see [MongoDB Atlas for Government](https://www.mongodb.com/docs/atlas/government/api/#creating-a-project). -* `is_slow_operation_thresholding_enabled` - (Optional) Flag that enables MongoDB Cloud to use its slow operation threshold for the specified project. The threshold determines which operations the Performance Advisor and Query Profiler considers slow. When enabled, MongoDB Cloud uses the average execution time for operations on your cluster to determine slow-running queries. As a result, the threshold is more pertinent to your cluster workload. The slow operation threshold is enabled by default for dedicated clusters (M10+). When disabled, MongoDB Cloud considers any operation that takes longer than 100 milliseconds to be slow. To use this resource, the requesting API Key must have the Project Owner role. +* `is_slow_operation_thresholding_enabled` - (Deprecated) (Optional) Flag that enables MongoDB Cloud to use its slow operation threshold for the specified project. The threshold determines which operations the Performance Advisor and Query Profiler considers slow. When enabled, MongoDB Cloud uses the average execution time for operations on your cluster to determine slow-running queries. As a result, the threshold is more pertinent to your cluster workload. The slow operation threshold is enabled by default for dedicated clusters (M10+). When disabled, MongoDB Cloud considers any operation that takes longer than 100 milliseconds to be slow. **Note**: To use this attribute, the requesting API Key must have the Project Owner role, if not it will show a warning and will return `false`. If you are not using this field, you don't need to take any action. ### Tags diff --git a/internal/common/constant/deprecation.go b/internal/common/constant/deprecation.go index 88fc9c40e6..b0fc609f2e 100644 --- a/internal/common/constant/deprecation.go +++ b/internal/common/constant/deprecation.go @@ -3,6 +3,7 @@ package constant const ( DeprecationParam = "This parameter is deprecated." DeprecationParamWithReplacement = "This parameter is deprecated. Please transition to %s." + DeprecationParamByVersion = "This parameter is deprecated and will be removed in version %s." DeprecationParamByVersionWithReplacement = "This parameter is deprecated and will be removed in version %s. Please transition to %s." DeprecationParamFutureWithReplacement = "This parameter is deprecated and will be removed in the future. Please transition to %s" DeprecationResourceByDateWithReplacement = "This resource is deprecated and will be removed in %s. Please transition to %s." diff --git a/internal/service/project/data_source_project.go b/internal/service/project/data_source_project.go index 982127552f..92c58af777 100644 --- a/internal/service/project/data_source_project.go +++ b/internal/service/project/data_source_project.go @@ -103,7 +103,8 @@ func (d *projectDS) Schema(ctx context.Context, req datasource.SchemaRequest, re Computed: true, }, "is_slow_operation_thresholding_enabled": schema.BoolAttribute{ - Computed: true, + Computed: true, + DeprecationMessage: fmt.Sprintf(constant.DeprecationParamByVersion, "1.24.0"), }, "region_usage_restrictions": schema.StringAttribute{ Computed: true, @@ -213,7 +214,7 @@ func (d *projectDS) Read(ctx context.Context, req datasource.ReadRequest, resp * } } - projectProps, err := GetProjectPropsFromAPI(ctx, connV2.ProjectsApi, connV2.TeamsApi, connV2.PerformanceAdvisorApi, project.GetId()) + projectProps, err := GetProjectPropsFromAPI(ctx, connV2.ProjectsApi, connV2.TeamsApi, connV2.PerformanceAdvisorApi, project.GetId(), &resp.Diagnostics) if err != nil { resp.Diagnostics.AddError("error when getting project properties", fmt.Sprintf(ErrorProjectRead, project.GetId(), err.Error())) return diff --git a/internal/service/project/data_source_projects.go b/internal/service/project/data_source_projects.go index 1385ef25da..dd52e38449 100644 --- a/internal/service/project/data_source_projects.go +++ b/internal/service/project/data_source_projects.go @@ -98,7 +98,8 @@ func (d *ProjectsDS) Schema(ctx context.Context, req datasource.SchemaRequest, r Computed: true, }, "is_slow_operation_thresholding_enabled": schema.BoolAttribute{ - Computed: true, + Computed: true, + DeprecationMessage: fmt.Sprintf(constant.DeprecationParamByVersion, "1.24.0"), }, "region_usage_restrictions": schema.StringAttribute{ Computed: true, @@ -208,12 +209,12 @@ func (d *ProjectsDS) Read(ctx context.Context, req datasource.ReadRequest, resp } func populateProjectsDataSourceModel(ctx context.Context, connV2 *admin.APIClient, stateModel *tfProjectsDSModel, projectsRes *admin.PaginatedAtlasGroup) diag.Diagnostics { - diagnostics := []diag.Diagnostic{} + diagnostics := diag.Diagnostics{} input := projectsRes.GetResults() results := make([]*TFProjectDSModel, 0, len(input)) for i := range input { project := input[i] - projectProps, err := GetProjectPropsFromAPI(ctx, connV2.ProjectsApi, connV2.TeamsApi, connV2.PerformanceAdvisorApi, project.GetId()) + projectProps, err := GetProjectPropsFromAPI(ctx, connV2.ProjectsApi, connV2.TeamsApi, connV2.PerformanceAdvisorApi, project.GetId(), &diagnostics) if err == nil { // if the project is still valid, e.g. could have just been deleted projectModel, diags := NewTFProjectDataSourceModel(ctx, &project, *projectProps) diagnostics = append(diagnostics, diags...) diff --git a/internal/service/project/resource_project.go b/internal/service/project/resource_project.go index 33b2adafa2..21ef55dcfe 100644 --- a/internal/service/project/resource_project.go +++ b/internal/service/project/resource_project.go @@ -13,6 +13,7 @@ import ( "go.mongodb.org/atlas-sdk/v20240805005/admin" "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource/schema" @@ -220,8 +221,9 @@ func (r *projectRS) Schema(ctx context.Context, req resource.SchemaRequest, resp }, }, "is_slow_operation_thresholding_enabled": schema.BoolAttribute{ - Computed: true, - Optional: true, + Computed: true, + Optional: true, + DeprecationMessage: fmt.Sprintf(constant.DeprecationParamByVersion, "1.24.0"), PlanModifiers: []planmodifier.Bool{ boolplanmodifier.UseStateForUnknown(), }, @@ -423,7 +425,7 @@ func (r *projectRS) Create(ctx context.Context, req resource.CreateRequest, resp } // get project props - projectProps, err := GetProjectPropsFromAPI(ctx, connV2.ProjectsApi, connV2.TeamsApi, connV2.PerformanceAdvisorApi, projectID) + projectProps, err := GetProjectPropsFromAPI(ctx, connV2.ProjectsApi, connV2.TeamsApi, connV2.PerformanceAdvisorApi, projectID, &resp.Diagnostics) if err != nil { resp.Diagnostics.AddError("error when getting project properties after create", fmt.Sprintf(ErrorProjectRead, projectID, err.Error())) return @@ -475,7 +477,7 @@ func (r *projectRS) Read(ctx context.Context, req resource.ReadRequest, resp *re } // get project props - projectProps, err := GetProjectPropsFromAPI(ctx, connV2.ProjectsApi, connV2.TeamsApi, connV2.PerformanceAdvisorApi, projectID) + projectProps, err := GetProjectPropsFromAPI(ctx, connV2.ProjectsApi, connV2.TeamsApi, connV2.PerformanceAdvisorApi, projectID, &resp.Diagnostics) if err != nil { resp.Diagnostics.AddError("error when getting project properties after create", fmt.Sprintf(ErrorProjectRead, projectID, err.Error())) return @@ -546,7 +548,7 @@ func (r *projectRS) Update(ctx context.Context, req resource.UpdateRequest, resp } // get project props - projectProps, err := GetProjectPropsFromAPI(ctx, connV2.ProjectsApi, connV2.TeamsApi, connV2.PerformanceAdvisorApi, projectID) + projectProps, err := GetProjectPropsFromAPI(ctx, connV2.ProjectsApi, connV2.TeamsApi, connV2.PerformanceAdvisorApi, projectID, &resp.Diagnostics) if err != nil { resp.Diagnostics.AddError("error when getting project properties after create", fmt.Sprintf(ErrorProjectRead, projectID, err.Error())) return @@ -626,7 +628,7 @@ type AdditionalProperties struct { } // GetProjectPropsFromAPI fetches properties obtained from complementary endpoints associated with a project. -func GetProjectPropsFromAPI(ctx context.Context, projectsAPI admin.ProjectsApi, teamsAPI admin.TeamsApi, performanceAdvisorAPI admin.PerformanceAdvisorApi, projectID string) (*AdditionalProperties, error) { +func GetProjectPropsFromAPI(ctx context.Context, projectsAPI admin.ProjectsApi, teamsAPI admin.TeamsApi, performanceAdvisorAPI admin.PerformanceAdvisorApi, projectID string, warnings *diag.Diagnostics) (*AdditionalProperties, error) { teams, _, err := teamsAPI.ListProjectTeams(ctx, projectID).Execute() if err != nil { return nil, fmt.Errorf("error getting project's teams assigned (%s): %v", projectID, err.Error()) @@ -646,7 +648,7 @@ func GetProjectPropsFromAPI(ctx context.Context, projectsAPI admin.ProjectsApi, if err != nil { return nil, fmt.Errorf("error getting project's IP addresses (%s): %v", projectID, err.Error()) } - isSlowOperationThresholdingEnabled, err := ReadIsSlowMsThresholdingEnabled(ctx, performanceAdvisorAPI, projectID) + isSlowOperationThresholdingEnabled, err := ReadIsSlowMsThresholdingEnabled(ctx, performanceAdvisorAPI, projectID, warnings) if err != nil { return nil, fmt.Errorf("error getting project's slow operation thresholding enabled (%s): %v", projectID, err.Error()) } @@ -661,7 +663,7 @@ func GetProjectPropsFromAPI(ctx context.Context, projectsAPI admin.ProjectsApi, } func SetSlowOperationThresholding(ctx context.Context, performanceAdvisorAPI admin.PerformanceAdvisorApi, projectID string, enabledPlan types.Bool) error { - if enabledPlan.IsNull() { + if enabledPlan.IsNull() || enabledPlan.IsUnknown() { return nil } enabled := enabledPlan.ValueBool() @@ -674,9 +676,15 @@ func SetSlowOperationThresholding(ctx context.Context, performanceAdvisorAPI adm return err } -func ReadIsSlowMsThresholdingEnabled(ctx context.Context, api admin.PerformanceAdvisorApi, projectID string) (bool, error) { +func ReadIsSlowMsThresholdingEnabled(ctx context.Context, api admin.PerformanceAdvisorApi, projectID string, warnings *diag.Diagnostics) (bool, error) { response, err := api.GetManagedSlowMs(ctx, projectID).Execute() if err != nil { + if apiError, ok := admin.AsError(err); ok && *apiError.ErrorCode == "USER_UNAUTHORIZED" { + if warnings != nil { + warnings.AddWarning("user does not have permission to read is_slow_operation_thresholding_enabled. Please read our documentation for more information.", fmt.Sprintf(ErrorProjectRead, projectID, err.Error())) + } + return false, nil + } return false, err } var isEnabled bool diff --git a/internal/service/project/resource_project_test.go b/internal/service/project/resource_project_test.go index 6c36b77870..73e9f3a270 100644 --- a/internal/service/project/resource_project_test.go +++ b/internal/service/project/resource_project_test.go @@ -144,7 +144,7 @@ func TestGetProjectPropsFromAPI(t *testing.T) { readGetManagedSlowMsResponse := http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(managedSlowMsJSON))} perfMock.EXPECT().GetManagedSlowMsExecute(mock.Anything).Return(&readGetManagedSlowMsResponse, nil).Maybe() - _, err := project.GetProjectPropsFromAPI(context.Background(), projectsMock, teamsMock, perfMock, dummyProjectID) + _, err := project.GetProjectPropsFromAPI(context.Background(), projectsMock, teamsMock, perfMock, dummyProjectID, nil) if (err != nil) != tc.expectedError { t.Errorf("Case %s: Received unexpected error: %v", tc.name, err) From a265e5d596447f77f5734c15ee8cd12dfe0766b0 Mon Sep 17 00:00:00 2001 From: svc-apix-bot Date: Thu, 24 Oct 2024 10:33:18 +0000 Subject: [PATCH 10/35] chore: Updates CHANGELOG.md for #2731 --- CHANGELOG.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d5dba5a7d4..184d277ce5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ ## (Unreleased) +NOTES: + +* data-source/mongodbatlas_project: Deprecates `is_slow_operation_thresholding_enabled`. Attribute will be supported in a separate data source as it requires different set of permissions ([#2731](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2731)) +* data-source/mongodbatlas_projects: Deprecates `is_slow_operation_thresholding_enabled`. Attribute will be supported in a separate data source as it requires different set of permissions ([#2731](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2731)) +* resource/mongodbatlas_project: Deprecates `is_slow_operation_thresholding_enabled`. Attribute will be supported in a separate resource as it requires different set of permissions ([#2731](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2731)) + +BUG FIXES: + +* data-source/mongodbatlas_project: Avoids error when user doesn't have project owner permission ([#2731](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2731)) +* data-source/mongodbatlas_projects: Avoids error when user doesn't have project owner permission ([#2731](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2731)) +* resource/mongodbatlas_project: Avoids error when user doesn't have project owner permission ([#2731](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2731)) + ## 1.21.2 (October 22, 2024) ENHANCEMENTS: From 0f8b8f5baa58291dbea717091cf02113a6cdde5c Mon Sep 17 00:00:00 2001 From: Agustin Bettati Date: Thu, 24 Oct 2024 16:45:51 +0200 Subject: [PATCH 11/35] chore: Merging schema generation internal tool PoC into master branch (#2735) * feat: Adds initial schema and config models for PoC - Model generation (#2638) * update computability type (#2668) * chore: PoC - Model generation - support primitive types at root level (#2673) * chore: PoC - Schema code generation - Initial support of primitive types (#2682) * initial commit with schema generation function and test fixture * small changes wip * include specific type generators * handling element types and imports * remove unrelated file * extract template logic to separate file * small revert change * extract import to const * follow up adjustments from PR comments and sync with Aastha * chore: PoC - Schema code generation - Supporting nested attributes (#2689) * support nested attribute types * rebasing changes related to unit testing adjustment * chore: PoC - Model generation - Supporting nested schema (List, ListNested, Set & SetNested) (#2693) * chore: PoC - Model generation - Supporting nested schema (objects - Map, MapNested, SingleNested Attributes) (#2704) * chore: PoC - Schema code generation - Supporting generation of typed model (#2703) * support typed model generation inlcuding root and nested attributes * minor fix for type of types map * add clarifying comment * improve name of generated object types, refactor function naming for readability * fix list map and set nested attribute generation (#2708) * chore: PoC - Model generation - support config aliases, ignores, and description overrides (#2712) * chore: PoC - Define make command to call code generation logic (#2706) * wip * iterating over all resources * add config for search deployment * update golden file test with fix in package name * use xstring implementation for pascal case * simplify write file logic * merge fixes * chore: PoC - Support configuration of timeout in schema (#2717) * wip * rebase fixes * fix logic avoiding adding timeout in nested schemas * fix generation * fix enum processing * fix golden file in timeout test * comment out unsupported config properties * simplify interfaces for attribute generation leaving common code in a separate function * chore: PoC - handle merging computability in nested attributes (#2722) * adjusting contributing guide (#2732) --------- Co-authored-by: maastha <122359335+maastha@users.noreply.github.com> Co-authored-by: Aastha Mahendru --- .gitignore | 3 + GNUmakefile | 8 +- contributing/development-best-practices.md | 27 +- go.mod | 12 +- go.sum | 30 +- tools/codegen/codespec/api_spec.go | 93 ++++ tools/codegen/codespec/api_spec_schema.go | 59 +++ .../codespec/api_to_provider_spec_mapper.go | 222 +++++++++ .../api_to_provider_spec_mapper_test.go | 378 ++++++++++++++ tools/codegen/codespec/attribute.go | 272 ++++++++++ tools/codegen/codespec/computability.go | 10 + tools/codegen/codespec/config.go | 123 +++++ tools/codegen/codespec/constants.go | 21 + tools/codegen/codespec/element_type.go | 20 + tools/codegen/codespec/merge_attributes.go | 158 ++++++ tools/codegen/codespec/model.go | 119 +++++ tools/codegen/codespec/string_case.go | 21 + tools/codegen/codespec/terraform_helper.go | 28 ++ tools/codegen/codespec/testdata/api-spec.yml | 465 ++++++++++++++++++ .../config-nested-schema-overrides.yml | 28 ++ .../testdata/config-nested-schema.yml | 16 + .../testdata/config-no-schema-opts.yml | 14 + tools/codegen/codespec/testdata/config.yml | 36 ++ tools/codegen/config.yml | 45 ++ tools/codegen/config/config_model.go | 48 ++ tools/codegen/config/parser.go | 22 + tools/codegen/main.go | 54 ++ tools/codegen/openapi/parser.go | 58 +++ tools/codegen/schema/code_statement.go | 20 + .../schema/codetemplate/schema-file.go.tmpl | 18 + tools/codegen/schema/codetemplate/template.go | 32 ++ tools/codegen/schema/element_type_mapping.go | 25 + tools/codegen/schema/schema_attribute.go | 145 ++++++ .../codegen/schema/schema_attribute_nested.go | 65 +++ .../schema/schema_attribute_primitive.go | 75 +++ .../schema/schema_attribute_timeout.go | 33 ++ tools/codegen/schema/schema_file.go | 31 ++ tools/codegen/schema/schema_file_test.go | 178 +++++++ .../testdata/nested-attributes.golden.go | 126 +++++ .../testdata/primitive-attributes.golden.go | 62 +++ .../schema/testdata/timeouts.golden.go | 30 ++ tools/codegen/schema/typed_model.go | 114 +++++ 42 files changed, 3337 insertions(+), 7 deletions(-) create mode 100644 tools/codegen/codespec/api_spec.go create mode 100644 tools/codegen/codespec/api_spec_schema.go create mode 100644 tools/codegen/codespec/api_to_provider_spec_mapper.go create mode 100644 tools/codegen/codespec/api_to_provider_spec_mapper_test.go create mode 100644 tools/codegen/codespec/attribute.go create mode 100644 tools/codegen/codespec/computability.go create mode 100644 tools/codegen/codespec/config.go create mode 100644 tools/codegen/codespec/constants.go create mode 100644 tools/codegen/codespec/element_type.go create mode 100644 tools/codegen/codespec/merge_attributes.go create mode 100644 tools/codegen/codespec/model.go create mode 100644 tools/codegen/codespec/string_case.go create mode 100644 tools/codegen/codespec/terraform_helper.go create mode 100644 tools/codegen/codespec/testdata/api-spec.yml create mode 100644 tools/codegen/codespec/testdata/config-nested-schema-overrides.yml create mode 100644 tools/codegen/codespec/testdata/config-nested-schema.yml create mode 100644 tools/codegen/codespec/testdata/config-no-schema-opts.yml create mode 100644 tools/codegen/codespec/testdata/config.yml create mode 100644 tools/codegen/config.yml create mode 100644 tools/codegen/config/config_model.go create mode 100644 tools/codegen/config/parser.go create mode 100644 tools/codegen/main.go create mode 100644 tools/codegen/openapi/parser.go create mode 100644 tools/codegen/schema/code_statement.go create mode 100644 tools/codegen/schema/codetemplate/schema-file.go.tmpl create mode 100644 tools/codegen/schema/codetemplate/template.go create mode 100644 tools/codegen/schema/element_type_mapping.go create mode 100644 tools/codegen/schema/schema_attribute.go create mode 100644 tools/codegen/schema/schema_attribute_nested.go create mode 100644 tools/codegen/schema/schema_attribute_primitive.go create mode 100644 tools/codegen/schema/schema_attribute_timeout.go create mode 100644 tools/codegen/schema/schema_file.go create mode 100644 tools/codegen/schema/schema_file_test.go create mode 100644 tools/codegen/schema/testdata/nested-attributes.golden.go create mode 100644 tools/codegen/schema/testdata/primitive-attributes.golden.go create mode 100644 tools/codegen/schema/testdata/timeouts.golden.go create mode 100644 tools/codegen/schema/typed_model.go diff --git a/.gitignore b/.gitignore index 6366b3c11a..5e0f0deefb 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,6 @@ vendor/ *.winfile eol=crlf /.vs node_modules + +#used for schema code generation but is not commited to avoid constant updates +tools/codegen/open-api-spec.yml diff --git a/GNUmakefile b/GNUmakefile index ba3690b6b6..25e6b83d76 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -118,11 +118,17 @@ scaffold: @echo "Reminder: configure the new $(type) in provider.go" # e.g. run: make scaffold-schemas resource_name=streamInstance -# details on usage can be found in contributing/development-best-practices.md under "Scaffolding Schema and Model Definitions" +# details on usage can be found in contributing/development-best-practices.md under "Generating Schema and Model Definitions - Using schema generation HashiCorp tooling" .PHONY: scaffold-schemas scaffold-schemas: @scripts/schema-scaffold.sh $(resource_name) +# e.g. run: make generate-schema resource_name=search_deployment +# resource_name is optional, if not provided all configured resources will be generated +# details on usage can be found in contributing/development-best-practices.md under "Generating Schema and Model Definitions - Using internal tool" +.PHONY: generate-schema +generate-schema: + @go run ./tools/codegen/main.go $(resource_name) .PHONY: generate-doc # e.g. run: make generate-doc resource_name=search_deployment diff --git a/contributing/development-best-practices.md b/contributing/development-best-practices.md index 0f5a5574ba..159d812790 100644 --- a/contributing/development-best-practices.md +++ b/contributing/development-best-practices.md @@ -4,7 +4,7 @@ ## Table of Contents - [Creating New Resource and Data Sources](#creating-new-resources-and-data-sources) - [Scaffolding Initial Code and File Structure](#scaffolding-initial-code-and-file-structure) - - [Scaffolding Schema and Model Definitions](#scaffolding-schema-and-model-definitions) + - [Generating Schema and Model Definitions](#scaffolding-schema-and-model-definitions) - Each resource (and associated data sources) is in a package in `internal/service`. - There can be multiple helper files and they can also be used from other resources, e.g. `common_advanced_cluster.go` defines functions that are also used from other resources using `advancedcluster.FunctionName`. @@ -26,11 +26,30 @@ This will generate resource/data source files and accompanying test files needed As a follow up step, use [Scaffolding Schema and Model Definitions](#scaffolding-schema-and-model-definitions) to autogenerate the schema via the Open API specification. This will require making adjustments to the generated `./internal/service//tfplugingen/generator_config.yml` file. -#### Scaffolding Schema and Model Definitions +#### Generating Schema and Model Definitions + +##### (Recommended) Using internal tool + +The generation command makes use of a configuration file defined under [`./tools/codegen/config.yml`](../tools/codegen/config.yml). The structure of this configuration file can be found under [`./tools/codegen/config/config_model.go`](../tools/codegen/config/config_model.go). + +The generation command takes a single optional argument `resource_name`. If not provided, all resources defined in the configuration are generated. + +```bash +make generate-schema resource_name=search_deployment +``` + +As a result, content of schemas will be written into the corresponding resource packages: +`./internal/service//resource_schema.go` + +**Note**: Data source schema generation is currently not supported. + + +##### (Legacy) Using schema generation HashiCorp tooling + Complementary to the `scaffold` command, there is a command which generates the initial Terraform schema definition and associated Go types for a resource or data source. This processes leverages [Code Generation Tools](https://developer.hashicorp.com/terraform/plugin/code-generation) developed by HashiCorp, which in turn make use of the [Atlas Admin API](https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/) OpenAPI Specification. -##### Running the command +###### Running the command Both `tfplugingen-openapi` and `tfplugingen-framework` must be installed. This can be done by running `make tools`. @@ -49,7 +68,7 @@ Note: if the resulting file paths already exist the content will be stored in fi Note: you can override the Open API description of a field with a custom description via the [overrides](https://developer.hashicorp.com/terraform/plugin/code-generation/openapi-generator#overriding-attribute-descriptions) param. See this [example](internal/service/searchdeployment/tfplugingen/generator_config.yml). -##### Considerations over generated schema and types +###### Considerations over generated schema and types - Generated Go type should include a TF prefix to follow the convention in our codebase, this will not be present in generated code. - Some attribute names may need to be adjusted if there is a difference in how they are named in Terraform vs the API. An examples of this is `group_id` → `project_id`. diff --git a/go.mod b/go.mod index f98101a916..eb95523f89 100644 --- a/go.mod +++ b/go.mod @@ -19,6 +19,8 @@ require ( github.com/hashicorp/terraform-plugin-sdk/v2 v2.34.0 github.com/hashicorp/terraform-plugin-testing v1.9.0 github.com/mongodb-forks/digest v1.1.0 + github.com/sebdah/goldie/v2 v2.5.5 + github.com/pb33f/libopenapi v0.18.1 github.com/spf13/cast v1.6.0 github.com/stretchr/testify v1.9.0 github.com/zclconf/go-cty v1.15.0 @@ -26,6 +28,7 @@ require ( go.mongodb.org/atlas-sdk/v20240530005 v20240530005.0.0 go.mongodb.org/atlas-sdk/v20240805005 v20240805005.0.0 go.mongodb.org/realm v0.1.0 + gopkg.in/yaml.v3 v3.0.1 ) require ( @@ -43,11 +46,14 @@ require ( github.com/apparentlymart/go-cidr v1.1.0 // indirect github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect github.com/armon/go-radix v1.0.0 // indirect + github.com/bahlo/generic-list-go v0.2.0 // indirect github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect github.com/bgentry/speakeasy v0.1.0 // indirect + github.com/buger/jsonparser v1.1.1 // indirect github.com/cloudflare/circl v1.3.7 // indirect github.com/cyphar/filepath-securejoin v0.2.4 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dprotaso/go-yit v0.0.0-20240618133044-5a0af90af097 // indirect github.com/emirpasic/gods v1.18.1 // indirect github.com/fatih/color v1.16.0 // indirect github.com/fatih/structs v1.1.0 // indirect @@ -89,6 +95,7 @@ require ( github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/kevinburke/ssh_config v1.2.0 // indirect github.com/klauspost/compress v1.15.11 // indirect + github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mitchellh/cli v1.1.5 // indirect @@ -102,6 +109,7 @@ require ( github.com/pjbgf/sha1cd v0.3.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/posener/complete v1.2.3 // indirect + github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect github.com/shopspring/decimal v1.2.0 // indirect github.com/skeema/knownhosts v1.2.2 // indirect @@ -112,6 +120,8 @@ require ( github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect + github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect + github.com/wk8/go-ordered-map/v2 v2.1.9-0.20240815153524-6ea36470d1bd // indirect github.com/xanzy/ssh-agent v0.3.3 // indirect github.com/zclconf/go-cty-yaml v1.0.2 // indirect go.opencensus.io v0.24.0 // indirect @@ -137,7 +147,7 @@ require ( google.golang.org/grpc v1.66.2 // indirect google.golang.org/protobuf v1.34.2 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect + ) exclude github.com/denis-tingajkin/go-header v0.4.2 diff --git a/go.sum b/go.sum index 0a39999bd8..395935e231 100644 --- a/go.sum +++ b/go.sum @@ -243,12 +243,16 @@ github.com/aws/aws-sdk-go v1.37.0/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zK github.com/aws/aws-sdk-go v1.44.122/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= github.com/aws/aws-sdk-go v1.55.5 h1:KKUZBfBoyqy5d3swXyiC7Q76ic40rYcbqH7qjh59kzU= github.com/aws/aws-sdk-go v1.55.5/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU= +github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= +github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bufbuild/protocompile v0.4.0 h1:LbFKd2XowZvQ/kajzguUp2DC9UEIQhIq77fZZlaQsNA= github.com/bufbuild/protocompile v0.4.0/go.mod h1:3v93+mbWn/v3xzN+31nwkJfrEpAUwp+BagBSZWx+TP8= +github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs= +github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= @@ -278,6 +282,9 @@ github.com/cyphar/filepath-securejoin v0.2.4/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxG github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960/go.mod h1:9HQzr9D/0PGwMEbC3d5AB7oi67+h4TsQqItC1GVYG58= +github.com/dprotaso/go-yit v0.0.0-20240618133044-5a0af90af097 h1:f5nA5Ys8RXqFXtKc0XofVRiuwNTuJzPIwTmbjLz9vj8= +github.com/dprotaso/go-yit v0.0.0-20240618133044-5a0af90af097/go.mod h1:FTAVyH6t+SlS97rv6EXRVuBDLkQqcIe/xQw9f4IFUI4= github.com/elazarl/goproxy v0.0.0-20230808193330-2592e75ae04a h1:mATvB/9r/3gvcejNsXKSkQ6lcIaNec2nyfOdlTBR2lU= github.com/elazarl/goproxy v0.0.0-20230808193330-2592e75ae04a/go.mod h1:Ro8st/ElPeALwNFlcTpWmkr6IoMFfkjXAvTHpevnDsM= github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8= @@ -308,6 +315,7 @@ github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= @@ -566,6 +574,7 @@ github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9Y github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a/go.mod h1:UJSiEoRfvx3hP73CvoARgeLjaIOjybY9vj8PUPPFGeU= @@ -590,6 +599,8 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lunixbochs/vtclean v0.0.0-20180621232353-2d01aacdc34a/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/manifoldco/promptui v0.8.0/go.mod h1:n4zTdgP0vr0S3w7/O/g98U+e0gwLScEXGwov2nIKuGQ= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= @@ -637,11 +648,14 @@ github.com/mongodb-forks/digest v1.1.0 h1:7eUdsR1BtqLv0mdNm4OXs6ddWvR4X2/OsLwdKk github.com/mongodb-forks/digest v1.1.0/go.mod h1:rb+EX8zotClD5Dj4NdgxnJXG9nwrlx3NWKJ8xttz1Dg= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= github.com/onsi/ginkgo/v2 v2.1.4/go.mod h1:um6tUpWM/cxCK3/FK8BXqEiUMUwRgSM4JXG47RKZmLU= @@ -657,6 +671,7 @@ github.com/onsi/ginkgo/v2 v2.9.2/go.mod h1:WHcJJG2dIlcCqVfBAwUCrJxSPFb6v4azBwgxe github.com/onsi/ginkgo/v2 v2.9.5/go.mod h1:tvAoo1QUJwNEU2ITftXTpR7R1RbCzoZUOs3RonqW57k= github.com/onsi/ginkgo/v2 v2.9.7/go.mod h1:cxrmXWykAwTwhQsJOPfdIDiJ+l2RYq7U8hFU+M/1uw0= github.com/onsi/ginkgo/v2 v2.11.0/go.mod h1:ZhrRA5XmEE3x3rhlzamx/JJvujdZoJ2uvgI7kR0iZvM= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= @@ -677,6 +692,8 @@ github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI= github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M= github.com/openlyinc/pointy v1.1.2 h1:LywVV2BWC5Sp5v7FoP4bUD+2Yn5k0VNeRbU5vq9jUMY= github.com/openlyinc/pointy v1.1.2/go.mod h1:w2Sytx+0FVuMKn37xpXIAyBNhFNBIJGR/v2m7ik1WtM= +github.com/pb33f/libopenapi v0.18.1 h1:Z2lWZ7A7G1u8gwx8A7IwuLwSToP8m55ZlzAagcLHh2U= +github.com/pb33f/libopenapi v0.18.1/go.mod h1:9ap4lXBHgxGyFwxtOfa+B1C3IQ0rvnqteqjJvJ11oiQ= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pjbgf/sha1cd v0.3.0 h1:4D5XXmUUBUl/xQ6IjCkEAbqXskkq/4O7LmGn0AqMDs4= github.com/pjbgf/sha1cd v0.3.0/go.mod h1:nZ1rrWOcGJ5uZgEEVL1VUM9iRQiZvWdbZjkKyFzPPsI= @@ -696,8 +713,11 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L github.com/rogpeppe/go-charset v0.0.0-20180617210344-2471d30d28b4/go.mod h1:qgYeAmZ5ZIpBWTGllZSQnw97Dj+woV0toclVaRGI8pc= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/sebdah/goldie/v2 v2.5.5 h1:rx1mwF95RxZ3/83sdS4Yp7t2C5TCokvWP4TBRbAyEWY= +github.com/sebdah/goldie/v2 v2.5.5/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= @@ -753,6 +773,10 @@ github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21 github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= +github.com/vmware-labs/yaml-jsonpath v0.3.2 h1:/5QKeCBGdsInyDCyVNLbXyilb61MXGi9NP674f9Hobk= +github.com/vmware-labs/yaml-jsonpath v0.3.2/go.mod h1:U6whw1z03QyqgWdgXxvVnQ90zN1BWz5V+51Ewf8k+rQ= +github.com/wk8/go-ordered-map/v2 v2.1.9-0.20240815153524-6ea36470d1bd h1:dLuIF2kX9c+KknGJUdJi1Il1SDiTSK158/BB9kdgAew= +github.com/wk8/go-ordered-map/v2 v2.1.9-0.20240815153524-6ea36470d1bd/go.mod h1:DbzwytT4g/odXquuOCqroKvtxxldI4nb3nuesHF/Exo= github.com/xanzy/ssh-agent v0.3.0/go.mod h1:3s9xbODqPuuhK9JV1R321M/FlMZSBvE5aY6eAcqrDh0= github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw= @@ -1442,9 +1466,11 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV gopkg.in/cheggaaa/pb.v1 v1.0.27/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME= gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -1452,7 +1478,9 @@ gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20191026110619-0b21df46bc1d/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/tools/codegen/codespec/api_spec.go b/tools/codegen/codespec/api_spec.go new file mode 100644 index 0000000000..cba8c2bdb7 --- /dev/null +++ b/tools/codegen/codespec/api_spec.go @@ -0,0 +1,93 @@ +package codespec + +import ( + "context" + "fmt" + "strconv" + + "github.com/pb33f/libopenapi/datamodel/high/base" + high "github.com/pb33f/libopenapi/datamodel/high/v3" + "github.com/pb33f/libopenapi/orderedmap" +) + +var ( + errSchemaNotFound = fmt.Errorf("schema not found") +) + +// This function only builds the schema from a proxy and returns the basic type and format without handling oneOf, anyOf, allOf, or nullable types. +func BuildSchema(proxy *base.SchemaProxy) (*APISpecSchema, error) { + resp := &APISpecSchema{} + + schema, err := proxy.BuildSchema() + if err != nil { + return nil, fmt.Errorf("failed to build schema from proxy: %w", err) + } + + if len(schema.Type) == 0 { + return nil, fmt.Errorf("invalid schema. no values for schema.Type found") + } + + resp.Type = schema.Type[0] + resp.Schema = schema + + return resp, nil +} + +func getSchemaFromMediaType(mediaTypes *orderedmap.Map[string, *high.MediaType]) (*APISpecSchema, error) { + if mediaTypes == nil { + return nil, errSchemaNotFound + } + + sortedMediaTypes := orderedmap.SortAlpha(mediaTypes) + for pair := range orderedmap.Iterate(context.Background(), sortedMediaTypes) { + mediaType := pair.Value() + if mediaType.Schema != nil { + s, err := BuildSchema(mediaType.Schema) + if err != nil { + return nil, err + } + return s, nil + } + } + + return nil, errSchemaNotFound +} + +func buildSchemaFromRequest(op *high.Operation) (*APISpecSchema, error) { + if op == nil || op.RequestBody == nil || op.RequestBody.Content == nil || op.RequestBody.Content.Len() == 0 { + return nil, errSchemaNotFound + } + + return getSchemaFromMediaType(op.RequestBody.Content) +} + +func buildSchemaFromResponse(op *high.Operation) (*APISpecSchema, error) { + if op == nil || op.Responses == nil || op.Responses.Codes == nil || op.Responses.Codes.Len() == 0 { + return nil, errSchemaNotFound + } + + okResponse, ok := op.Responses.Codes.Get(OASResponseCodeOK) + if ok { + return getSchemaFromMediaType(okResponse.Content) + } + + createdResponse, ok := op.Responses.Codes.Get(OASResponseCodeCreated) + if ok { + return getSchemaFromMediaType(createdResponse.Content) + } + + sortedCodes := orderedmap.SortAlpha(op.Responses.Codes) + for pair := range orderedmap.Iterate(context.Background(), sortedCodes) { + responseCode := pair.Value() + statusCode, err := strconv.Atoi(pair.Key()) + if err != nil { + continue + } + + if statusCode >= 200 && statusCode <= 299 { + return getSchemaFromMediaType(responseCode.Content) + } + } + + return nil, errSchemaNotFound +} diff --git a/tools/codegen/codespec/api_spec_schema.go b/tools/codegen/codespec/api_spec_schema.go new file mode 100644 index 0000000000..c8d0c44f87 --- /dev/null +++ b/tools/codegen/codespec/api_spec_schema.go @@ -0,0 +1,59 @@ +package codespec + +import ( + "slices" + + "github.com/pb33f/libopenapi/datamodel/high/base" + high "github.com/pb33f/libopenapi/datamodel/high/v3" +) + +type APISpecSchema struct { + Schema *base.Schema + Type string +} + +type APISpecResource struct { + Description *string + DeprecationMessage *string + CreateOp *high.Operation + ReadOp *high.Operation + UpdateOp *high.Operation + DeleteOp *high.Operation + CommonParameters []*high.Parameter +} + +func (s *APISpecSchema) GetComputability(name string) ComputedOptionalRequired { + if slices.Contains(s.Schema.Required, name) { + return Required + } + + return Optional +} + +func (s *APISpecSchema) GetDeprecationMessage() *string { + if s.Schema.Deprecated == nil || !(*s.Schema.Deprecated) { + return nil + } + + deprecationMessage := "This attribute has been deprecated" + + return &deprecationMessage +} + +func (s *APISpecSchema) GetDescription() *string { + if s.Schema.Description == "" { + return nil + } + + return &s.Schema.Description +} + +func (s *APISpecSchema) IsSensitive() *bool { + isSensitive := s.Schema.Format == OASFormatPassword + + if !isSensitive { + return nil + } + + return &isSensitive +} diff --git a/tools/codegen/codespec/api_to_provider_spec_mapper.go b/tools/codegen/codespec/api_to_provider_spec_mapper.go new file mode 100644 index 0000000000..12ec3f9e76 --- /dev/null +++ b/tools/codegen/codespec/api_to_provider_spec_mapper.go @@ -0,0 +1,222 @@ +package codespec + +import ( + "errors" + "fmt" + "log" + "strings" + + high "github.com/pb33f/libopenapi/datamodel/high/v3" + low "github.com/pb33f/libopenapi/datamodel/low/v3" + + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/config" + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/openapi" +) + +func ToCodeSpecModel(atlasAdminAPISpecFilePath, configPath string, resourceName *string) (*Model, error) { + apiSpec, err := openapi.ParseAtlasAdminAPI(atlasAdminAPISpecFilePath) + if err != nil { + return nil, fmt.Errorf("unable to parse Atlas Admin API: %v", err) + } + + configModel, err := config.ParseGenConfigYAML(configPath) + if err != nil { + return nil, fmt.Errorf("unable to parse config file: %v", err) + } + + resourceConfigsToIterate := configModel.Resources + if resourceName != nil { // only generate a specific resource + resourceConfigsToIterate = map[string]config.Resource{ + *resourceName: configModel.Resources[*resourceName], + } + } + + var results []Resource + for name, resourceConfig := range resourceConfigsToIterate { + log.Printf("Generating resource: %s", name) + // find resource operations, schemas, etc from OAS + oasResource, err := getAPISpecResource(&apiSpec.Model, &resourceConfig, SnakeCaseString(name)) + if err != nil { + return nil, fmt.Errorf("unable to get APISpecResource schema: %v", err) + } + // map OAS resource model to CodeSpecModel + results = append(results, *apiSpecResourceToCodeSpecModel(oasResource, &resourceConfig, SnakeCaseString(name))) + } + + return &Model{Resources: results}, nil +} + +func apiSpecResourceToCodeSpecModel(oasResource APISpecResource, resourceConfig *config.Resource, name SnakeCaseString) *Resource { + createOp := oasResource.CreateOp + readOp := oasResource.ReadOp + + pathParamAttributes := pathParamsToAttributes(createOp) + createRequestAttributes := opRequestToAttributes(createOp) + createResponseAttributes := opResponseToAttributes(createOp) + readResponseAttributes := opResponseToAttributes(readOp) + + attributes := mergeAttributes(pathParamAttributes, createRequestAttributes, createResponseAttributes, readResponseAttributes) + + schema := &Schema{ + Description: oasResource.Description, + DeprecationMessage: oasResource.DeprecationMessage, + Attributes: attributes, + } + + resource := &Resource{ + Name: name, + Schema: schema, + } + + applyConfigSchemaOptions(resourceConfig, resource) + + return resource +} + +func pathParamsToAttributes(createOp *high.Operation) Attributes { + pathParams := createOp.Parameters + + pathAttributes := Attributes{} + for _, param := range pathParams { + if param.In != OASPathParam { + continue + } + + s, err := BuildSchema(param.Schema) + if err != nil { + continue + } + + paramName := param.Name + s.Schema.Description = param.Description + parameterAttribute, err := s.buildResourceAttr(paramName, Required) + if err != nil { + log.Printf("[WARN] Path param %s could not be mapped: %s", paramName, err) + continue + } + pathAttributes = append(pathAttributes, *parameterAttribute) + } + return pathAttributes +} + +func opRequestToAttributes(op *high.Operation) Attributes { + var requestAttributes Attributes + requestSchema, err := buildSchemaFromRequest(op) + if err != nil { + log.Printf("[WARN] Request schema could not be mapped (OperationId: %s): %s", op.OperationId, err) + return nil + } + + requestAttributes, err = buildResourceAttrs(requestSchema) + if err != nil { + log.Printf("[WARN] Request attributes could not be mapped (OperationId: %s): %s", op.OperationId, err) + return nil + } + + return requestAttributes +} + +func opResponseToAttributes(op *high.Operation) Attributes { + var responseAttributes Attributes + responseSchema, err := buildSchemaFromResponse(op) + if err != nil { + if errors.Is(err, errSchemaNotFound) { + log.Printf("[INFO] Operation response body schema not found (OperationId: %s)", op.OperationId) + } else { + log.Printf("[WARN] Operation response body schema could not be mapped (OperationId: %s): %s", op.OperationId, err) + } + } else { + responseAttributes, err = buildResourceAttrs(responseSchema) + if err != nil { + log.Printf("[WARN] Operation response body schema could not be mapped (OperationId: %s): %s", op.OperationId, err) + } + } + return responseAttributes +} + +func getAPISpecResource(spec *high.Document, resourceConfig *config.Resource, name SnakeCaseString) (APISpecResource, error) { + var errResult error + var resourceDeprecationMsg *string + + createOp, err := extractOp(spec.Paths, resourceConfig.Create) + if err != nil { + errResult = errors.Join(errResult, fmt.Errorf("unable to extract '%s.create' operation: %w", name, err)) + } + readOp, err := extractOp(spec.Paths, resourceConfig.Read) + if err != nil { + errResult = errors.Join(errResult, fmt.Errorf("unable to extract '%s.read' operation: %w", name, err)) + } + updateOp, err := extractOp(spec.Paths, resourceConfig.Update) + if err != nil { + errResult = errors.Join(errResult, fmt.Errorf("unable to extract '%s.update' operation: %w", name, err)) + } + deleteOp, err := extractOp(spec.Paths, resourceConfig.Delete) + if err != nil { + errResult = errors.Join(errResult, fmt.Errorf("unable to extract '%s.delete' operation: %w", name, err)) + } + + commonParameters, err := extractCommonParameters(spec.Paths, resourceConfig.Read.Path) + if err != nil { + errResult = errors.Join(errResult, fmt.Errorf("unable to extract '%s' common parameters: %w", name, err)) + } + + if readOp.Deprecated != nil && *readOp.Deprecated { + resourceDeprecationMsg = conversion.StringPtr(DefaultDeprecationMsg) + } + + return APISpecResource{ + Description: &createOp.Description, + DeprecationMessage: resourceDeprecationMsg, + CreateOp: createOp, + ReadOp: readOp, + UpdateOp: updateOp, + DeleteOp: deleteOp, + CommonParameters: commonParameters, + }, errResult +} + +func extractOp(paths *high.Paths, apiOp *config.APIOperation) (*high.Operation, error) { + if apiOp == nil { + return nil, nil + } + + if paths == nil || paths.PathItems == nil || paths.PathItems.GetOrZero(apiOp.Path) == nil { + return nil, fmt.Errorf("path '%s' not found in OpenAPI spec", apiOp.Path) + } + + pathItem, _ := paths.PathItems.Get(apiOp.Path) + + return extractOpFromPathItem(pathItem, apiOp) +} + +func extractOpFromPathItem(pathItem *high.PathItem, apiOp *config.APIOperation) (*high.Operation, error) { + if pathItem == nil || apiOp == nil { + return nil, fmt.Errorf("pathItem or apiOp cannot be nil") + } + + switch strings.ToLower(apiOp.Method) { + case low.PostLabel: + return pathItem.Post, nil + case low.GetLabel: + return pathItem.Get, nil + case low.PutLabel: + return pathItem.Put, nil + case low.DeleteLabel: + return pathItem.Delete, nil + case low.PatchLabel: + return pathItem.Patch, nil + default: + return nil, fmt.Errorf("method '%s' not found at OpenAPI path '%s'", apiOp.Method, apiOp.Path) + } +} + +func extractCommonParameters(paths *high.Paths, path string) ([]*high.Parameter, error) { + if paths.PathItems.GetOrZero(path) == nil { + return nil, fmt.Errorf("path '%s' not found in OpenAPI spec", path) + } + + pathItem, _ := paths.PathItems.Get(path) + + return pathItem.Parameters, nil +} diff --git a/tools/codegen/codespec/api_to_provider_spec_mapper_test.go b/tools/codegen/codespec/api_to_provider_spec_mapper_test.go new file mode 100644 index 0000000000..6eb7129d87 --- /dev/null +++ b/tools/codegen/codespec/api_to_provider_spec_mapper_test.go @@ -0,0 +1,378 @@ +package codespec_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/codespec" +) + +const ( + testFieldDesc = "Test field description" + testResourceDesc = "POST API description" + testPathParamDesc = "Path param test description" +) + +type convertToSpecTestCase struct { + expectedResult *codespec.Model + inputOpenAPISpecPath string + inputConfigPath string + inputResourceName string +} + +func TestConvertToProviderSpec(t *testing.T) { + testCases := map[string]convertToSpecTestCase{ + "Valid input": { + inputOpenAPISpecPath: "testdata/api-spec.yml", + inputConfigPath: "testdata/config-no-schema-opts.yml", + inputResourceName: "test_resource", + + expectedResult: &codespec.Model{ + Resources: []codespec.Resource{{ + Schema: &codespec.Schema{ + Description: conversion.StringPtr(testResourceDesc), + Attributes: codespec.Attributes{ + { + Name: "bool_default_attr", + ComputedOptionalRequired: codespec.ComputedOptional, + Bool: &codespec.BoolAttribute{Default: conversion.Pointer(false)}, + }, + { + Name: "count", + ComputedOptionalRequired: codespec.Optional, + Int64: &codespec.Int64Attribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "create_date", + String: &codespec.StringAttribute{}, + ComputedOptionalRequired: codespec.Computed, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "group_id", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testPathParamDesc), + }, + { + Name: "num_double_default_attr", + Float64: &codespec.Float64Attribute{Default: conversion.Pointer(2.0)}, + ComputedOptionalRequired: codespec.ComputedOptional, + }, + { + Name: "str_computed_attr", + ComputedOptionalRequired: codespec.Computed, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "str_req_attr1", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "str_req_attr2", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "str_req_attr3", + String: &codespec.StringAttribute{}, + ComputedOptionalRequired: codespec.Required, + Description: conversion.StringPtr(testFieldDesc), + }, + }, + }, + Name: "test_resource", + }, + }, + }, + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + result, err := codespec.ToCodeSpecModel(tc.inputOpenAPISpecPath, tc.inputConfigPath, &tc.inputResourceName) + require.NoError(t, err) + assert.Equal(t, tc.expectedResult, result, "Expected result to match the specified structure") + }) + } +} + +func TestConvertToProviderSpec_nested(t *testing.T) { + testCases := map[string]convertToSpecTestCase{ + "Valid input": { + inputOpenAPISpecPath: "testdata/api-spec.yml", + inputConfigPath: "testdata/config-nested-schema.yml", + inputResourceName: "test_resource_with_nested_attr", + + expectedResult: &codespec.Model{ + Resources: []codespec.Resource{{ + Schema: &codespec.Schema{ + Description: conversion.StringPtr(testResourceDesc), + Attributes: codespec.Attributes{ + { + Name: "cluster_name", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testPathParamDesc), + }, + { + Name: "group_id", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testPathParamDesc), + }, + { + Name: "list_primitive_string_attr", + ComputedOptionalRequired: codespec.Computed, + List: &codespec.ListAttribute{ + ElementType: codespec.String, + }, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "nested_list_array_attr", + ComputedOptionalRequired: codespec.Required, + ListNested: &codespec.ListNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "inner_num_attr", + ComputedOptionalRequired: codespec.Required, + Int64: &codespec.Int64Attribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "list_primitive_string_attr", + ComputedOptionalRequired: codespec.Optional, + List: &codespec.ListAttribute{ + ElementType: codespec.String, + }, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "list_primitive_string_computed_attr", + ComputedOptionalRequired: codespec.Computed, + List: &codespec.ListAttribute{ + ElementType: codespec.String, + }, + Description: conversion.StringPtr(testFieldDesc), + }, + }, + }, + }, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "nested_map_object_attr", + ComputedOptionalRequired: codespec.Computed, + MapNested: &codespec.MapNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "attr", + ComputedOptionalRequired: codespec.Computed, + String: &codespec.StringAttribute{}, + }, + }, + }, + }, + }, + { + Name: "nested_set_array_attr", + ComputedOptionalRequired: codespec.Computed, + SetNested: &codespec.SetNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "inner_num_attr", + ComputedOptionalRequired: codespec.Computed, + Int64: &codespec.Int64Attribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "list_primitive_string_attr", + ComputedOptionalRequired: codespec.Computed, + List: &codespec.ListAttribute{ + ElementType: codespec.String, + }, + Description: conversion.StringPtr(testFieldDesc), + }, + }, + }, + }, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "set_primitive_string_attr", + ComputedOptionalRequired: codespec.Computed, + Set: &codespec.SetAttribute{ + ElementType: codespec.String, + }, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "single_nested_attr", + ComputedOptionalRequired: codespec.Computed, + SingleNested: &codespec.SingleNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "inner_int_attr", + ComputedOptionalRequired: codespec.Computed, + Int64: &codespec.Int64Attribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "inner_str_attr", + ComputedOptionalRequired: codespec.Computed, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + }, + }, + }, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "single_nested_attr_with_nested_maps", + ComputedOptionalRequired: codespec.Computed, + SingleNested: &codespec.SingleNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "map_attr1", + ComputedOptionalRequired: codespec.Computed, + Map: &codespec.MapAttribute{ + ElementType: codespec.String, + }, + }, + { + Name: "map_attr2", + ComputedOptionalRequired: codespec.Computed, + Map: &codespec.MapAttribute{ + ElementType: codespec.String, + }, + }, + }, + }, + }, + Description: conversion.StringPtr(testFieldDesc), + }, + }, + }, + Name: "test_resource_with_nested_attr", + }, + }, + }, + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + result, err := codespec.ToCodeSpecModel(tc.inputOpenAPISpecPath, tc.inputConfigPath, &tc.inputResourceName) + require.NoError(t, err) + assert.Equal(t, tc.expectedResult, result, "Expected result to match the specified structure") + }) + } +} + +func TestConvertToProviderSpec_nested_schemaOverrides(t *testing.T) { + testCases := map[string]convertToSpecTestCase{ + "Valid input": { + inputOpenAPISpecPath: "testdata/api-spec.yml", + inputConfigPath: "testdata/config-nested-schema-overrides.yml", + inputResourceName: "test_resource_with_nested_attr_overrides", + + expectedResult: &codespec.Model{ + Resources: []codespec.Resource{{ + Schema: &codespec.Schema{ + Description: conversion.StringPtr(testResourceDesc), + Attributes: codespec.Attributes{ + { + Name: "project_id", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testPathParamDesc), + }, + { + Name: "nested_list_array_attr", + ComputedOptionalRequired: codespec.Required, + ListNested: &codespec.ListNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "inner_num_attr_alias", + ComputedOptionalRequired: codespec.Required, + Int64: &codespec.Int64Attribute{}, + Description: conversion.StringPtr("Overridden inner_num_attr_alias description"), + }, + { + Name: "list_primitive_string_computed_attr", + ComputedOptionalRequired: codespec.Computed, + List: &codespec.ListAttribute{ + ElementType: codespec.String, + }, + Description: conversion.StringPtr(testFieldDesc), + }, + }, + }, + }, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "outer_object", + ComputedOptionalRequired: codespec.Computed, + SingleNested: &codespec.SingleNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "nested_level1", + ComputedOptionalRequired: codespec.Computed, + SingleNested: &codespec.SingleNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "level_field1_alias", + ComputedOptionalRequired: codespec.Computed, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr("Overridden level_field1_alias description"), + }, + }, + }, + }, + }, + }, + }, + }, + }, + { + Name: "timeouts", + Timeouts: &codespec.TimeoutsAttribute{ + ConfigurableTimeouts: []codespec.Operation{codespec.Create, codespec.Read, codespec.Update, codespec.Delete}, + }, + }, + }, + }, + Name: "test_resource_with_nested_attr_overrides", + }, + }, + }, + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + result, err := codespec.ToCodeSpecModel(tc.inputOpenAPISpecPath, tc.inputConfigPath, &tc.inputResourceName) + require.NoError(t, err) + assert.Equal(t, tc.expectedResult, result, "Expected result to match the specified structure") + }) + } +} diff --git a/tools/codegen/codespec/attribute.go b/tools/codegen/codespec/attribute.go new file mode 100644 index 0000000000..c20b8fbacb --- /dev/null +++ b/tools/codegen/codespec/attribute.go @@ -0,0 +1,272 @@ +package codespec + +import ( + "context" + "fmt" + + "github.com/pb33f/libopenapi/orderedmap" +) + +func buildResourceAttrs(s *APISpecSchema) (Attributes, error) { + objectAttributes := Attributes{} + + sortedProperties := orderedmap.SortAlpha(s.Schema.Properties) + for pair := range orderedmap.Iterate(context.Background(), sortedProperties) { + name := pair.Key() + proxy := pair.Value() + + schema, err := BuildSchema(proxy) + if err != nil { + return nil, err + } + + attribute, err := schema.buildResourceAttr(name, s.GetComputability(name)) + if err != nil { + return nil, err + } + + if attribute != nil { + objectAttributes = append(objectAttributes, *attribute) + } + } + + return objectAttributes, nil +} + +func (s *APISpecSchema) buildResourceAttr(name string, computability ComputedOptionalRequired) (*Attribute, error) { + switch s.Type { + case OASTypeString: + return s.buildStringAttr(name, computability) + case OASTypeInteger: + return s.buildIntegerAttr(name, computability) + case OASTypeNumber: + return s.buildNumberAttr(name, computability) + case OASTypeBoolean: + return s.buildBoolAttr(name, computability) + case OASTypeArray: + return s.buildArrayAttr(name, computability) + case OASTypeObject: + if s.Schema.AdditionalProperties != nil && s.Schema.AdditionalProperties.IsA() { + return s.buildMapAttr(name, computability) + } + return s.buildSingleNestedAttr(name, computability) + default: + return nil, fmt.Errorf("invalid schema type '%s'", s.Type) + } +} + +func (s *APISpecSchema) buildStringAttr(name string, computability ComputedOptionalRequired) (*Attribute, error) { + result := &Attribute{ + Name: terraformAttrName(name), + ComputedOptionalRequired: computability, + DeprecationMessage: s.GetDeprecationMessage(), + Description: s.GetDescription(), + Sensitive: s.IsSensitive(), + String: &StringAttribute{}, + } + + if s.Schema.Default != nil { + var staticDefault string + if err := s.Schema.Default.Decode(&staticDefault); err == nil { + result.ComputedOptionalRequired = ComputedOptional + + result.String.Default = &staticDefault + } + } + + return result, nil +} + +func (s *APISpecSchema) buildIntegerAttr(name string, computability ComputedOptionalRequired) (*Attribute, error) { + result := &Attribute{ + Name: terraformAttrName(name), + ComputedOptionalRequired: computability, + DeprecationMessage: s.GetDeprecationMessage(), + Description: s.GetDescription(), + Int64: &Int64Attribute{}, + } + + if s.Schema.Default != nil { + var staticDefault int64 + if err := s.Schema.Default.Decode(&staticDefault); err == nil { + result.ComputedOptionalRequired = ComputedOptional + + result.Int64.Default = &staticDefault + } + } + + return result, nil +} + +func (s *APISpecSchema) buildNumberAttr(name string, computability ComputedOptionalRequired) (*Attribute, error) { + if s.Schema.Format == OASFormatDouble || s.Schema.Format == OASFormatFloat { + result := &Attribute{ + Name: terraformAttrName(name), + ComputedOptionalRequired: computability, + DeprecationMessage: s.GetDeprecationMessage(), + Description: s.GetDescription(), + Float64: &Float64Attribute{}, + } + + if s.Schema.Default != nil { + var staticDefault float64 + if err := s.Schema.Default.Decode(&staticDefault); err == nil { + result.ComputedOptionalRequired = ComputedOptional + + result.Float64.Default = &staticDefault + } + } + + return result, nil + } + + return &Attribute{ + Name: terraformAttrName(name), + ComputedOptionalRequired: computability, + DeprecationMessage: s.GetDeprecationMessage(), + Description: s.GetDescription(), + Number: &NumberAttribute{}, + }, nil +} + +func (s *APISpecSchema) buildBoolAttr(name string, computability ComputedOptionalRequired) (*Attribute, error) { + result := &Attribute{ + Name: terraformAttrName(name), + ComputedOptionalRequired: computability, + DeprecationMessage: s.GetDeprecationMessage(), + Description: s.GetDescription(), + Bool: &BoolAttribute{}, + } + + if s.Schema.Default != nil { + var staticDefault bool + if err := s.Schema.Default.Decode(&staticDefault); err == nil { + result.ComputedOptionalRequired = ComputedOptional + result.Bool.Default = &staticDefault + } + } + + return result, nil +} + +func (s *APISpecSchema) buildArrayAttr(name string, computability ComputedOptionalRequired) (*Attribute, error) { + if !s.Schema.Items.IsA() { + return nil, fmt.Errorf("invalid array items property, schema doesn't exist: %s", name) + } + + itemSchema, err := BuildSchema(s.Schema.Items.A) + if err != nil { + return nil, fmt.Errorf("error while building nested schema: %s", name) + } + + isSet := s.Schema.Format == OASFormatSet || (s.Schema.UniqueItems != nil && *s.Schema.UniqueItems) + + createAttribute := func(nestedObject *NestedAttributeObject, elemType ElemType) *Attribute { + attr := &Attribute{ + Name: terraformAttrName(name), + ComputedOptionalRequired: computability, + DeprecationMessage: s.GetDeprecationMessage(), + Description: s.GetDescription(), + } + + if nestedObject != nil { + if isSet { + attr.SetNested = &SetNestedAttribute{NestedObject: *nestedObject} + } else { + attr.ListNested = &ListNestedAttribute{NestedObject: *nestedObject} + } + } else { + if isSet { + attr.Set = &SetAttribute{ElementType: elemType} + } else { + attr.List = &ListAttribute{ElementType: elemType} + } + } + + return attr + } + + if itemSchema.Type == OASTypeObject { + objectAttributes, err := buildResourceAttrs(itemSchema) + if err != nil { + return nil, fmt.Errorf("error while building nested schema: %s", name) + } + nestedObject := &NestedAttributeObject{Attributes: objectAttributes} + + return createAttribute(nestedObject, Unknown), nil // Using Unknown ElemType as a placeholder for no ElemType + } + + elemType, err := itemSchema.buildElementType() + if err != nil { + return nil, fmt.Errorf("error while building nested schema: %s", name) + } + + result := createAttribute(nil, elemType) + + if s.Schema.Default != nil { + var staticDefault bool + if err := s.Schema.Default.Decode(&staticDefault); err == nil { + result.ComputedOptionalRequired = ComputedOptional + result.Bool.Default = &staticDefault + } + } + + return result, nil +} + +func (s *APISpecSchema) buildMapAttr(name string, computability ComputedOptionalRequired) (*Attribute, error) { + mapSchema, err := BuildSchema(s.Schema.AdditionalProperties.A) + if err != nil { + return nil, err + } + + result := &Attribute{ + Name: terraformAttrName(name), + ComputedOptionalRequired: computability, + DeprecationMessage: s.GetDeprecationMessage(), + Description: s.GetDescription(), + } + + if mapSchema.Type == OASTypeObject { + mapAttributes, err := buildResourceAttrs(mapSchema) + if err != nil { + return nil, err + } + + result.MapNested = &MapNestedAttribute{ + NestedObject: NestedAttributeObject{ + Attributes: mapAttributes, + }, + } + } else { + elemType, err := mapSchema.buildElementType() + if err != nil { + return nil, err + } + + result.Map = &MapAttribute{ + ElementType: elemType, + } + } + + return result, nil +} + +func (s *APISpecSchema) buildSingleNestedAttr(name string, computability ComputedOptionalRequired) (*Attribute, error) { + objectAttributes, err := buildResourceAttrs(s) + if err != nil { + return nil, err + } + + return &Attribute{ + Name: terraformAttrName(name), + ComputedOptionalRequired: computability, + DeprecationMessage: s.GetDeprecationMessage(), + Description: s.GetDescription(), + SingleNested: &SingleNestedAttribute{ + NestedObject: NestedAttributeObject{ + Attributes: objectAttributes, + }, + }, + }, nil +} diff --git a/tools/codegen/codespec/computability.go b/tools/codegen/codespec/computability.go new file mode 100644 index 0000000000..394d411f82 --- /dev/null +++ b/tools/codegen/codespec/computability.go @@ -0,0 +1,10 @@ +package codespec + +const ( + Computed ComputedOptionalRequired = "computed" + ComputedOptional ComputedOptionalRequired = "computed_optional" + Optional ComputedOptionalRequired = "optional" + Required ComputedOptionalRequired = "required" +) + +type ComputedOptionalRequired string diff --git a/tools/codegen/codespec/config.go b/tools/codegen/codespec/config.go new file mode 100644 index 0000000000..f935472bad --- /dev/null +++ b/tools/codegen/codespec/config.go @@ -0,0 +1,123 @@ +package codespec + +import ( + "log" + "strings" + + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/config" +) + +func applyConfigSchemaOptions(resourceConfig *config.Resource, resource *Resource) { + applySchemaOptions(resourceConfig.SchemaOptions, &resource.Schema.Attributes, "") +} + +func applySchemaOptions(schemaOptions config.SchemaOptions, attributes *Attributes, parentName string) { + ignoredAttrs := getIgnoredAttributesMap(schemaOptions.Ignores) + + var finalAttributes Attributes + + for i := range *attributes { + attr := &(*attributes)[i] + attrPathName := getAttributePathName(string(attr.Name), parentName) + + if shouldIgnoreAttribute(attrPathName, ignoredAttrs) { + continue + } + + // the config is expected to use alias name for defining any subsequent overrides (description, etc) + applyAlias(attr, &attrPathName, schemaOptions) + + applyOverrides(attr, attrPathName, schemaOptions) + + processNestedAttributes(attr, schemaOptions, attrPathName) + + finalAttributes = append(finalAttributes, *attr) + } + + if timeoutAttr := applyTimeoutConfig(schemaOptions); parentName == "" && timeoutAttr != nil { // will not run for nested attributes + finalAttributes = append(finalAttributes, *timeoutAttr) + } + + *attributes = finalAttributes +} + +func getAttributePathName(attrName, parentName string) string { + if parentName == "" { + return attrName + } + return parentName + "." + attrName +} + +func getIgnoredAttributesMap(ignores []string) map[string]bool { + ignoredAttrs := make(map[string]bool) + for _, ignoredAttr := range ignores { + ignoredAttrs[ignoredAttr] = true + } + return ignoredAttrs +} + +func shouldIgnoreAttribute(attrName string, ignoredAttrs map[string]bool) bool { + return ignoredAttrs[attrName] +} + +func applyAlias(attr *Attribute, attrPathName *string, schemaOptions config.SchemaOptions) { + parts := strings.Split(*attrPathName, ".") + + for i := range parts { + currentPath := strings.Join(parts[:i+1], ".") + + if newName, ok := schemaOptions.Aliases[currentPath]; ok { + parts[i] = newName + + if i == len(parts)-1 { + attr.Name = SnakeCaseString(newName) + } + } + } + + *attrPathName = strings.Join(parts, ".") +} + +func applyOverrides(attr *Attribute, attrPathName string, schemaOptions config.SchemaOptions) { + if override, ok := schemaOptions.Overrides[attrPathName]; ok { + attr.Description = &override.Description + } +} + +func processNestedAttributes(attr *Attribute, schemaOptions config.SchemaOptions, attrPathName string) { + switch { + case attr.ListNested != nil: + applySchemaOptions(schemaOptions, &attr.ListNested.NestedObject.Attributes, attrPathName) + case attr.SingleNested != nil: + applySchemaOptions(schemaOptions, &attr.SingleNested.NestedObject.Attributes, attrPathName) + case attr.SetNested != nil: + applySchemaOptions(schemaOptions, &attr.SetNested.NestedObject.Attributes, attrPathName) + case attr.MapNested != nil: + applySchemaOptions(schemaOptions, &attr.MapNested.NestedObject.Attributes, attrPathName) + } +} + +func applyTimeoutConfig(options config.SchemaOptions) *Attribute { + var result []Operation + for _, op := range options.Timeouts { + switch op { + case "create": + result = append(result, Create) + case "read": + result = append(result, Read) + case "delete": + result = append(result, Delete) + case "update": + result = append(result, Update) + default: + log.Printf("[WARN] Unknown operation type defined in timeout configuration: %s", op) + } + } + if result != nil { + return &Attribute{ + Name: "timeouts", + Timeouts: &TimeoutsAttribute{ConfigurableTimeouts: result}, + } + } + return nil +} diff --git a/tools/codegen/codespec/constants.go b/tools/codegen/codespec/constants.go new file mode 100644 index 0000000000..cd41c1b8c0 --- /dev/null +++ b/tools/codegen/codespec/constants.go @@ -0,0 +1,21 @@ +package codespec + +const ( + OASTypeString = "string" + OASTypeInteger = "integer" + OASTypeNumber = "number" + OASTypeBoolean = "boolean" + OASTypeArray = "array" + OASTypeObject = "object" + OASFormatDouble = "double" + OASFormatFloat = "float" + OASFormatPassword = "password" + OASFormatSet = "set" + + OASResponseCodeOK = "200" + OASResponseCodeCreated = "201" + + OASPathParam = "path" + + DefaultDeprecationMsg = "This resource has been deprecated" +) diff --git a/tools/codegen/codespec/element_type.go b/tools/codegen/codespec/element_type.go new file mode 100644 index 0000000000..1546786211 --- /dev/null +++ b/tools/codegen/codespec/element_type.go @@ -0,0 +1,20 @@ +package codespec + +import "fmt" + +func (s *APISpecSchema) buildElementType() (ElemType, error) { + switch s.Type { + case OASTypeString: + return String, nil + case OASTypeBoolean: + return Bool, nil + case OASTypeInteger: + return Int64, nil + case OASTypeNumber: + return Number, nil + case OASTypeArray, OASTypeObject: + return String, nil // complex element types are unsupported so this defaults to string for now to provide best effort generation + default: + return Unknown, fmt.Errorf("invalid schema type '%s'", s.Type) + } +} diff --git a/tools/codegen/codespec/merge_attributes.go b/tools/codegen/codespec/merge_attributes.go new file mode 100644 index 0000000000..7d129eada3 --- /dev/null +++ b/tools/codegen/codespec/merge_attributes.go @@ -0,0 +1,158 @@ +package codespec + +import ( + "sort" +) + +// mergeNestedAttributes recursively merges nested attributes +func mergeNestedAttributes(existingAttrs *Attributes, newAttrs Attributes, computability ComputedOptionalRequired, isFromResponse bool) { + mergedMap := make(map[string]*Attribute) + if existingAttrs != nil { + for i := range *existingAttrs { + mergedMap[(*existingAttrs)[i].Name.SnakeCase()] = &(*existingAttrs)[i] + } + } + + // add new attributes and merge when necessary + for i := range newAttrs { + newAttr := &newAttrs[i] + + if _, exists := mergedMap[newAttr.Name.SnakeCase()]; exists { + addOrUpdate(newAttr, computability, mergedMap, isFromResponse) + } else { + newAttr.ComputedOptionalRequired = computability + mergedMap[newAttr.Name.SnakeCase()] = newAttr + } + } + + // update original existingAttrs with the merged result + *existingAttrs = make(Attributes, 0, len(mergedMap)) + for _, attr := range mergedMap { + *existingAttrs = append(*existingAttrs, *attr) + } + + sortAttributes(*existingAttrs) +} + +// addOrUpdate adds or updates an attribute in the merged map, including nested attributes +func addOrUpdate(attr *Attribute, computability ComputedOptionalRequired, merged map[string]*Attribute, isFromResponse bool) { + if existingAttr, exists := merged[attr.Name.SnakeCase()]; exists { + if existingAttr.Description == nil || *existingAttr.Description == "" { + existingAttr.Description = attr.Description + } + + // retain computability if already set from request + if !isFromResponse && existingAttr.ComputedOptionalRequired != Required { + existingAttr.ComputedOptionalRequired = computability + } + + // handle nested attributes + if existingAttr.ListNested != nil && attr.ListNested != nil { + mergeNestedAttributes(&existingAttr.ListNested.NestedObject.Attributes, attr.ListNested.NestedObject.Attributes, computability, isFromResponse) + } else if attr.ListNested != nil { + existingAttr.ListNested = attr.ListNested + } + + if existingAttr.SingleNested != nil && attr.SingleNested != nil { + mergeNestedAttributes(&existingAttr.SingleNested.NestedObject.Attributes, attr.SingleNested.NestedObject.Attributes, computability, isFromResponse) + } else if attr.SingleNested != nil { + existingAttr.SingleNested = attr.SingleNested + } + + if existingAttr.SetNested != nil && attr.SetNested != nil { + mergeNestedAttributes(&existingAttr.SetNested.NestedObject.Attributes, attr.SetNested.NestedObject.Attributes, computability, isFromResponse) + } else if attr.SetNested != nil { + existingAttr.SetNested = attr.SetNested + } + + if existingAttr.MapNested != nil && attr.MapNested != nil { + mergeNestedAttributes(&existingAttr.MapNested.NestedObject.Attributes, attr.MapNested.NestedObject.Attributes, computability, isFromResponse) + } else if attr.MapNested != nil { + existingAttr.MapNested = attr.MapNested + } + } else { + // add new attribute with the given computability + newAttr := *attr + newAttr.ComputedOptionalRequired = computability + merged[attr.Name.SnakeCase()] = &newAttr + } +} + +func mergeAttributes(pathParams, createRequest, createResponse, readResponse Attributes) Attributes { + merged := make(map[string]*Attribute) + + // Path parameters: all attributes will be "required" + for i := range pathParams { + addOrUpdate(&pathParams[i], Required, merged, false) + } + + // POST request body: optional/required is as defined + for i := range createRequest { + addOrUpdate(&createRequest[i], createRequest[i].ComputedOptionalRequired, merged, false) + } + + // POST/GET response body: properties not in the request body are "computed" or "computed_optional" (if a default is present) + for i := range createResponse { + if hasDefault(&createResponse[i]) { + addOrUpdate(&createResponse[i], ComputedOptional, merged, true) + } else { + addOrUpdate(&createResponse[i], Computed, merged, true) + } + } + + for i := range readResponse { + if hasDefault(&readResponse[i]) { + addOrUpdate(&readResponse[i], ComputedOptional, merged, true) + } else { + addOrUpdate(&readResponse[i], Computed, merged, true) + } + } + + resourceAttributes := make(Attributes, 0, len(merged)) + for _, attr := range merged { + resourceAttributes = append(resourceAttributes, *attr) + } + + sortAttributes(resourceAttributes) + + updateNestedComputability(&resourceAttributes, Optional) + + return resourceAttributes +} + +func updateNestedComputability(attrs *Attributes, parentComputability ComputedOptionalRequired) { + for i := range *attrs { + attr := &(*attrs)[i] + + if parentComputability == Computed { + attr.ComputedOptionalRequired = Computed + } + + if attr.ListNested != nil { + updateNestedComputability(&attr.ListNested.NestedObject.Attributes, attr.ComputedOptionalRequired) + } + if attr.SingleNested != nil { + updateNestedComputability(&attr.SingleNested.NestedObject.Attributes, attr.ComputedOptionalRequired) + } + if attr.SetNested != nil { + updateNestedComputability(&attr.SetNested.NestedObject.Attributes, attr.ComputedOptionalRequired) + } + if attr.MapNested != nil { + updateNestedComputability(&attr.MapNested.NestedObject.Attributes, attr.ComputedOptionalRequired) + } + } +} + +func hasDefault(attr *Attribute) bool { + return (attr.Bool != nil && attr.Bool.Default != nil) || + (attr.Int64 != nil && attr.Int64.Default != nil) || + (attr.String != nil && attr.String.Default != nil) || + (attr.Float64 != nil && attr.Float64.Default != nil) || + (attr.Number != nil && attr.Number.Default != nil) +} + +func sortAttributes(attrs Attributes) { + sort.Slice(attrs, func(i, j int) bool { + return attrs[i].Name < attrs[j].Name + }) +} diff --git a/tools/codegen/codespec/model.go b/tools/codegen/codespec/model.go new file mode 100644 index 0000000000..ac86367ca1 --- /dev/null +++ b/tools/codegen/codespec/model.go @@ -0,0 +1,119 @@ +package codespec + +type ElemType int + +const ( + Bool ElemType = iota + Float64 + Int64 + Number + String + Unknown +) + +type Model struct { + Resources []Resource +} + +type Resource struct { + Schema *Schema + Name SnakeCaseString +} + +type Schema struct { + Description *string + DeprecationMessage *string + + Attributes Attributes +} + +type Attributes []Attribute + +type Attribute struct { + List *ListAttribute + SetNested *SetNestedAttribute + + Float64 *Float64Attribute + String *StringAttribute + + Bool *BoolAttribute + ListNested *ListNestedAttribute + Map *MapAttribute + MapNested *MapNestedAttribute + Number *NumberAttribute + Set *SetAttribute + Int64 *Int64Attribute + SingleNested *SingleNestedAttribute + Timeouts *TimeoutsAttribute + + Description *string + Name SnakeCaseString + DeprecationMessage *string + Sensitive *bool + ComputedOptionalRequired ComputedOptionalRequired +} + +type BoolAttribute struct { + Default *bool +} +type Float64Attribute struct { + Default *float64 +} +type Int64Attribute struct { + Default *int64 +} +type MapAttribute struct { + Default *CustomDefault + ElementType ElemType +} +type MapNestedAttribute struct { + Default *CustomDefault + NestedObject NestedAttributeObject +} +type NumberAttribute struct { + Default *CustomDefault +} +type SetAttribute struct { + Default *CustomDefault + ElementType ElemType +} +type SetNestedAttribute struct { + Default *CustomDefault + NestedObject NestedAttributeObject +} +type SingleNestedAttribute struct { + Default *CustomDefault + NestedObject NestedAttributeObject +} +type StringAttribute struct { + Default *string +} +type ListAttribute struct { + Default *CustomDefault + ElementType ElemType +} +type ListNestedAttribute struct { + Default *CustomDefault + NestedObject NestedAttributeObject +} +type NestedAttributeObject struct { + Attributes Attributes +} + +type TimeoutsAttribute struct { + ConfigurableTimeouts []Operation +} + +type Operation int + +const ( + Create Operation = iota + Update + Read + Delete +) + +type CustomDefault struct { + Definition string + Imports []string +} diff --git a/tools/codegen/codespec/string_case.go b/tools/codegen/codespec/string_case.go new file mode 100644 index 0000000000..d079e2d485 --- /dev/null +++ b/tools/codegen/codespec/string_case.go @@ -0,0 +1,21 @@ +package codespec + +import ( + "strings" + + "github.com/huandu/xstrings" +) + +type SnakeCaseString string + +func (snake SnakeCaseString) SnakeCase() string { + return string(snake) +} + +func (snake SnakeCaseString) PascalCase() string { + return xstrings.ToCamelCase(string(snake)) // in xstrings v1.15.0 we can switch to using ToPascalCase for same functionality +} + +func (snake SnakeCaseString) LowerCaseNoUnderscore() string { + return strings.ReplaceAll(string(snake), "_", "") +} diff --git a/tools/codegen/codespec/terraform_helper.go b/tools/codegen/codespec/terraform_helper.go new file mode 100644 index 0000000000..84e764f82c --- /dev/null +++ b/tools/codegen/codespec/terraform_helper.go @@ -0,0 +1,28 @@ +package codespec + +import ( + "fmt" + "regexp" + "strings" +) + +var ( + camelCase = regexp.MustCompile(`([a-z])[A-Z]`) + unsupportedCharacters = regexp.MustCompile(`[^a-zA-Z0-9_]+`) +) + +func terraformAttrName(attrName string) SnakeCaseString { + if attrName == "" { + return SnakeCaseString(attrName) + } + + removedUnsupported := unsupportedCharacters.ReplaceAllString(attrName, "") + + insertedUnderscores := camelCase.ReplaceAllStringFunc(removedUnsupported, func(s string) string { + firstChar := s[0] + restOfString := s[1:] + return fmt.Sprintf("%c_%s", firstChar, strings.ToLower(restOfString)) + }) + + return SnakeCaseString(strings.ToLower(insertedUnderscores)) +} diff --git a/tools/codegen/codespec/testdata/api-spec.yml b/tools/codegen/codespec/testdata/api-spec.yml new file mode 100644 index 0000000000..42eda820a7 --- /dev/null +++ b/tools/codegen/codespec/testdata/api-spec.yml @@ -0,0 +1,465 @@ +openapi: 3.0.1 +info: + description: >- + The MongoDB Atlas Administration API allows developers to manage all + components in MongoDB Atlas. + + + The Atlas Administration API uses HTTP Digest Authentication to authenticate requests. Provide a programmatic API public key and corresponding private key as the username and password when constructing the HTTP request. For example, to [return database access history](#tag/Access-Tracking/operation/listAccessLogsByClusterName) with [cURL](https://en.wikipedia.org/wiki/CURL), run the following command in the terminal: + + + ``` + + curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" \ + --digest \ + --header "Accept: application/vnd.atlas.2024-08-05+json" \ + -X GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/dbAccessHistory/clusters/{clusterName}?pretty=true" + ``` + + + To learn more, see [Get Started with the Atlas Administration API](https://www.mongodb.com/docs/atlas/configure-api-access/). For support, see [MongoDB Support](https://www.mongodb.com/support/get-started). + + + You can also explore the various endpoints available through the Atlas Administration API in MongoDB's [Postman workspace](https://www.postman.com/mongodb-devrel/workspace/mongodb-atlas-administration-apis/). + license: + name: CC BY-NC-SA 3.0 US + url: https://creativecommons.org/licenses/by-nc-sa/3.0/us/ + termsOfService: https://www.mongodb.com/mongodb-management-service-terms-and-conditions + title: MongoDB Atlas Administration API + version: "2.0" + x-xgen-sha: 991036ecf95ec6855a39cd80bd2a15a90e012e7d +servers: + - url: https://cloud.mongodb.com +tags: + - description: Test Resource root description. + name: Test Resource +paths: + "/api/atlas/v2/groups/{groupId}/testResource": + delete: + description: DELETE API description + operationId: deleteTestResourceConfiguration + parameters: + - $ref: "#/components/parameters/groupId" + responses: + "200": + content: + application/vnd.atlas.2023-01-01+json: + x-xgen-version: 2023-01-01 + description: OK + security: + - DigestAuth: [] + summary: Disable the Test Resource feature for a project. + tags: + - Test Resource + get: + description: GET API description + operationId: getTestResourceConfiguration + parameters: + - $ref: "#/components/parameters/groupId" + responses: + "200": + content: + application/vnd.atlas.2023-01-01+json: + schema: + $ref: "#/components/schemas/TestResource" + x-xgen-version: 2023-01-01 + description: OK + security: + - DigestAuth: [] + summary: Get the Test Resource configuration for a project + tags: + - Test Resource + patch: + description: PATCH API description + operationId: updateTestResourceConfiguration + parameters: + - $ref: "#/components/parameters/groupId" + requestBody: + content: + application/vnd.atlas.2023-01-01+json: + schema: + $ref: "#/components/schemas/TestResource" + x-xgen-version: 2023-01-01 + description: Patch request description + required: true + responses: + "200": + content: + application/vnd.atlas.2023-01-01+json: + x-xgen-version: 2023-01-01 + description: OK + security: + - DigestAuth: [] + summary: Update the Test Resource feature for a project + tags: + - Test Resource + post: + description: POST API description + operationId: createTestResourceConfiguration + parameters: + - $ref: "#/components/parameters/groupId" + requestBody: + content: + application/vnd.atlas.2023-01-01+json: + schema: + $ref: "#/components/schemas/CreateTestResourceRequest" + x-xgen-version: 2023-01-01 + description: Create request description + required: true + responses: + "200": + content: + application/vnd.atlas.2023-01-01+json: + x-xgen-version: 2023-01-01 + description: OK + security: + - DigestAuth: [] + summary: Enable the Test Resource feature for a project + tags: + - Test Resource + "/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/nestedTestResource": + delete: + description: DELETE API description + operationId: deleteNestedTestResource + parameters: + - $ref: "#/components/parameters/groupId" + - description: Path param test description + in: path + name: clusterName + required: true + schema: + type: string + maxLength: 64 + minLength: 1 + pattern: ^([a-zA-Z0-9][a-zA-Z0-9-]*)?[a-zA-Z0-9]+$ + responses: + "204": + content: + application/vnd.atlas.2024-05-30+json: + schema: + $ref: "#/components/schemas/NoBody" + x-xgen-version: 2024-05-30 + description: This endpoint does not return a response body. + security: + - DigestAuth: [] + summary: Delete Search Nodes + tags: + - Atlas Search + get: + description: GET API description + operationId: getNestedTestResource + parameters: + - $ref: "#/components/parameters/groupId" + - description: Path param test description + in: path + name: clusterName + required: true + schema: + type: string + maxLength: 64 + minLength: 1 + pattern: ^([a-zA-Z0-9][a-zA-Z0-9-]*)?[a-zA-Z0-9]+$ + responses: + "200": + content: + application/vnd.atlas.2024-05-30+json: + schema: + $ref: "#/components/schemas/NestedTestResourceResponse" + x-xgen-version: 2024-05-30 + description: OK + security: + - DigestAuth: [] + summary: Return Search Nodes + tags: + - Atlas Search + patch: + description: PATCH API description + operationId: updateNestedTestResource + parameters: + - $ref: "#/components/parameters/groupId" + - description: Path param test description + in: path + name: clusterName + required: true + schema: + type: string + maxLength: 64 + minLength: 1 + pattern: ^([a-zA-Z0-9][a-zA-Z0-9-]*)?[a-zA-Z0-9]+$ + requestBody: + content: + application/vnd.atlas.2024-05-30+json: + schema: + $ref: "#/components/schemas/NestedTestResourceRequest" + description: Updates the Search Nodes for the specified cluster. + required: true + responses: + "200": + content: + application/vnd.atlas.2024-05-30+json: + schema: + $ref: "#/components/schemas/NestedTestResourceResponse" + x-xgen-version: 2024-05-30 + description: OK + security: + - DigestAuth: [] + summary: Update Search Nodes + tags: + - Atlas Search + post: + description: POST API description + operationId: createNestedTestResource + parameters: + - $ref: "#/components/parameters/groupId" + - description: Path param test description + in: path + name: clusterName + required: true + schema: + type: string + maxLength: 64 + minLength: 1 + pattern: ^([a-zA-Z0-9][a-zA-Z0-9-]*)?[a-zA-Z0-9]+$ + requestBody: + content: + application/vnd.atlas.2024-05-30+json: + schema: + $ref: "#/components/schemas/NestedTestResourceRequest" + description: Creates Search Nodes for the specified cluster. + required: true + responses: + "201": + content: + application/vnd.atlas.2024-05-30+json: + schema: + $ref: "#/components/schemas/NestedTestResourceResponse" + x-xgen-version: 2024-05-30 + description: Created + security: + - DigestAuth: [] + summary: Create Nested Test Resource + tags: + - Atlas Search +components: + parameters: + groupId: + description: >- + Path param test description + in: path + name: groupId + required: true + schema: + type: string + example: 32b6e34b3d91647abb20e7b8 + maxLength: 24 + minLength: 24 + pattern: ^([a-f0-9]{24})$ + responses: + accepted: + description: Accepted. + schemas: + CreateTestResourceRequest: + type: object + properties: + strReqAttr1: + type: string + description: Test field description + strReqAttr2: + type: string + description: Test field description + strReqAttr3: + type: string + description: Test field description + boolDefaultAttr: + type: boolean + default: false + count: + type: integer + format: int32 + description: Test field description + numDoubleDefaultAttr: + type: number + format: double + default: 2.0 + required: + - strReqAttr1 + - strReqAttr2 + - strReqAttr3 + TestResource: + type: object + properties: + strReqAttr1: + type: string + description: Test field description + createDate: + type: string + format: date-time + description: Test field description + readOnly: true + strReqAttr2: + type: string + description: Test field description + strReqAttr3: + type: string + description: Test field description + strComputedAttr: + type: string + description: Test field description + readOnly: true + boolDefaultAttr: + type: boolean + default: false + count: + type: integer + format: int32 + description: Test field description + numDoubleDefaultAttr: + type: number + format: double + default: 2.0 + NestedTestResourceResponse: + type: object + properties: + groupId: + type: string + description: Path param test description + example: 32b6e34b3d91647abb20e7b8 + maxLength: 24 + minLength: 24 + pattern: ^([a-f0-9]{24})$ + readOnly: true + nestedListArrayAttr: + type: array + description: Test field description + items: + type: object + properties: + innerNumAttr: + type: integer + format: int32 + description: Test field description + example: 2 + maximum: 32 + minimum: 2 + listPrimitiveStringAttr: + type: array + description: Test field description + items: + type: string + listPrimitiveStringComputedAttr: + type: array + description: Test field description + items: + type: string + required: + - innerNumAttr + readOnly: true + nestedSetArrayAttr: + type: array + description: Test field description + items: + $ref: "#/components/schemas/NestedObjectAttr" + readOnly: true + uniqueItems: true + outerObject: + $ref: "#/components/schemas/OuterObject" + setPrimitiveStringAttr: + type: array + description: Test field description + items: + type: string + uniqueItems: true + listPrimitiveStringAttr: + type: array + description: Test field description + items: + type: string + singleNestedAttrWithNestedMaps: + $ref: "#/components/schemas/SingleNestedAttrWithNestedMaps" + singleNestedAttr: + $ref: "#/components/schemas/SingleNestedAttr" + nestedMapObjectAttr: + $ref: "#/components/schemas/NestedMapObjectAttr" + SingleNestedAttrWithNestedMaps: + type: object + description: Test field description + properties: + mapAttr1: + type: object + additionalProperties: + type: string + readOnly: true + readOnly: true + mapAttr2: + type: object + additionalProperties: + type: string + readOnly: true + readOnly: true + readOnly: true + title: Outbound Control Plane IP Addresses By Cloud Provider + SingleNestedAttr: + type: object + description: Test field description + properties: + innerIntAttr: + type: integer + description: Test field description + innerStrAttr: + $ref: "#/components/schemas/SimpleStringRefObject" + required: + - innerIntAttr + - innerStrAttr + NestedObjectAttr: + type: object + properties: + innerNumAttr: + type: integer + format: int32 + description: Test field description + example: 2 + maximum: 32 + minimum: 2 + listPrimitiveStringAttr: + type: array + description: Test field description + items: + type: string + required: + - innerNumAttr + NestedTestResourceRequest: + type: object + properties: + nestedListArrayAttr: + type: array + description: Test field description + items: + $ref: "#/components/schemas/NestedObjectAttr" + maxItems: 1 + minItems: 1 + required: + - nestedListArrayAttr + SimpleStringRefObject: + type: string + description: Test field description + NoBody: + type: object + description: Endpoint does not return a response body. + NestedMapObjectAttr: + type: object + additionalProperties: + type: object + properties: + attr: + type: string + OuterObject: + type: object + properties: + nestedLevel1: + $ref: '#/components/schemas/NestedLevel1Object' + NestedLevel1Object: + type: object + properties: + levelField1: + type: string + diff --git a/tools/codegen/codespec/testdata/config-nested-schema-overrides.yml b/tools/codegen/codespec/testdata/config-nested-schema-overrides.yml new file mode 100644 index 0000000000..95b2f7a9ee --- /dev/null +++ b/tools/codegen/codespec/testdata/config-nested-schema-overrides.yml @@ -0,0 +1,28 @@ +resources: + test_resource_with_nested_attr_overrides: + read: + path: /api/atlas/v2/groups/{groupId}/clusters/{clusterName}/nestedTestResource + method: GET + create: + path: /api/atlas/v2/groups/{groupId}/clusters/{clusterName}/nestedTestResource + method: POST + update: + path: /api/atlas/v2/groups/{groupId}/clusters/{clusterName}/nestedTestResource + method: PATCH + delete: + path: /api/atlas/v2/groups/{groupId}/clusters/{clusterName}/nestedTestResource + method: DELETE + schema: + aliases: + group_id: project_id + nested_list_array_attr.inner_num_attr: inner_num_attr_alias + outer_object.nested_level1.level_field1: level_field1_alias + + ignores: ["nested_list_array_attr.list_primitive_string_attr", "cluster_name", "list_primitive_string_attr", "nested_map_object_attr", "nested_set_array_attr","set_primitive_string_attr", "single_nested_attr", "single_nested_attr_with_nested_maps"] + + overrides: + nested_list_array_attr.inner_num_attr_alias: + description: "Overridden inner_num_attr_alias description" + outer_object.nested_level1.level_field1_alias: + description: "Overridden level_field1_alias description" + timeouts: ["create", "read", "update", "delete"] diff --git a/tools/codegen/codespec/testdata/config-nested-schema.yml b/tools/codegen/codespec/testdata/config-nested-schema.yml new file mode 100644 index 0000000000..54f4d80ee7 --- /dev/null +++ b/tools/codegen/codespec/testdata/config-nested-schema.yml @@ -0,0 +1,16 @@ +resources: + test_resource_with_nested_attr: + read: + path: /api/atlas/v2/groups/{groupId}/clusters/{clusterName}/nestedTestResource + method: GET + create: + path: /api/atlas/v2/groups/{groupId}/clusters/{clusterName}/nestedTestResource + method: POST + update: + path: /api/atlas/v2/groups/{groupId}/clusters/{clusterName}/nestedTestResource + method: PATCH + delete: + path: /api/atlas/v2/groups/{groupId}/clusters/{clusterName}/nestedTestResource + method: DELETE + schema: + ignores: ["outer_object"] \ No newline at end of file diff --git a/tools/codegen/codespec/testdata/config-no-schema-opts.yml b/tools/codegen/codespec/testdata/config-no-schema-opts.yml new file mode 100644 index 0000000000..5a9921e8d5 --- /dev/null +++ b/tools/codegen/codespec/testdata/config-no-schema-opts.yml @@ -0,0 +1,14 @@ +resources: + test_resource: + read: + path: /api/atlas/v2/groups/{groupId}/testResource + method: GET + create: + path: /api/atlas/v2/groups/{groupId}/testResource + method: POST + update: + path: /api/atlas/v2/groups/{groupId}/testResource + method: PATCH + delete: + path: /api/atlas/v2/groups/{groupId}/testResource + method: DELETE diff --git a/tools/codegen/codespec/testdata/config.yml b/tools/codegen/codespec/testdata/config.yml new file mode 100644 index 0000000000..661116eb9a --- /dev/null +++ b/tools/codegen/codespec/testdata/config.yml @@ -0,0 +1,36 @@ +resources: + test_resource: + read: + path: /api/atlas/v2/groups/{groupId}/testResource + method: GET + create: + path: /api/atlas/v2/groups/{groupId}/testResource + method: POST + schema: + aliases: + group_id: project_id + + ignores: ["links"] + + overrides: + project_id: + description: "Overridden project_id description" + default: "defaultProjectId" + plan_modifiers: [{ + imports: [ "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" ], + definition: "stringplanmodifier.RequiresReplace()" + }] + validators: [{ + imports: [ + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator", + "github.com/hashicorp/terraform-plugin-framework/path" + ], + definition: "stringvalidator.ConflictsWith(path.MatchRoot(\"name\"))" + }] + + prefix_path: + computability: + optional: true + computed: true + + timeouts: ["create", "read", "delete"] diff --git a/tools/codegen/config.yml b/tools/codegen/config.yml new file mode 100644 index 0000000000..fcd9a73079 --- /dev/null +++ b/tools/codegen/config.yml @@ -0,0 +1,45 @@ +resources: + push_based_log_export: + read: + path: /api/atlas/v2/groups/{groupId}/pushBasedLogExport + method: GET + create: + path: /api/atlas/v2/groups/{groupId}/pushBasedLogExport + method: POST + schema: + aliases: + group_id: project_id + ignores: ["links"] + timeouts: ["create", "update", "delete"] + + # overrides: + # project_id: + # plan_modifiers: [{ + # imports: [ "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" ], + # definition: "stringplanmodifier.RequiresReplace()" + # }] + # validators: [{ + # imports: [ + # "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator", + # "github.com/hashicorp/terraform-plugin-framework/path" + # ], + # definition: "stringvalidator.ConflictsWith(path.MatchRoot(\"name\"))" + # }] + + # prefix_path: + # computability: + # optional: true + # computed: true + + search_deployment: + read: + path: /api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/deployment + method: GET + create: + path: /api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/deployment + method: POST + schema: + aliases: + group_id: project_id + ignores: ["links"] + timeouts: ["create", "update", "delete"] diff --git a/tools/codegen/config/config_model.go b/tools/codegen/config/config_model.go new file mode 100644 index 0000000000..322fc44962 --- /dev/null +++ b/tools/codegen/config/config_model.go @@ -0,0 +1,48 @@ +package config + +type Config struct { + Resources map[string]Resource `yaml:"resources"` +} + +type Resource struct { + Create *APIOperation `yaml:"create"` + Read *APIOperation `yaml:"read"` + Update *APIOperation `yaml:"update"` + Delete *APIOperation `yaml:"delete"` + SchemaOptions SchemaOptions `yaml:"schema"` +} + +type APIOperation struct { + Path string `yaml:"path"` + Method string `yaml:"method"` +} + +type SchemaOptions struct { + Ignores []string `yaml:"ignores"` + Aliases map[string]string `yaml:"aliases"` + Overrides map[string]Override `yaml:"overrides"` + Timeouts []string `yaml:"timeouts"` +} + +type Override struct { + Description string `yaml:"description"` + PlanModifiers []PlanModifier `yaml:"plan_modifiers"` + Validators []Validator `yaml:"validators"` + Computability Computability `yaml:"computability"` +} + +type PlanModifier struct { + Definition string `yaml:"definition"` + Imports []string `yaml:"imports"` +} + +type Validator struct { + Definition string `yaml:"definition"` + Imports []string `yaml:"imports"` +} + +type Computability struct { + Optional bool `yaml:"optional"` + Computed bool `yaml:"computed"` + Required bool `yaml:"required"` +} diff --git a/tools/codegen/config/parser.go b/tools/codegen/config/parser.go new file mode 100644 index 0000000000..73495b10f9 --- /dev/null +++ b/tools/codegen/config/parser.go @@ -0,0 +1,22 @@ +package config + +import ( + "os" + + "gopkg.in/yaml.v3" +) + +func ParseGenConfigYAML(path string) (*Config, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + + var config Config + err = yaml.Unmarshal(data, &config) + if err != nil { + return nil, err + } + + return &config, nil +} diff --git a/tools/codegen/main.go b/tools/codegen/main.go new file mode 100644 index 0000000000..f45e2e3c98 --- /dev/null +++ b/tools/codegen/main.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" + "log" + "os" + + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/codespec" + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/openapi" + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/schema" +) + +const ( + atlasAdminAPISpecURL = "https://raw.githubusercontent.com/mongodb/atlas-sdk-go/main/openapi/atlas-api-transformed.yaml" + configPath = "tools/codegen/config.yml" + specFilePath = "tools/codegen/open-api-spec.yml" +) + +func main() { + resourceName := getOsArg() + + if err := openapi.DownloadOpenAPISpec(atlasAdminAPISpecURL, specFilePath); err != nil { + log.Fatalf("an error occurred when downloading Atlas Admin API spec: %v", err) + } + + model, err := codespec.ToCodeSpecModel(specFilePath, configPath, resourceName) + if err != nil { + log.Fatalf("an error occurred while generating codespec.Model: %v", err) + } + + for i := range model.Resources { + resourceModel := model.Resources[i] + schemaCode := schema.GenerateGoCode(resourceModel) + if err := writeToFile(fmt.Sprintf("internal/service/%s/resource_schema.go", resourceModel.Name.LowerCaseNoUnderscore()), schemaCode); err != nil { + log.Fatalf("an error occurred when writing content to file: %v", err) + } + } +} + +func getOsArg() *string { + if len(os.Args) < 2 { + return nil + } + return &os.Args[1] +} + +func writeToFile(fileName, content string) error { + // will override content if file exists + err := os.WriteFile(fileName, []byte(content), 0o600) + if err != nil { + return err + } + return nil +} diff --git a/tools/codegen/openapi/parser.go b/tools/codegen/openapi/parser.go new file mode 100644 index 0000000000..c6908de2d3 --- /dev/null +++ b/tools/codegen/openapi/parser.go @@ -0,0 +1,58 @@ +package openapi + +import ( + "context" + "fmt" + "io" + "net/http" + "os" + "time" + + "github.com/pb33f/libopenapi" + v3 "github.com/pb33f/libopenapi/datamodel/high/v3" +) + +func ParseAtlasAdminAPI(filePath string) (*libopenapi.DocumentModel[v3.Document], error) { + atlasAPISpec, _ := os.ReadFile(filePath) + document, err := libopenapi.NewDocument(atlasAPISpec) + if err != nil { + return nil, fmt.Errorf("cannot create new document: %e", err) + } + docModel, errors := document.BuildV3Model() + if len(errors) > 0 { + for i := range errors { + fmt.Printf("error: %e\n", errors[i]) + } + return nil, fmt.Errorf("cannot create v3 model from document: %d errors reported", len(errors)) + } + + return docModel, nil +} + +func DownloadOpenAPISpec(url, specFilePath string) (err error) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) + if err != nil { + return err + } + + client := http.Client{} + res, getErr := client.Do(req) + if getErr != nil { + return getErr + } + + if res.Body != nil { + defer res.Body.Close() + } + + body, readErr := io.ReadAll(res.Body) + if readErr != nil { + return readErr + } + + err = os.WriteFile(specFilePath, body, 0o600) + return err +} diff --git a/tools/codegen/schema/code_statement.go b/tools/codegen/schema/code_statement.go new file mode 100644 index 0000000000..2c2b79f170 --- /dev/null +++ b/tools/codegen/schema/code_statement.go @@ -0,0 +1,20 @@ +package schema + +type CodeStatement struct { + Code string + Imports []string +} + +func GroupCodeStatements(stmts []CodeStatement, grouping func([]string) string) CodeStatement { + listOfCode := []string{} + imports := []string{} + for i := range stmts { + listOfCode = append(listOfCode, stmts[i].Code) + imports = append(imports, stmts[i].Imports...) + } + resultCode := grouping(listOfCode) + return CodeStatement{ + Code: resultCode, + Imports: imports, + } +} diff --git a/tools/codegen/schema/codetemplate/schema-file.go.tmpl b/tools/codegen/schema/codetemplate/schema-file.go.tmpl new file mode 100644 index 0000000000..d6197c929d --- /dev/null +++ b/tools/codegen/schema/codetemplate/schema-file.go.tmpl @@ -0,0 +1,18 @@ +package {{ .PackageName }} + +import ( + "context" + {{range .Imports }} + "{{ . }}" + {{- end }} +) + +func ResourceSchema(ctx context.Context) schema.Schema { + return schema.Schema{ + Attributes: map[string]schema.Attribute{ + {{ .SchemaAttributes }} + }, + } +} + +{{ .Models }} diff --git a/tools/codegen/schema/codetemplate/template.go b/tools/codegen/schema/codetemplate/template.go new file mode 100644 index 0000000000..7765b9e6c9 --- /dev/null +++ b/tools/codegen/schema/codetemplate/template.go @@ -0,0 +1,32 @@ +package codetemplate + +import ( + "bytes" + _ "embed" + "text/template" +) + +//go:embed schema-file.go.tmpl +var schemaFileTemplate string + +type SchemaFileInputs struct { + PackageName string + SchemaAttributes string + Models string + Imports []string +} + +func ApplySchemaFileTemplate(inputs SchemaFileInputs) bytes.Buffer { + t, err := template.New("template").Parse(schemaFileTemplate) + if err != nil { + panic(err) + } + + var buf bytes.Buffer + err = t.Execute(&buf, inputs) + if err != nil { + panic(err) + } + + return buf +} diff --git a/tools/codegen/schema/element_type_mapping.go b/tools/codegen/schema/element_type_mapping.go new file mode 100644 index 0000000000..34685b2381 --- /dev/null +++ b/tools/codegen/schema/element_type_mapping.go @@ -0,0 +1,25 @@ +package schema + +import ( + "fmt" + + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/codespec" +) + +var elementTypeToString = map[codespec.ElemType]string{ + codespec.Bool: "types.BoolType", + codespec.Float64: "types.Float64Type", + codespec.Int64: "types.Int64Type", + codespec.Number: "types.NumberType", + codespec.String: "types.StringType", +} + +const typesImportStatement = "github.com/hashicorp/terraform-plugin-framework/types" + +func ElementTypeProperty(elementType codespec.ElemType) CodeStatement { + result := elementTypeToString[elementType] + return CodeStatement{ + Code: fmt.Sprintf("ElementType: %s", result), + Imports: []string{typesImportStatement}, + } +} diff --git a/tools/codegen/schema/schema_attribute.go b/tools/codegen/schema/schema_attribute.go new file mode 100644 index 0000000000..a99b7012a1 --- /dev/null +++ b/tools/codegen/schema/schema_attribute.go @@ -0,0 +1,145 @@ +package schema + +import ( + "fmt" + "strings" + + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/codespec" +) + +func GenerateSchemaAttributes(attrs codespec.Attributes) CodeStatement { + attrsCode := []string{} + imports := []string{} + for i := range attrs { + result := generator(&attrs[i]).AttributeCode() + attrsCode = append(attrsCode, result.Code) + imports = append(imports, result.Imports...) + } + finalAttrs := strings.Join(attrsCode, ",\n") + "," + return CodeStatement{ + Code: finalAttrs, + Imports: imports, + } +} + +type attributeGenerator interface { + AttributeCode() CodeStatement +} + +func generator(attr *codespec.Attribute) attributeGenerator { + if attr.Int64 != nil { + return &Int64AttrGenerator{intModel: *attr.Int64, attr: *attr} + } + if attr.Float64 != nil { + return &Float64AttrGenerator{ + floatModel: *attr.Float64, + attr: *attr, + } + } + if attr.String != nil { + return &StringAttrGenerator{ + stringModel: *attr.String, + attr: *attr, + } + } + if attr.Bool != nil { + return &BoolAttrGenerator{ + boolModel: *attr.Bool, + attr: *attr, + } + } + if attr.List != nil { + return &ListAttrGenerator{ + listModel: *attr.List, + attr: *attr, + } + } + if attr.ListNested != nil { + return &ListNestedAttrGenerator{ + listNestedModel: *attr.ListNested, + attr: *attr, + } + } + if attr.Map != nil { + return &MapAttrGenerator{ + mapModel: *attr.Map, + attr: *attr, + } + } + if attr.MapNested != nil { + return &MapNestedAttrGenerator{ + mapNestedModel: *attr.MapNested, + attr: *attr, + } + } + if attr.Number != nil { + return &NumberAttrGenerator{ + numberModel: *attr.Number, + attr: *attr, + } + } + if attr.Set != nil { + return &SetAttrGenerator{ + setModel: *attr.Set, + attr: *attr, + } + } + if attr.SetNested != nil { + return &SetNestedGenerator{ + setNestedModel: *attr.SetNested, + attr: *attr, + } + } + if attr.SingleNested != nil { + return &SingleNestedAttrGenerator{ + singleNestedModel: *attr.SingleNested, + attr: *attr, + } + } + if attr.Timeouts != nil { + return &timeoutAttributeGenerator{ + timeouts: *attr.Timeouts, + } + } + panic("Attribute with unknown type defined when generating schema attribute") +} + +// generation of conventional attribute types which have common properties like MarkdownDescription, Computed/Optional/Required, Sensitive +func commonAttrStructure(attr *codespec.Attribute, typeDef string, specificProperties []CodeStatement) CodeStatement { + properties := commonProperties(attr) + imports := []string{} + for i := range specificProperties { + properties = append(properties, specificProperties[i].Code) + imports = append(imports, specificProperties[i].Imports...) + } + + name := attr.Name + propsResultString := strings.Join(properties, ",\n") + "," + code := fmt.Sprintf(`"%s": %s{ + %s + }`, name, typeDef, propsResultString) + return CodeStatement{ + Code: code, + Imports: imports, + } +} + +func commonProperties(attr *codespec.Attribute) []string { + var result []string + if attr.ComputedOptionalRequired == codespec.Required { + result = append(result, "Required: true") + } + if attr.ComputedOptionalRequired == codespec.Computed || attr.ComputedOptionalRequired == codespec.ComputedOptional { + result = append(result, "Computed: true") + } + if attr.ComputedOptionalRequired == codespec.Optional || attr.ComputedOptionalRequired == codespec.ComputedOptional { + result = append(result, "Optional: true") + } + if attr.Description != nil { + result = append(result, fmt.Sprintf("MarkdownDescription: %q", *attr.Description)) + } + if attr.Sensitive != nil && *attr.Sensitive { + result = append(result, "Sensitive: true") + } + return result +} diff --git a/tools/codegen/schema/schema_attribute_nested.go b/tools/codegen/schema/schema_attribute_nested.go new file mode 100644 index 0000000000..90a283c260 --- /dev/null +++ b/tools/codegen/schema/schema_attribute_nested.go @@ -0,0 +1,65 @@ +package schema + +import ( + "fmt" + + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/codespec" +) + +type ListNestedAttrGenerator struct { + attr codespec.Attribute + listNestedModel codespec.ListNestedAttribute +} + +func (l *ListNestedAttrGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&l.attr, "schema.ListNestedAttribute", []CodeStatement{nestedObjectProperty(l.listNestedModel.NestedObject)}) +} + +type SetNestedGenerator struct { + attr codespec.Attribute + setNestedModel codespec.SetNestedAttribute +} + +func (l *SetNestedGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&l.attr, "schema.SetNestedAttribute", []CodeStatement{nestedObjectProperty(l.setNestedModel.NestedObject)}) +} + +type MapNestedAttrGenerator struct { + attr codespec.Attribute + mapNestedModel codespec.MapNestedAttribute +} + +func (m *MapNestedAttrGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&m.attr, "schema.MapNestedAttribute", []CodeStatement{nestedObjectProperty(m.mapNestedModel.NestedObject)}) +} + +type SingleNestedAttrGenerator struct { + attr codespec.Attribute + singleNestedModel codespec.SingleNestedAttribute +} + +func (l *SingleNestedAttrGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&l.attr, "schema.SingleNestedAttribute", []CodeStatement{attributesProperty(l.singleNestedModel.NestedObject)}) +} + +func attributesProperty(nested codespec.NestedAttributeObject) CodeStatement { + attrs := GenerateSchemaAttributes(nested.Attributes) + attributeProperty := fmt.Sprintf(`Attributes: map[string]schema.Attribute{ + %s + }`, attrs.Code) + return CodeStatement{ + Code: attributeProperty, + Imports: attrs.Imports, + } +} + +func nestedObjectProperty(nested codespec.NestedAttributeObject) CodeStatement { + result := attributesProperty(nested) + nestedObj := fmt.Sprintf(`NestedObject: schema.NestedAttributeObject{ + %s, + }`, result.Code) + return CodeStatement{ + Code: nestedObj, + Imports: result.Imports, + } +} diff --git a/tools/codegen/schema/schema_attribute_primitive.go b/tools/codegen/schema/schema_attribute_primitive.go new file mode 100644 index 0000000000..79e44975c0 --- /dev/null +++ b/tools/codegen/schema/schema_attribute_primitive.go @@ -0,0 +1,75 @@ +package schema + +import "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/codespec" + +type Int64AttrGenerator struct { + intModel codespec.Int64Attribute + attr codespec.Attribute +} + +func (i *Int64AttrGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&i.attr, "schema.Int64Attribute", []CodeStatement{}) +} + +type Float64AttrGenerator struct { + floatModel codespec.Float64Attribute + attr codespec.Attribute +} + +func (f *Float64AttrGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&f.attr, "schema.Float64Attribute", []CodeStatement{}) +} + +type StringAttrGenerator struct { + stringModel codespec.StringAttribute + attr codespec.Attribute +} + +func (s *StringAttrGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&s.attr, "schema.StringAttribute", []CodeStatement{}) +} + +type BoolAttrGenerator struct { + boolModel codespec.BoolAttribute + attr codespec.Attribute +} + +func (s *BoolAttrGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&s.attr, "schema.BoolAttribute", []CodeStatement{}) +} + +type NumberAttrGenerator struct { + numberModel codespec.NumberAttribute + attr codespec.Attribute +} + +func (s *NumberAttrGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&s.attr, "schema.NumberAttribute", []CodeStatement{}) +} + +type ListAttrGenerator struct { + listModel codespec.ListAttribute + attr codespec.Attribute +} + +func (l *ListAttrGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&l.attr, "schema.ListAttribute", []CodeStatement{ElementTypeProperty(l.listModel.ElementType)}) +} + +type MapAttrGenerator struct { + mapModel codespec.MapAttribute + attr codespec.Attribute +} + +func (m *MapAttrGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&m.attr, "schema.MapAttribute", []CodeStatement{ElementTypeProperty(m.mapModel.ElementType)}) +} + +type SetAttrGenerator struct { + setModel codespec.SetAttribute + attr codespec.Attribute +} + +func (s *SetAttrGenerator) AttributeCode() CodeStatement { + return commonAttrStructure(&s.attr, "schema.SetAttribute", []CodeStatement{ElementTypeProperty(s.setModel.ElementType)}) +} diff --git a/tools/codegen/schema/schema_attribute_timeout.go b/tools/codegen/schema/schema_attribute_timeout.go new file mode 100644 index 0000000000..4dc1928870 --- /dev/null +++ b/tools/codegen/schema/schema_attribute_timeout.go @@ -0,0 +1,33 @@ +package schema + +import ( + "fmt" + + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/codespec" +) + +type timeoutAttributeGenerator struct { + timeouts codespec.TimeoutsAttribute +} + +func (s *timeoutAttributeGenerator) AttributeCode() CodeStatement { + var optionProperties string + for _, op := range s.timeouts.ConfigurableTimeouts { + switch op { + case codespec.Create: + optionProperties += "Create: true,\n" + case codespec.Update: + optionProperties += "Update: true,\n" + case codespec.Delete: + optionProperties += "Delete: true,\n" + case codespec.Read: + optionProperties += "Read: true,\n" + } + } + return CodeStatement{ + Code: fmt.Sprintf(`"timeouts": timeouts.Attributes(ctx, timeouts.Opts{ + %s + })`, optionProperties), + Imports: []string{"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"}, + } +} diff --git a/tools/codegen/schema/schema_file.go b/tools/codegen/schema/schema_file.go new file mode 100644 index 0000000000..d05fe4ee74 --- /dev/null +++ b/tools/codegen/schema/schema_file.go @@ -0,0 +1,31 @@ +package schema + +import ( + "go/format" + + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/codespec" + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/schema/codetemplate" +) + +func GenerateGoCode(input codespec.Resource) string { + schemaAttrs := GenerateSchemaAttributes(input.Schema.Attributes) + models := GenerateTypedModels(input.Schema.Attributes) + + imports := []string{"github.com/hashicorp/terraform-plugin-framework/resource/schema"} + imports = append(imports, schemaAttrs.Imports...) + imports = append(imports, models.Imports...) + + tmplInputs := codetemplate.SchemaFileInputs{ + PackageName: input.Name.LowerCaseNoUnderscore(), + Imports: imports, + SchemaAttributes: schemaAttrs.Code, + Models: models.Code, + } + result := codetemplate.ApplySchemaFileTemplate(tmplInputs) + + formattedResult, err := format.Source(result.Bytes()) + if err != nil { + panic(err) + } + return string(formattedResult) +} diff --git a/tools/codegen/schema/schema_file_test.go b/tools/codegen/schema/schema_file_test.go new file mode 100644 index 0000000000..ca38fe1278 --- /dev/null +++ b/tools/codegen/schema/schema_file_test.go @@ -0,0 +1,178 @@ +package schema_test + +import ( + "testing" + + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/codespec" + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/schema" + "github.com/sebdah/goldie/v2" + "go.mongodb.org/atlas-sdk/v20240530005/admin" +) + +var stringAttr = codespec.Attribute{ + Name: "string_attr", + String: &codespec.StringAttribute{}, + Description: admin.PtrString("string attribute"), + ComputedOptionalRequired: codespec.Optional, +} + +var intAttr = codespec.Attribute{ + Name: "int_attr", + Int64: &codespec.Int64Attribute{}, + Description: admin.PtrString("int attribute"), + ComputedOptionalRequired: codespec.Required, +} + +type schemaGenerationTestCase struct { + inputModel codespec.Resource + goldenFileName string +} + +func TestSchemaGenerationFromCodeSpec(t *testing.T) { + testCases := map[string]schemaGenerationTestCase{ + "Primitive attributes": { + inputModel: codespec.Resource{ + Name: "test_name", + Schema: &codespec.Schema{ + Attributes: []codespec.Attribute{ + { + Name: "string_attr", + String: &codespec.StringAttribute{}, + Description: admin.PtrString("string description"), + ComputedOptionalRequired: codespec.Required, + }, + { + Name: "bool_attr", + Bool: &codespec.BoolAttribute{}, + Description: admin.PtrString("bool description"), + ComputedOptionalRequired: codespec.Optional, + }, + { + Name: "int_attr", + Int64: &codespec.Int64Attribute{}, + Description: admin.PtrString("int description"), + ComputedOptionalRequired: codespec.ComputedOptional, + }, + { + Name: "float_attr", + Float64: &codespec.Float64Attribute{}, + Description: admin.PtrString("float description"), + ComputedOptionalRequired: codespec.Optional, + }, + { + Name: "number_attr", + Number: &codespec.NumberAttribute{}, + Description: admin.PtrString("number description"), + ComputedOptionalRequired: codespec.Optional, + }, + { + Name: "simple_list_attr", + List: &codespec.ListAttribute{ + ElementType: codespec.String, + }, + Description: admin.PtrString("simple arr description"), + ComputedOptionalRequired: codespec.Optional, + }, + { + Name: "simple_set_attr", + Set: &codespec.SetAttribute{ + ElementType: codespec.Float64, + }, + Description: admin.PtrString("simple set description"), + ComputedOptionalRequired: codespec.Optional, + }, + { + Name: "simple_map_attr", + Map: &codespec.MapAttribute{ + ElementType: codespec.Bool, + }, + Description: admin.PtrString("simple map description"), + ComputedOptionalRequired: codespec.Optional, + }, + }, + }, + }, + goldenFileName: "primitive-attributes", + }, + "Nested attributes": { + inputModel: codespec.Resource{ + Name: "test_name", + Schema: &codespec.Schema{ + Attributes: []codespec.Attribute{ + { + Name: "nested_single_attr", + Description: admin.PtrString("nested single attribute"), + ComputedOptionalRequired: codespec.Required, + SingleNested: &codespec.SingleNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: []codespec.Attribute{stringAttr, intAttr}, + }, + }, + }, + { + Name: "nested_list_attr", + Description: admin.PtrString("nested list attribute"), + ComputedOptionalRequired: codespec.Optional, + ListNested: &codespec.ListNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: []codespec.Attribute{stringAttr, intAttr}, + }, + }, + }, + { + Name: "set_nested_attribute", + Description: admin.PtrString("set nested attribute"), + ComputedOptionalRequired: codespec.ComputedOptional, + SetNested: &codespec.SetNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: []codespec.Attribute{stringAttr, intAttr}, + }, + }, + }, + { + Name: "map_nested_attribute", + Description: admin.PtrString("map nested attribute"), + ComputedOptionalRequired: codespec.ComputedOptional, + MapNested: &codespec.MapNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: []codespec.Attribute{stringAttr, intAttr}, + }, + }, + }, + }, + }, + }, + goldenFileName: "nested-attributes", + }, + "timeout attribute": { + inputModel: codespec.Resource{ + Name: "test_name", + Schema: &codespec.Schema{ + Attributes: []codespec.Attribute{ + { + Name: "string_attr", + String: &codespec.StringAttribute{}, + Description: admin.PtrString("string description"), + ComputedOptionalRequired: codespec.Required, + }, + { + Name: "timeouts", + Timeouts: &codespec.TimeoutsAttribute{ + ConfigurableTimeouts: []codespec.Operation{codespec.Create, codespec.Update, codespec.Delete}, + }, + }, + }, + }, + }, + goldenFileName: "timeouts", + }, + } + + for testName, tc := range testCases { + t.Run(testName, func(t *testing.T) { + result := schema.GenerateGoCode(tc.inputModel) + g := goldie.New(t, goldie.WithNameSuffix(".golden.go")) + g.Assert(t, tc.goldenFileName, []byte(result)) + }) + } +} diff --git a/tools/codegen/schema/testdata/nested-attributes.golden.go b/tools/codegen/schema/testdata/nested-attributes.golden.go new file mode 100644 index 0000000000..b0915d9593 --- /dev/null +++ b/tools/codegen/schema/testdata/nested-attributes.golden.go @@ -0,0 +1,126 @@ +package testname + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +func ResourceSchema(ctx context.Context) schema.Schema { + return schema.Schema{ + Attributes: map[string]schema.Attribute{ + "nested_single_attr": schema.SingleNestedAttribute{ + Required: true, + MarkdownDescription: "nested single attribute", + Attributes: map[string]schema.Attribute{ + "string_attr": schema.StringAttribute{ + Optional: true, + MarkdownDescription: "string attribute", + }, + "int_attr": schema.Int64Attribute{ + Required: true, + MarkdownDescription: "int attribute", + }, + }, + }, + "nested_list_attr": schema.ListNestedAttribute{ + Optional: true, + MarkdownDescription: "nested list attribute", + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + "string_attr": schema.StringAttribute{ + Optional: true, + MarkdownDescription: "string attribute", + }, + "int_attr": schema.Int64Attribute{ + Required: true, + MarkdownDescription: "int attribute", + }, + }, + }, + }, + "set_nested_attribute": schema.SetNestedAttribute{ + Computed: true, + Optional: true, + MarkdownDescription: "set nested attribute", + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + "string_attr": schema.StringAttribute{ + Optional: true, + MarkdownDescription: "string attribute", + }, + "int_attr": schema.Int64Attribute{ + Required: true, + MarkdownDescription: "int attribute", + }, + }, + }, + }, + "map_nested_attribute": schema.MapNestedAttribute{ + Computed: true, + Optional: true, + MarkdownDescription: "map nested attribute", + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + "string_attr": schema.StringAttribute{ + Optional: true, + MarkdownDescription: "string attribute", + }, + "int_attr": schema.Int64Attribute{ + Required: true, + MarkdownDescription: "int attribute", + }, + }, + }, + }, + }, + } +} + +type TFModel struct { + NestedSingleAttr types.Object `tfsdk:"nested_single_attr"` + NestedListAttr types.List `tfsdk:"nested_list_attr"` + SetNestedAttribute types.Set `tfsdk:"set_nested_attribute"` + MapNestedAttribute types.Map `tfsdk:"map_nested_attribute"` +} +type TFNestedSingleAttrModel struct { + StringAttr types.String `tfsdk:"string_attr"` + IntAttr types.Int64 `tfsdk:"int_attr"` +} + +var NestedSingleAttrObjType = types.ObjectType{AttrTypes: map[string]attr.Type{ + "string_attr": types.StringType, + "int_attr": types.Int64Type, +}} + +type TFNestedListAttrModel struct { + StringAttr types.String `tfsdk:"string_attr"` + IntAttr types.Int64 `tfsdk:"int_attr"` +} + +var NestedListAttrObjType = types.ObjectType{AttrTypes: map[string]attr.Type{ + "string_attr": types.StringType, + "int_attr": types.Int64Type, +}} + +type TFSetNestedAttributeModel struct { + StringAttr types.String `tfsdk:"string_attr"` + IntAttr types.Int64 `tfsdk:"int_attr"` +} + +var SetNestedAttributeObjType = types.ObjectType{AttrTypes: map[string]attr.Type{ + "string_attr": types.StringType, + "int_attr": types.Int64Type, +}} + +type TFMapNestedAttributeModel struct { + StringAttr types.String `tfsdk:"string_attr"` + IntAttr types.Int64 `tfsdk:"int_attr"` +} + +var MapNestedAttributeObjType = types.ObjectType{AttrTypes: map[string]attr.Type{ + "string_attr": types.StringType, + "int_attr": types.Int64Type, +}} diff --git a/tools/codegen/schema/testdata/primitive-attributes.golden.go b/tools/codegen/schema/testdata/primitive-attributes.golden.go new file mode 100644 index 0000000000..1025675c4b --- /dev/null +++ b/tools/codegen/schema/testdata/primitive-attributes.golden.go @@ -0,0 +1,62 @@ +package testname + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +func ResourceSchema(ctx context.Context) schema.Schema { + return schema.Schema{ + Attributes: map[string]schema.Attribute{ + "string_attr": schema.StringAttribute{ + Required: true, + MarkdownDescription: "string description", + }, + "bool_attr": schema.BoolAttribute{ + Optional: true, + MarkdownDescription: "bool description", + }, + "int_attr": schema.Int64Attribute{ + Computed: true, + Optional: true, + MarkdownDescription: "int description", + }, + "float_attr": schema.Float64Attribute{ + Optional: true, + MarkdownDescription: "float description", + }, + "number_attr": schema.NumberAttribute{ + Optional: true, + MarkdownDescription: "number description", + }, + "simple_list_attr": schema.ListAttribute{ + Optional: true, + MarkdownDescription: "simple arr description", + ElementType: types.StringType, + }, + "simple_set_attr": schema.SetAttribute{ + Optional: true, + MarkdownDescription: "simple set description", + ElementType: types.Float64Type, + }, + "simple_map_attr": schema.MapAttribute{ + Optional: true, + MarkdownDescription: "simple map description", + ElementType: types.BoolType, + }, + }, + } +} + +type TFModel struct { + StringAttr types.String `tfsdk:"string_attr"` + BoolAttr types.Bool `tfsdk:"bool_attr"` + IntAttr types.Int64 `tfsdk:"int_attr"` + FloatAttr types.Float64 `tfsdk:"float_attr"` + NumberAttr types.Number `tfsdk:"number_attr"` + SimpleListAttr types.List `tfsdk:"simple_list_attr"` + SimpleSetAttr types.Set `tfsdk:"simple_set_attr"` + SimpleMapAttr types.Map `tfsdk:"simple_map_attr"` +} diff --git a/tools/codegen/schema/testdata/timeouts.golden.go b/tools/codegen/schema/testdata/timeouts.golden.go new file mode 100644 index 0000000000..ca5213bd1e --- /dev/null +++ b/tools/codegen/schema/testdata/timeouts.golden.go @@ -0,0 +1,30 @@ +package testname + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +func ResourceSchema(ctx context.Context) schema.Schema { + return schema.Schema{ + Attributes: map[string]schema.Attribute{ + "string_attr": schema.StringAttribute{ + Required: true, + MarkdownDescription: "string description", + }, + "timeouts": timeouts.Attributes(ctx, timeouts.Opts{ + Create: true, + Update: true, + Delete: true, + }), + }, + } +} + +type TFModel struct { + StringAttr types.String `tfsdk:"string_attr"` + Timeouts timeouts.Value `tfsdk:"timeouts"` +} diff --git a/tools/codegen/schema/typed_model.go b/tools/codegen/schema/typed_model.go new file mode 100644 index 0000000000..5a324af296 --- /dev/null +++ b/tools/codegen/schema/typed_model.go @@ -0,0 +1,114 @@ +package schema + +import ( + "fmt" + "strings" + + "github.com/mongodb/terraform-provider-mongodbatlas/tools/codegen/codespec" +) + +func GenerateTypedModels(attributes codespec.Attributes) CodeStatement { + return generateTypedModels(attributes, "", false) // empty string for root model, results in TFModel +} + +func generateTypedModels(attributes codespec.Attributes, name string, isNested bool) CodeStatement { + models := []CodeStatement{generateStructOfTypedModel(attributes, name)} + + if isNested { + models = append(models, generateModelObjType(attributes, name)) + } + + for i := range attributes { + additionalModel := getNestedModel(&attributes[i]) + if additionalModel != nil { + models = append(models, *additionalModel) + } + } + + return GroupCodeStatements(models, func(list []string) string { return strings.Join(list, "\n") }) +} + +func generateModelObjType(attrs codespec.Attributes, name string) CodeStatement { + structProperties := []string{} + for i := range attrs { + propType := attrModelType(&attrs[i]) + prop := fmt.Sprintf(`%q: %sType,`, attrs[i].Name.SnakeCase(), propType) + structProperties = append(structProperties, prop) + } + structPropsCode := strings.Join(structProperties, "\n") + return CodeStatement{ + Code: fmt.Sprintf(`var %sObjType = types.ObjectType{AttrTypes: map[string]attr.Type{ + %s +}}`, name, structPropsCode), + Imports: []string{"github.com/hashicorp/terraform-plugin-framework/types", "github.com/hashicorp/terraform-plugin-framework/attr"}, + } +} + +func getNestedModel(attribute *codespec.Attribute) *CodeStatement { + var nested *codespec.NestedAttributeObject + if attribute.ListNested != nil { + nested = &attribute.ListNested.NestedObject + } + if attribute.SingleNested != nil { + nested = &attribute.SingleNested.NestedObject + } + if attribute.MapNested != nil { + nested = &attribute.MapNested.NestedObject + } + if attribute.SetNested != nil { + nested = &attribute.SetNested.NestedObject + } + if nested == nil { + return nil + } + res := generateTypedModels(nested.Attributes, attribute.Name.PascalCase(), true) + return &res +} + +func generateStructOfTypedModel(attributes codespec.Attributes, name string) CodeStatement { + structProperties := []string{} + for i := range attributes { + structProperties = append(structProperties, typedModelProperty(&attributes[i])) + } + structPropsCode := strings.Join(structProperties, "\n") + return CodeStatement{ + Code: fmt.Sprintf(`type TF%sModel struct { + %s + }`, name, structPropsCode), + Imports: []string{"github.com/hashicorp/terraform-plugin-framework/types"}, + } +} + +func typedModelProperty(attr *codespec.Attribute) string { + namePascalCase := attr.Name.PascalCase() + propType := attrModelType(attr) + return fmt.Sprintf("%s %s", namePascalCase, propType) + " `" + fmt.Sprintf("tfsdk:%q", attr.Name.SnakeCase()) + "`" +} + +func attrModelType(attr *codespec.Attribute) string { + switch { + case attr.Float64 != nil: + return "types.Float64" + case attr.Bool != nil: + return "types.Bool" + case attr.String != nil: + return "types.String" + case attr.Number != nil: + return "types.Number" + case attr.Int64 != nil: + return "types.Int64" + case attr.Timeouts != nil: + return "timeouts.Value" + // For nested attributes the generic type is used, this is to ensure the model can store all possible values. e.g. nested computed only attributes need to be defined with TPF types to avoid error when getting the config. + case attr.List != nil || attr.ListNested != nil: + return "types.List" + case attr.Set != nil || attr.SetNested != nil: + return "types.Set" + case attr.Map != nil || attr.MapNested != nil: + return "types.Map" + case attr.SingleNested != nil: + return "types.Object" + default: + panic("Attribute with unknown type defined when generating typed model") + } +} From 6f5894ce70a81afd63850de93059561af82bd076 Mon Sep 17 00:00:00 2001 From: maastha <122359335+maastha@users.noreply.github.com> Date: Thu, 24 Oct 2024 18:05:34 +0100 Subject: [PATCH 12/35] doc: Adds documentation for `replication_specs.*.external_id` computed attribute for `mongodbatlas_advanced_cluster` (#2734) --- docs/data-sources/advanced_cluster.md | 2 ++ docs/data-sources/advanced_clusters.md | 2 ++ docs/data-sources/cluster.md | 2 +- docs/data-sources/clusters.md | 2 +- docs/resources/advanced_cluster.md | 2 ++ docs/resources/cluster.md | 2 +- 6 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/data-sources/advanced_cluster.md b/docs/data-sources/advanced_cluster.md index bd62827de3..0b69cd8796 100644 --- a/docs/data-sources/advanced_cluster.md +++ b/docs/data-sources/advanced_cluster.md @@ -136,6 +136,8 @@ Key-value pairs that categorize the cluster. Each key and value has a maximum le ### replication_specs +* `id` - **(DEPRECATED)** Unique identifer of the replication document for a zone in a Global Cluster. This value corresponds to the legacy sharding schema (no independent shard scaling) and is different from the Shard ID you may see in the Atlas UI. +* `external_id` - Unique 24-hexadecimal digit string that identifies the replication object for a shard in a Cluster. This value corresponds to Shard ID displayed in the UI. When using old sharding configuration (replication spec with `num_shards` greater than 1) this value is not populated. * `num_shards` - Provide this value if you set a `cluster_type` of `SHARDED` or `GEOSHARDED`. **(DEPRECATED.)** To learn more, see the [Migration Guide](../guides/1.18.0-upgrade-guide.html.markdown). * `region_configs` - Configuration for the hardware specifications for nodes set for a given regionEach `region_configs` object describes the region's priority in elections and the number and type of MongoDB nodes that Atlas deploys to the region. Each `region_configs` object must have either an `analytics_specs` object, `electable_specs` object, or `read_only_specs` object. See [below](#region_configs) * `container_id` - A key-value map of the Network Peering Container ID(s) for the configuration specified in `region_configs`. The Container ID is the id of the container either created programmatically by the user before any clusters existed in a project or when the first cluster in the region (AWS/Azure) or project (GCP) was created. The syntax is `"providerName:regionName" = "containerId"`. Example `AWS:US_EAST_1" = "61e0797dde08fb498ca11a71`. diff --git a/docs/data-sources/advanced_clusters.md b/docs/data-sources/advanced_clusters.md index 98f85f42bd..c1d26b12e3 100644 --- a/docs/data-sources/advanced_clusters.md +++ b/docs/data-sources/advanced_clusters.md @@ -138,6 +138,8 @@ Key-value pairs that categorize the cluster. Each key and value has a maximum le ### replication_specs +* `id` - **(DEPRECATED)** Unique identifer of the replication document for a zone in a Global Cluster. This value corresponds to the legacy sharding schema (no independent shard scaling) and is different from the Shard ID you may see in the Atlas UI. +* `external_id` - Unique 24-hexadecimal digit string that identifies the replication object for a shard in a Cluster. This value corresponds to Shard ID displayed in the UI. When using old sharding configuration (replication spec with `num_shards` greater than 1) this value is not populated. * `num_shards` - Provide this value if you set a `cluster_type` of SHARDED or GEOSHARDED. **(DEPRECATED.)** To learn more, see the [Migration Guide](../guides/1.18.0-upgrade-guide.html.markdown) for more details. * `region_configs` - Configuration for the hardware specifications for nodes set for a given regionEach `region_configs` object describes the region's priority in elections and the number and type of MongoDB nodes that Atlas deploys to the region. Each `region_configs` object must have either an `analytics_specs` object, `electable_specs` object, or `read_only_specs` object. See [below](#region_configs) * `container_id` - A key-value map of the Network Peering Container ID(s) for the configuration specified in `region_configs`. The Container ID is the id of the container either created programmatically by the user before any clusters existed in a project or when the first cluster in the region (AWS/Azure) or project (GCP) was created. The syntax is `"providerName:regionName" = "containerId"`. Example `AWS:US_EAST_1" = "61e0797dde08fb498ca11a71`. diff --git a/docs/data-sources/cluster.md b/docs/data-sources/cluster.md index 5dc6c71783..e8f96a3e9d 100644 --- a/docs/data-sources/cluster.md +++ b/docs/data-sources/cluster.md @@ -141,7 +141,7 @@ Indicates BI Connector for Atlas configuration. Configuration for cluster regions. -* `id` - Unique identifer of the replication document for a zone in a Global Cluster. +* `id` - Unique identifer of the replication document for a zone in a Global Cluster. This value corresponds to the legacy sharding schema (no independent shard scaling) and is different from the Shard ID you may see in the Atlas UI. * `num_shards` - Number of shards to deploy in the specified zone. * `regions_config` - Describes the physical location of the region. Each regionsConfig document describes the region’s priority in elections and the number and type of MongoDB nodes Atlas deploys to the region. You must order each regionsConfigs document by regionsConfig.priority, descending. See [Region Config](#region-config) below for more details. * `zone_name` - Indicates the n ame for the zone in a Global Cluster. diff --git a/docs/data-sources/clusters.md b/docs/data-sources/clusters.md index 8a3be69f86..4cef071990 100644 --- a/docs/data-sources/clusters.md +++ b/docs/data-sources/clusters.md @@ -132,7 +132,7 @@ Indicates BI Connector for Atlas configuration. Configuration for cluster regions. -* `id` - Unique identifer of the replication document for a zone in a Global Cluster. +* `id` - Unique identifer of the replication document for a zone in a Global Cluster. This value corresponds to the legacy sharding schema (no independent shard scaling) and is different from the Shard ID you may see in the Atlas UI. * `num_shards` - Number of shards to deploy in the specified zone. * `regions_config` - Describes the physical location of the region. Each regionsConfig document describes the region’s priority in elections and the number and type of MongoDB nodes Atlas deploys to the region. You must order each regionsConfigs document by regionsConfig.priority, descending. See [Region Config](#region-config) below for more details. * `zone_name` - Indicates the n ame for the zone in a Global Cluster. diff --git a/docs/resources/advanced_cluster.md b/docs/resources/advanced_cluster.md index 3b209860b2..be0d6aebfd 100644 --- a/docs/resources/advanced_cluster.md +++ b/docs/resources/advanced_cluster.md @@ -533,6 +533,8 @@ replication_specs { } ``` +* `id` - **(DEPRECATED)** Unique identifer of the replication document for a zone in a Global Cluster. This value corresponds to the legacy sharding schema (no independent shard scaling) and is different from the Shard ID you may see in the Atlas UI. +* `external_id` - Unique 24-hexadecimal digit string that identifies the replication object for a shard in a Cluster. This value corresponds to Shard ID displayed in the UI. When using old sharding configuration (replication spec with `num_shards` greater than 1) this value is not populated. * `num_shards` - (Optional) Provide this value if you set a `cluster_type` of SHARDED or GEOSHARDED. Omit this value if you selected a `cluster_type` of REPLICASET. This API resource accepts 1 through 50, inclusive. This parameter defaults to 1. If you specify a `num_shards` value of 1 and a `cluster_type` of SHARDED, Atlas deploys a single-shard [sharded cluster](https://docs.atlas.mongodb.com/reference/glossary/#std-term-sharded-cluster). Don't create a sharded cluster with a single shard for production environments. Single-shard sharded clusters don't provide the same benefits as multi-shard configurations. If you are upgrading a replica set to a sharded cluster, you cannot increase the number of shards in the same update request. You should wait until after the cluster has completed upgrading to sharded and you have reconnected all application clients to the MongoDB router before adding additional shards. Otherwise, your data might become inconsistent once MongoDB Cloud begins distributing data across shards. To learn more, see [Convert a replica set to a sharded cluster documentation](https://www.mongodb.com/docs/atlas/scale-cluster/#convert-a-replica-set-to-a-sharded-cluster) and [Convert a replica set to a sharded cluster tutorial](https://www.mongodb.com/docs/upcoming/tutorial/convert-replica-set-to-replicated-shard-cluster). **(DEPRECATED)** To learn more, see the [1.18.0 Upgrade Guide](../guides/1.18.0-upgrade-guide.html.markdown). * `region_configs` - (Optional) Configuration for the hardware specifications for nodes set for a given regionEach `region_configs` object describes the region's priority in elections and the number and type of MongoDB nodes that Atlas deploys to the region. Each `region_configs` object must have either an `analytics_specs` object, `electable_specs` object, or `read_only_specs` object. See [below](#region_configs) diff --git a/docs/resources/cluster.md b/docs/resources/cluster.md index 1cb95bb2c7..ab526505b9 100644 --- a/docs/resources/cluster.md +++ b/docs/resources/cluster.md @@ -420,7 +420,7 @@ replication_specs { * `num_shards` - (Required) Number of shards up to 50 to deploy for a sharded cluster. The resource returns 1 to indicate a replica set and values of 2 and higher to indicate a sharded cluster. The returned value equals the number of shards in the cluster. If you are upgrading a replica set to a sharded cluster, you cannot increase the number of shards in the same update request. You should wait until after the cluster has completed upgrading to sharded and you have reconnected all application clients to the MongoDB router before adding additional shards. Otherwise, your data might become inconsistent once MongoDB Cloud begins distributing data across shards. To learn more, see [Convert a replica set to a sharded cluster documentation](https://www.mongodb.com/docs/atlas/scale-cluster/#convert-a-replica-set-to-a-sharded-cluster) and [Convert a replica set to a sharded cluster tutorial](https://www.mongodb.com/docs/upcoming/tutorial/convert-replica-set-to-replicated-shard-cluster). -* `id` - (Optional) Unique identifer of the replication document for a zone in a Global Cluster. +* `id` - (Optional) Unique identifer of the replication document for a zone in a Global Cluster. This value corresponds to the legacy sharding schema (no independent shard scaling) and is different from the Shard ID you may see in the Atlas UI. * `regions_config` - (Optional) Physical location of the region. Each regionsConfig document describes the region’s priority in elections and the number and type of MongoDB nodes Atlas deploys to the region. You must order each regionsConfigs document by regionsConfig.priority, descending. See [Region Config](#region-config) below for more details. * `zone_name` - (Optional) Name for the zone in a Global Cluster. From 45b26063db74afc5ac13baad3c23afa37c8e1b04 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Fri, 25 Oct 2024 00:57:58 +0200 Subject: [PATCH 13/35] adds M0 (#2730) --- docs/resources/advanced_cluster.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/resources/advanced_cluster.md b/docs/resources/advanced_cluster.md index be0d6aebfd..43424d4d4a 100644 --- a/docs/resources/advanced_cluster.md +++ b/docs/resources/advanced_cluster.md @@ -558,7 +558,7 @@ If you are upgrading a replica set to a sharded cluster, you cannot increase the - `AWS` - Amazon AWS - `GCP` - Google Cloud Platform - `AZURE` - Microsoft Azure - - `TENANT` - M2 or M5 multi-tenant cluster. Use `replication_specs.#.region_configs.#.backing_provider_name` to set the cloud service provider. + - `TENANT` - M0, M2 or M5 multi-tenant cluster. Use `replication_specs.#.region_configs.#.backing_provider_name` to set the cloud service provider. * `read_only_specs` - (Optional) Hardware specifications for read-only nodes in the region. Read-only nodes can become the [primary](https://docs.atlas.mongodb.com/reference/glossary/#std-term-primary) and can enable local reads. If you don't specify this parameter, no read-only nodes are deployed to the region. See [below](#specs) * `region_name` - (Optional) Physical location of your MongoDB cluster. The region you choose can affect network latency for clients accessing your databases. Requires the **Atlas region name**, see the reference list for [AWS](https://docs.atlas.mongodb.com/reference/amazon-aws/), [GCP](https://docs.atlas.mongodb.com/reference/google-gcp/), [Azure](https://docs.atlas.mongodb.com/reference/microsoft-azure/). From 77f4e966e4df165829ded51c74ccd2805b75547b Mon Sep 17 00:00:00 2001 From: Agustin Bettati Date: Fri, 25 Oct 2024 08:41:29 +0200 Subject: [PATCH 14/35] docs: Remove legacy project_id attribute in docs as it has been removed (#2733) --- docs/resources/project_api_key.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/resources/project_api_key.md b/docs/resources/project_api_key.md index 6404d3d0b9..e5187d2965 100644 --- a/docs/resources/project_api_key.md +++ b/docs/resources/project_api_key.md @@ -38,7 +38,6 @@ resource "mongodbatlas_project_api_key" "test" { ## Argument Reference * `description` - (Required) Description of this Project API key. -* `project_id` - Unique 24-hexadecimal digit string that identifies your project. **WARNING:** this parameter is deprecated as it no longer needs to be defined. It will be removed in version 1.16.0. ~> **NOTE:** Project created by API Keys must belong to an existing organization. From 77b672e6bb40bb498709d6f3091558deb2ae23d2 Mon Sep 17 00:00:00 2001 From: svc-apix-bot Date: Fri, 25 Oct 2024 07:32:45 +0000 Subject: [PATCH 15/35] chore: Updates examples link in index.md for v1.21.3 release --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index 9ef95749b7..28c6661683 100644 --- a/docs/index.md +++ b/docs/index.md @@ -220,7 +220,7 @@ We ship binaries but do not prioritize fixes for the following operating system ## Examples from MongoDB and the Community -We have [example configurations](https://github.com/mongodb/terraform-provider-mongodbatlas/tree/v1.21.2/examples) +We have [example configurations](https://github.com/mongodb/terraform-provider-mongodbatlas/tree/v1.21.3/examples) in our GitHub repo that will help both beginner and more advanced users. Have a good example you've created and want to share? From 3f021d3e1d57d6df5d71d5b9603b06241bab4c97 Mon Sep 17 00:00:00 2001 From: svc-apix-bot Date: Fri, 25 Oct 2024 07:33:08 +0000 Subject: [PATCH 16/35] chore: Updates CHANGELOG.md header for v1.21.3 release --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 184d277ce5..14064d6f27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ ## (Unreleased) +## 1.21.3 (October 25, 2024) + NOTES: * data-source/mongodbatlas_project: Deprecates `is_slow_operation_thresholding_enabled`. Attribute will be supported in a separate data source as it requires different set of permissions ([#2731](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2731)) From 221ddfc967ca18e381af5b4fd7929e2f99d4754d Mon Sep 17 00:00:00 2001 From: Oriol Date: Fri, 25 Oct 2024 15:41:04 +0200 Subject: [PATCH 17/35] chore: Unify file name for plural data source schema (#2739) * change name * fix name * rename to plural_data_source.go --- .../{pural_data_source_schema.go => plural_data_source_schema.go} | 0 .../{data_source_plural.go => plural_data_source.go} | 0 ...{data_source_plural_schema.go => plural_data_source_schema.go} | 0 .../{data_source_plural.go => plural_data_source.go} | 0 ...{data_source_plural_schema.go => plural_data_source_schema.go} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename internal/service/encryptionatrestprivateendpoint/{pural_data_source_schema.go => plural_data_source_schema.go} (100%) rename internal/service/resourcepolicy/{data_source_plural.go => plural_data_source.go} (100%) rename internal/service/resourcepolicy/{data_source_plural_schema.go => plural_data_source_schema.go} (100%) rename internal/service/streamprocessor/{data_source_plural.go => plural_data_source.go} (100%) rename internal/service/streamprocessor/{data_source_plural_schema.go => plural_data_source_schema.go} (100%) diff --git a/internal/service/encryptionatrestprivateendpoint/pural_data_source_schema.go b/internal/service/encryptionatrestprivateendpoint/plural_data_source_schema.go similarity index 100% rename from internal/service/encryptionatrestprivateendpoint/pural_data_source_schema.go rename to internal/service/encryptionatrestprivateendpoint/plural_data_source_schema.go diff --git a/internal/service/resourcepolicy/data_source_plural.go b/internal/service/resourcepolicy/plural_data_source.go similarity index 100% rename from internal/service/resourcepolicy/data_source_plural.go rename to internal/service/resourcepolicy/plural_data_source.go diff --git a/internal/service/resourcepolicy/data_source_plural_schema.go b/internal/service/resourcepolicy/plural_data_source_schema.go similarity index 100% rename from internal/service/resourcepolicy/data_source_plural_schema.go rename to internal/service/resourcepolicy/plural_data_source_schema.go diff --git a/internal/service/streamprocessor/data_source_plural.go b/internal/service/streamprocessor/plural_data_source.go similarity index 100% rename from internal/service/streamprocessor/data_source_plural.go rename to internal/service/streamprocessor/plural_data_source.go diff --git a/internal/service/streamprocessor/data_source_plural_schema.go b/internal/service/streamprocessor/plural_data_source_schema.go similarity index 100% rename from internal/service/streamprocessor/data_source_plural_schema.go rename to internal/service/streamprocessor/plural_data_source_schema.go From 8417717351b6d23223e1d8f86037e6b97a2bdef9 Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Mon, 28 Oct 2024 09:30:41 +0100 Subject: [PATCH 18/35] check cluster creation times (#2728) --- .../resource_advanced_cluster_test.go | 20 +++++++++---------- .../resource_cloud_backup_schedule_test.go | 14 ++++++------- .../resource_cloud_backup_snapshot_test.go | 4 ++-- ...e_cloud_backup_snapshot_export_job_test.go | 2 +- ..._cloud_backup_snapshot_restore_job_test.go | 4 ++-- .../service/cluster/resource_cluster_test.go | 18 ++++++++--------- ...resource_cluster_outage_simulation_test.go | 4 ++-- ...source_federated_database_instance_test.go | 2 +- .../resource_global_cluster_config_test.go | 4 ++-- .../resource_online_archive_test.go | 8 ++++---- internal/testutil/acc/pre_check.go | 10 +++++++++- 11 files changed, 49 insertions(+), 41 deletions(-) diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index 4573821fda..c56d9b2e86 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -36,7 +36,7 @@ func TestAccClusterAdvancedCluster_basicTenant(t *testing.T) { clusterNameUpdated = acc.RandomClusterName() ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -69,7 +69,7 @@ func replicaSetAWSProviderTestCase(t *testing.T) resource.TestCase { ) return resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -174,7 +174,7 @@ func TestAccClusterAdvancedCluster_unpausedToPaused(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -209,7 +209,7 @@ func TestAccClusterAdvancedCluster_pausedToUnpaused(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -271,7 +271,7 @@ func TestAccClusterAdvancedCluster_advancedConfig(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -306,7 +306,7 @@ func TestAccClusterAdvancedCluster_advancedConfig_MongoDBVersion5(t *testing.T) ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -347,7 +347,7 @@ func TestAccClusterAdvancedCluster_defaultWrite(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -379,7 +379,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAutoScaling(t *testing. ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -422,7 +422,7 @@ func TestAccClusterAdvancedClusterConfig_replicationSpecsAnalyticsAutoScaling(t ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -535,7 +535,7 @@ func TestAccClusterAdvancedClusterConfig_selfManagedShardingIncorrectType(t *tes ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ diff --git a/internal/service/cloudbackupschedule/resource_cloud_backup_schedule_test.go b/internal/service/cloudbackupschedule/resource_cloud_backup_schedule_test.go index 4e5930aef6..610e7dc3ab 100644 --- a/internal/service/cloudbackupschedule/resource_cloud_backup_schedule_test.go +++ b/internal/service/cloudbackupschedule/resource_cloud_backup_schedule_test.go @@ -25,7 +25,7 @@ func TestAccBackupRSCloudBackupSchedule_basic(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ @@ -159,7 +159,7 @@ func TestAccBackupRSCloudBackupSchedule_export(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ExternalProviders: acc.ExternalProvidersOnlyAWS(), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, @@ -188,7 +188,7 @@ func TestAccBackupRSCloudBackupSchedule_onePolicy(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ @@ -313,7 +313,7 @@ func TestAccBackupRSCloudBackupSchedule_copySettings_repSpecId(t *testing.T) { checksUpdate := acc.AddAttrChecks(resourceName, checksDefaultRS, emptyCopySettingsChecks) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ @@ -399,7 +399,7 @@ func TestAccBackupRSCloudBackupSchedule_copySettings_zoneId(t *testing.T) { checksUpdate := acc.AddAttrChecks(resourceName, checksDefaultRS, emptyCopySettingsChecks) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ @@ -429,7 +429,7 @@ func TestAccBackupRSCloudBackupScheduleImport_basic(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ @@ -484,7 +484,7 @@ func TestAccBackupRSCloudBackupSchedule_azure(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ diff --git a/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_test.go b/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_test.go index 31a121a232..3e306ddc60 100644 --- a/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_test.go +++ b/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot_test.go @@ -26,7 +26,7 @@ func TestAccBackupRSCloudBackupSnapshot_basic(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ @@ -75,7 +75,7 @@ func TestAccBackupRSCloudBackupSnapshot_sharded(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ diff --git a/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job_test.go b/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job_test.go index 7d4579b98a..26dcd24356 100644 --- a/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job_test.go +++ b/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job_test.go @@ -54,7 +54,7 @@ func basicTestCase(tb testing.TB) *resource.TestCase { checks = acc.AddAttrChecks(dataSourcePluralName, checks, attrsPluralDS) return &resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(tb), + PreCheck: acc.PreCheckBasicSleep(tb, &clusterInfo, "", ""), ExternalProviders: acc.ExternalProvidersOnlyAWS(), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, Steps: []resource.TestStep{ 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 d70a05526b..d5042b0cfe 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 @@ -43,7 +43,7 @@ func TestAccCloudBackupSnapshotRestoreJob_basicDownload(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ @@ -75,7 +75,7 @@ func basicTestCase(tb testing.TB) *resource.TestCase { ) return &resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(tb), + PreCheck: acc.PreCheckBasicSleep(tb, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ diff --git a/internal/service/cluster/resource_cluster_test.go b/internal/service/cluster/resource_cluster_test.go index 92199d7cfc..118e1ced33 100644 --- a/internal/service/cluster/resource_cluster_test.go +++ b/internal/service/cluster/resource_cluster_test.go @@ -36,7 +36,7 @@ func basicTestCase(tb testing.TB) *resource.TestCase { ) return &resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(tb), + PreCheck: acc.PreCheckBasicSleep(tb, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -101,7 +101,7 @@ func partialAdvancedConfTestCase(tb testing.TB) *resource.TestCase { ) return &resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(tb), + PreCheck: acc.PreCheckBasicSleep(tb, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -163,7 +163,7 @@ func TestAccCluster_basic_DefaultWriteRead_AdvancedConf(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -222,7 +222,7 @@ func TestAccCluster_emptyAdvancedConf(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -264,7 +264,7 @@ func TestAccCluster_basicAdvancedConf(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -625,7 +625,7 @@ func TestAccCluster_AWSWithLabels(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -986,7 +986,7 @@ func TestAccCluster_withAutoScalingAWS(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -1267,7 +1267,7 @@ func TestAccCluster_basicAWS_UnpauseToPaused(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -1315,7 +1315,7 @@ func TestAccCluster_basicAWS_PausedToUnpaused(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, nil, projectID, clusterName), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ diff --git a/internal/service/clusteroutagesimulation/resource_cluster_outage_simulation_test.go b/internal/service/clusteroutagesimulation/resource_cluster_outage_simulation_test.go index 1976c09d56..95bfada97c 100644 --- a/internal/service/clusteroutagesimulation/resource_cluster_outage_simulation_test.go +++ b/internal/service/clusteroutagesimulation/resource_cluster_outage_simulation_test.go @@ -32,7 +32,7 @@ func singleRegionTestCase(t *testing.T) *resource.TestCase { clusterName = clusterInfo.Name ) return &resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ @@ -80,7 +80,7 @@ func multiRegionTestCase(t *testing.T) *resource.TestCase { ) return &resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ diff --git a/internal/service/federateddatabaseinstance/resource_federated_database_instance_test.go b/internal/service/federateddatabaseinstance/resource_federated_database_instance_test.go index 124ca55523..0efd1174b0 100644 --- a/internal/service/federateddatabaseinstance/resource_federated_database_instance_test.go +++ b/internal/service/federateddatabaseinstance/resource_federated_database_instance_test.go @@ -123,7 +123,7 @@ func TestAccFederatedDatabaseInstance_atlasCluster(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), CheckDestroy: acc.CheckDestroyFederatedDatabaseInstance, Steps: []resource.TestStep{ { diff --git a/internal/service/globalclusterconfig/resource_global_cluster_config_test.go b/internal/service/globalclusterconfig/resource_global_cluster_config_test.go index 0b53bd5794..c522cb5632 100644 --- a/internal/service/globalclusterconfig/resource_global_cluster_config_test.go +++ b/internal/service/globalclusterconfig/resource_global_cluster_config_test.go @@ -41,7 +41,7 @@ func basicTestCase(tb testing.TB, checkZoneID, withBackup bool) *resource.TestCa } return &resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(tb), + PreCheck: acc.PreCheckBasicSleep(tb, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ @@ -113,7 +113,7 @@ func TestAccGlobalClusterConfig_database(t *testing.T) { ) resource.Test(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy, Steps: []resource.TestStep{ diff --git a/internal/service/onlinearchive/resource_online_archive_test.go b/internal/service/onlinearchive/resource_online_archive_test.go index 8464ff3713..a5d76aeba5 100644 --- a/internal/service/onlinearchive/resource_online_archive_test.go +++ b/internal/service/onlinearchive/resource_online_archive_test.go @@ -37,7 +37,7 @@ func TestAccBackupRSOnlineArchive(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -135,7 +135,7 @@ func TestAccBackupRSOnlineArchiveBasic(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -184,7 +184,7 @@ func TestAccBackupRSOnlineArchiveWithProcessRegion(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ @@ -227,7 +227,7 @@ func TestAccBackupRSOnlineArchiveInvalidProcessRegion(t *testing.T) { ) resource.ParallelTest(t, resource.TestCase{ - PreCheck: acc.PreCheckBasicSleep(t), + PreCheck: acc.PreCheckBasicSleep(t, &clusterInfo, "", ""), ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: acc.CheckDestroyCluster, Steps: []resource.TestStep{ diff --git a/internal/testutil/acc/pre_check.go b/internal/testutil/acc/pre_check.go index 336962cf80..17f5df11e3 100644 --- a/internal/testutil/acc/pre_check.go +++ b/internal/testutil/acc/pre_check.go @@ -4,6 +4,9 @@ import ( "os" "strings" "testing" + "time" + + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" ) func PreCheckBasic(tb testing.TB) { @@ -17,11 +20,16 @@ func PreCheckBasic(tb testing.TB) { // PreCheckBasicSleep is a helper function to call SerialSleep, see its help for more info. // Some examples of use are when the test is calling ProjectIDExecution or GetClusterInfo to create clusters. -func PreCheckBasicSleep(tb testing.TB) func() { +func PreCheckBasicSleep(tb testing.TB, clusterInfo *ClusterInfo, projectID, clusterName string) func() { tb.Helper() return func() { PreCheckBasic(tb) SerialSleep(tb) + if clusterInfo != nil { + projectID = clusterInfo.ProjectID + clusterName = clusterInfo.Name + } + tb.Logf("Time before creating cluster: %s, ProjectID: %s, Cluster name: %s", conversion.TimeToString(time.Now()), projectID, clusterName) } } From 13bdf24038c39a41af2b07b7547227ec095f265f Mon Sep 17 00:00:00 2001 From: Oriol Date: Mon, 28 Oct 2024 09:42:21 +0100 Subject: [PATCH 19/35] fix: Adds new attribute `results` and deprecates `resource_policies` for `mongodbatlas_resource_policies` data source (#2740) * new attribute results and deprecate resource_policies * changelog entry * change test to check new attribute * fix changelog * changelog fix * fix docs * Update .changelog/2740.txt Co-authored-by: Leo Antoli <430982+lantoli@users.noreply.github.com> * migration test * skip mig test until next version * fix comment --------- Co-authored-by: Leo Antoli <430982+lantoli@users.noreply.github.com> --- .changelog/2740.txt | 7 +++ docs/data-sources/resource_policies.md | 48 ++++++++++++++++++- docs/data-sources/resource_policy.md | 2 +- docs/resources/resource_policy.md | 2 +- examples/mongodbatlas_resource_policy/main.tf | 2 +- internal/service/resourcepolicy/model.go | 1 + .../plural_data_source_schema.go | 10 ++++ .../resourcepolicy/resource_migration_test.go | 2 +- .../service/resourcepolicy/resource_test.go | 6 +-- 9 files changed, 71 insertions(+), 9 deletions(-) create mode 100644 .changelog/2740.txt diff --git a/.changelog/2740.txt b/.changelog/2740.txt new file mode 100644 index 0000000000..179c07ea1b --- /dev/null +++ b/.changelog/2740.txt @@ -0,0 +1,7 @@ +```release-note:enhancement +data-source/mongodbatlas_resource_policies: Adds `results` attribute +``` + +```release-note:note +data-source/mongodbatlas_resource_policies: Deprecates `resource_policies` attribute +``` diff --git a/docs/data-sources/resource_policies.md b/docs/data-sources/resource_policies.md index daf1d45560..792fb4a5f9 100644 --- a/docs/data-sources/resource_policies.md +++ b/docs/data-sources/resource_policies.md @@ -84,7 +84,7 @@ data "mongodbatlas_resource_policies" "this" { output "policy_ids" { - value = { for policy in data.mongodbatlas_resource_policies.this.resource_policies : policy.name => policy.id } + value = { for policy in data.mongodbatlas_resource_policies.this.results : policy.name => policy.id } } ``` @@ -97,7 +97,8 @@ output "policy_ids" { ### Read-Only -- `resource_policies` (Attributes List) (see [below for nested schema](#nestedatt--resource_policies)) +- `resource_policies` (Attributes List, Deprecated) (see [below for nested schema](#nestedatt--resource_policies)) +- `results` (Attributes List) (see [below for nested schema](#nestedatt--results)) ### Nested Schema for `resource_policies` @@ -140,3 +141,46 @@ Read-Only: - `body` (String) A string that defines the permissions for the policy. The syntax used is the Cedar Policy language. - `id` (String) Unique 24-hexadecimal character string that identifies the policy. + + + +### Nested Schema for `results` + +Read-Only: + +- `created_by_user` (Attributes) The user that last updated the Atlas resource policy. (see [below for nested schema](#nestedatt--results--created_by_user)) +- `created_date` (String) Date and time in UTC when the Atlas resource policy was created. +- `id` (String) Unique 24-hexadecimal digit string that identifies an Atlas resource policy. +- `last_updated_by_user` (Attributes) The user that last updated the Atlas resource policy. (see [below for nested schema](#nestedatt--results--last_updated_by_user)) +- `last_updated_date` (String) Date and time in UTC when the Atlas resource policy was last updated. +- `name` (String) Human-readable label that describes the Atlas resource policy. +- `org_id` (String) Unique 24-hexadecimal digit string that identifies the organization that contains your projects. Use the [/orgs](#tag/Organizations/operation/listOrganizations) endpoint to retrieve all organizations to which the authenticated user has access. +- `policies` (Attributes List) List of policies that make up the Atlas resource policy. (see [below for nested schema](#nestedatt--results--policies)) +- `version` (String) A string that identifies the version of the Atlas resource policy. + + +### Nested Schema for `results.created_by_user` + +Read-Only: + +- `id` (String) Unique 24-hexadecimal character string that identifies a user. +- `name` (String) Human-readable label that describes a user. + + + +### Nested Schema for `results.last_updated_by_user` + +Read-Only: + +- `id` (String) Unique 24-hexadecimal character string that identifies a user. +- `name` (String) Human-readable label that describes a user. + + + +### Nested Schema for `results.policies` + +Read-Only: + +- `body` (String) A string that defines the permissions for the policy. The syntax used is the Cedar Policy language. +- `id` (String) Unique 24-hexadecimal character string that identifies the policy. + diff --git a/docs/data-sources/resource_policy.md b/docs/data-sources/resource_policy.md index 1405e79239..28ed9c64dd 100644 --- a/docs/data-sources/resource_policy.md +++ b/docs/data-sources/resource_policy.md @@ -84,7 +84,7 @@ data "mongodbatlas_resource_policies" "this" { output "policy_ids" { - value = { for policy in data.mongodbatlas_resource_policies.this.resource_policies : policy.name => policy.id } + value = { for policy in data.mongodbatlas_resource_policies.this.results : policy.name => policy.id } } ``` diff --git a/docs/resources/resource_policy.md b/docs/resources/resource_policy.md index 60063f6956..023db662db 100644 --- a/docs/resources/resource_policy.md +++ b/docs/resources/resource_policy.md @@ -86,7 +86,7 @@ data "mongodbatlas_resource_policies" "this" { output "policy_ids" { - value = { for policy in data.mongodbatlas_resource_policies.this.resource_policies : policy.name => policy.id } + value = { for policy in data.mongodbatlas_resource_policies.this.results : policy.name => policy.id } } ``` diff --git a/examples/mongodbatlas_resource_policy/main.tf b/examples/mongodbatlas_resource_policy/main.tf index e0bb93ab8c..f055c3ad05 100644 --- a/examples/mongodbatlas_resource_policy/main.tf +++ b/examples/mongodbatlas_resource_policy/main.tf @@ -74,5 +74,5 @@ data "mongodbatlas_resource_policies" "this" { output "policy_ids" { - value = { for policy in data.mongodbatlas_resource_policies.this.resource_policies : policy.name => policy.id } + value = { for policy in data.mongodbatlas_resource_policies.this.results : policy.name => policy.id } } diff --git a/internal/service/resourcepolicy/model.go b/internal/service/resourcepolicy/model.go index d7ec3662e3..bf514496ca 100644 --- a/internal/service/resourcepolicy/model.go +++ b/internal/service/resourcepolicy/model.go @@ -82,6 +82,7 @@ func NewTFModelDSP(ctx context.Context, orgID string, input []admin.ApiAtlasReso } return &TFModelDSP{ ResourcePolicies: tfModels, + Results: tfModels, OrgID: types.StringValue(orgID), }, *diags } diff --git a/internal/service/resourcepolicy/plural_data_source_schema.go b/internal/service/resourcepolicy/plural_data_source_schema.go index 1efd8a3aa6..bfe843386d 100644 --- a/internal/service/resourcepolicy/plural_data_source_schema.go +++ b/internal/service/resourcepolicy/plural_data_source_schema.go @@ -2,8 +2,10 @@ package resourcepolicy import ( "context" + "fmt" "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/constant" "github.com/hashicorp/terraform-plugin-framework/datasource/schema" ) @@ -18,6 +20,13 @@ func DataSourcePluralSchema(ctx context.Context) schema.Schema { MarkdownDescription: "Unique 24-hexadecimal digit string that identifies the organization that contains your projects. Use the [/orgs](#tag/Organizations/operation/listOrganizations) endpoint to retrieve all organizations to which the authenticated user has access.", }, "resource_policies": schema.ListNestedAttribute{ + DeprecationMessage: fmt.Sprintf(constant.DeprecationParamWithReplacement, "`results`"), + NestedObject: schema.NestedAttributeObject{ + Attributes: dsAttributes, + }, + Computed: true, + }, + "results": schema.ListNestedAttribute{ NestedObject: schema.NestedAttributeObject{ Attributes: dsAttributes, }, @@ -30,4 +39,5 @@ func DataSourcePluralSchema(ctx context.Context) schema.Schema { type TFModelDSP struct { OrgID types.String `tfsdk:"org_id"` ResourcePolicies []TFModel `tfsdk:"resource_policies"` + Results []TFModel `tfsdk:"results"` } diff --git a/internal/service/resourcepolicy/resource_migration_test.go b/internal/service/resourcepolicy/resource_migration_test.go index 4ae76015c5..d7ebd7fa8d 100644 --- a/internal/service/resourcepolicy/resource_migration_test.go +++ b/internal/service/resourcepolicy/resource_migration_test.go @@ -7,6 +7,6 @@ import ( ) func TestMigResourcePolicy_basic(t *testing.T) { - mig.SkipIfVersionBelow(t, "1.21.0") // this feature was introduced in provider version 1.21.0 + mig.SkipIfVersionBelow(t, "1.22.0") // this feature was introduced in provider version 1.21.0, plural data source schema was changed in 1.22.0 mig.CreateAndRunTestNonParallel(t, basicTestCase(t)) } diff --git a/internal/service/resourcepolicy/resource_test.go b/internal/service/resourcepolicy/resource_test.go index b3f2a1b19e..112bcf5dde 100644 --- a/internal/service/resourcepolicy/resource_test.go +++ b/internal/service/resourcepolicy/resource_test.go @@ -158,15 +158,15 @@ func checksResourcePolicy(orgID, name string, policyCount int) resource.TestChec "version", } pluralMap := map[string]string{ - "org_id": orgID, - "resource_policies.#": "1", + "org_id": orgID, + "results.#": "1", } checks := []resource.TestCheckFunc{checkExists()} checks = acc.AddAttrChecks(dataSourcePluralID, checks, pluralMap) for i := 0; i < policyCount; i++ { checks = acc.AddAttrSetChecks(resourceID, checks, fmt.Sprintf("policies.%d.body", i), fmt.Sprintf("policies.%d.id", i)) checks = acc.AddAttrSetChecks(dataSourceID, checks, fmt.Sprintf("policies.%d.body", i), fmt.Sprintf("policies.%d.id", i)) - checks = acc.AddAttrSetChecks(dataSourcePluralID, checks, fmt.Sprintf("resource_policies.0.policies.%d.body", i), fmt.Sprintf("resource_policies.0.policies.%d.id", i)) + checks = acc.AddAttrSetChecks(dataSourcePluralID, checks, fmt.Sprintf("results.0.policies.%d.body", i), fmt.Sprintf("results.0.policies.%d.id", i)) } // cannot use dataSourcePluralID as it doesn't have the `results` attribute return acc.CheckRSAndDS(resourceID, &dataSourceID, nil, attrSet, attrMap, resource.ComposeAggregateTestCheckFunc(checks...)) From c895638ddf9c4b67b26e093b0d6d41666e909891 Mon Sep 17 00:00:00 2001 From: svc-apix-bot Date: Mon, 28 Oct 2024 08:44:06 +0000 Subject: [PATCH 20/35] chore: Updates CHANGELOG.md for #2740 --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 14064d6f27..faf591f23f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ ## (Unreleased) +NOTES: + +* data-source/mongodbatlas_resource_policies: Deprecates `resource_policies` attribute ([#2740](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2740)) + +ENHANCEMENTS: + +* data-source/mongodbatlas_resource_policies: Adds `results` attribute ([#2740](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2740)) + ## 1.21.3 (October 25, 2024) NOTES: From e08f9de6852d2166bd1ae6508809aeb5f1018619 Mon Sep 17 00:00:00 2001 From: svc-apix-Bot <142542575+svc-apix-Bot@users.noreply.github.com> Date: Tue, 29 Oct 2024 09:24:42 +0000 Subject: [PATCH 21/35] build(deps): bump go.mongodb.org/atlas-sdk (#2745) Co-authored-by: wtrocki <981838+wtrocki@users.noreply.github.com> --- go.mod | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/go.mod b/go.mod index eb95523f89..33cf3e63f1 100644 --- a/go.mod +++ b/go.mod @@ -18,9 +18,10 @@ require ( github.com/hashicorp/terraform-plugin-sdk v1.17.2 github.com/hashicorp/terraform-plugin-sdk/v2 v2.34.0 github.com/hashicorp/terraform-plugin-testing v1.9.0 + github.com/huandu/xstrings v1.3.3 github.com/mongodb-forks/digest v1.1.0 - github.com/sebdah/goldie/v2 v2.5.5 github.com/pb33f/libopenapi v0.18.1 + github.com/sebdah/goldie/v2 v2.5.5 github.com/spf13/cast v1.6.0 github.com/stretchr/testify v1.9.0 github.com/zclconf/go-cty v1.15.0 @@ -89,7 +90,6 @@ require ( github.com/hashicorp/terraform-registry-address v0.2.3 // indirect github.com/hashicorp/terraform-svchost v0.1.1 // indirect github.com/hashicorp/yamux v0.1.1 // indirect - github.com/huandu/xstrings v1.3.3 // indirect github.com/imdario/mergo v0.3.15 // indirect github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect From 641090be8146edc96806abfc6443eafeef4f042a Mon Sep 17 00:00:00 2001 From: Leo Antoli <430982+lantoli@users.noreply.github.com> Date: Tue, 29 Oct 2024 10:37:41 +0100 Subject: [PATCH 22/35] fix: Fixes change assigments in `mongodbatlas_project_api_key` (#2737) * fix changed assigments * fix TestAccProjectAPIKey_updateRole * changelog * join configMultiple to configBasic * don't allow duplicate projectIDs * fix TestAccProjectAPIKey_dataSources * refactor Create * refactor getAPIProjectAssignments and flattenProjectAssignments * refactor Read * refactor Delete * fix TestAccProjectAPIKey_recreateWhenDeletedExternally * refactor Import * remove flattenProjectAssignments, flattenProjectAPIKeyRoles and getAPIProjectAssignments * fix plural ds * fix basicTestCase * refactor Update description * refactor Update * refactor expandProjectAssignments * update changelog * initial checkAggr * checkExists * delete redundant TestAccProjectAPIKey_dataSources * refactor configDuplicatedProject * refactor configChangingProject * model file * more detailed changelog * revert import * doc * refactor checks --- .changelog/2737.txt | 3 + .../data_source_project_api_key.go | 10 +- .../data_source_project_api_keys.go | 18 +- .../projectapikey/model_project_api_key.go | 101 +++++ .../projectapikey/resource_project_api_key.go | 406 ++++-------------- .../resource_project_api_key_test.go | 274 +++++++----- internal/testutil/acc/attribute_checks.go | 19 + 7 files changed, 393 insertions(+), 438 deletions(-) create mode 100644 .changelog/2737.txt create mode 100644 internal/service/projectapikey/model_project_api_key.go diff --git a/.changelog/2737.txt b/.changelog/2737.txt new file mode 100644 index 0000000000..2622c46cd9 --- /dev/null +++ b/.changelog/2737.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/mongodbatlas_project_api_key: Validates `project_id` are unique across `project_assignment` blocks and fixes update issues with error `API_KEY_ALREADY_IN_GROUP` +``` diff --git a/internal/service/projectapikey/data_source_project_api_key.go b/internal/service/projectapikey/data_source_project_api_key.go index eb335115a5..8004eaf680 100644 --- a/internal/service/projectapikey/data_source_project_api_key.go +++ b/internal/service/projectapikey/data_source_project_api_key.go @@ -84,10 +84,12 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return diag.FromErr(fmt.Errorf("error setting `private_key`: %s", err)) } - if projectAssignments, err := newProjectAssignment(ctx, connV2, apiKeyID); err == nil { - if err := d.Set("project_assignment", projectAssignments); err != nil { - return diag.Errorf(ErrorProjectSetting, `project_assignment`, projectID, err) - } + details, _, err := getKeyDetails(ctx, connV2, apiKeyID) + if err != nil { + return diag.FromErr(fmt.Errorf("error getting api key information: %s", err)) + } + if err := d.Set("project_assignment", flattenProjectAssignments(details.GetRoles())); err != nil { + return diag.FromErr(fmt.Errorf("error setting `project_assignment`: %s", err)) } } diff --git a/internal/service/projectapikey/data_source_project_api_keys.go b/internal/service/projectapikey/data_source_project_api_keys.go index 7bcaa70b55..c0850baa2e 100644 --- a/internal/service/projectapikey/data_source_project_api_keys.go +++ b/internal/service/projectapikey/data_source_project_api_keys.go @@ -7,6 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "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/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "go.mongodb.org/atlas-sdk/v20240805005/admin" ) @@ -76,12 +77,12 @@ func PluralDataSource() *schema.Resource { func pluralDataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { connV2 := meta.(*config.MongoDBClient).AtlasV2 - pageNum := d.Get("page_num").(int) - itemsPerPage := d.Get("items_per_page").(int) - - projectID := d.Get("project_id").(string) - - apiKeys, _, err := connV2.ProgrammaticAPIKeysApi.ListProjectApiKeys(ctx, projectID).PageNum(pageNum).ItemsPerPage(itemsPerPage).Execute() + params := &admin.ListProjectApiKeysApiParams{ + GroupId: d.Get("project_id").(string), + PageNum: conversion.IntPtr(d.Get("page_num").(int)), + ItemsPerPage: conversion.IntPtr(d.Get("items_per_page").(int)), + } + apiKeys, _, err := connV2.ProgrammaticAPIKeysApi.ListProjectApiKeysWithParams(ctx, params).Execute() if err != nil { return diag.FromErr(fmt.Errorf("error getting api keys information: %s", err)) } @@ -116,12 +117,11 @@ func flattenProjectAPIKeys(ctx context.Context, connV2 *admin.APIClient, apiKeys "private_key": apiKey.GetPrivateKey(), } - projectAssignment, err := newProjectAssignment(ctx, connV2, apiKey.GetId()) + details, _, err := getKeyDetails(ctx, connV2, apiKey.GetId()) if err != nil { return nil, err } - - results[k]["project_assignment"] = projectAssignment + results[k]["project_assignment"] = flattenProjectAssignments(details.GetRoles()) } return results, nil } diff --git a/internal/service/projectapikey/model_project_api_key.go b/internal/service/projectapikey/model_project_api_key.go new file mode 100644 index 0000000000..95db220ce8 --- /dev/null +++ b/internal/service/projectapikey/model_project_api_key.go @@ -0,0 +1,101 @@ +package projectapikey + +import ( + "context" + "fmt" + "reflect" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" + "go.mongodb.org/atlas-sdk/v20240805005/admin" +) + +func expandProjectAssignments(projectAssignments *schema.Set) map[string][]string { + results := make(map[string][]string) + for _, val := range projectAssignments.List() { + results[val.(map[string]any)["project_id"].(string)] = conversion.ExpandStringList(val.(map[string]any)["role_names"].(*schema.Set).List()) + } + return results +} + +func flattenProjectAssignments(roles []admin.CloudAccessRoleAssignment) []map[string]any { + assignments := make(map[string][]string) + for _, role := range roles { + if groupID := role.GetGroupId(); groupID != "" { + assignments[groupID] = append(assignments[groupID], role.GetRoleName()) + } + } + var results []map[string]any + for projectID, roles := range assignments { + results = append(results, map[string]any{ + "project_id": projectID, + "role_names": roles, + }) + } + return results +} + +func getAssignmentChanges(d *schema.ResourceData) (add, remove, update map[string][]string) { + before, after := d.GetChange("project_assignment") + add = expandProjectAssignments(after.(*schema.Set)) + remove = expandProjectAssignments(before.(*schema.Set)) + update = make(map[string][]string) + + for projectID, rolesAfter := range add { + if rolesBefore, ok := remove[projectID]; ok { + if !sameRoles(rolesBefore, rolesAfter) { + update[projectID] = rolesAfter + } + delete(remove, projectID) + delete(add, projectID) + } + } + return +} + +func sameRoles(roles1, roles2 []string) bool { + set1 := make(map[string]struct{}) + for _, role := range roles1 { + set1[role] = struct{}{} + } + set2 := make(map[string]struct{}) + for _, role := range roles2 { + set2[role] = struct{}{} + } + return reflect.DeepEqual(set1, set2) +} + +// getKeyDetails returns nil error and nil details if not found as it's not considered an error +func getKeyDetails(ctx context.Context, connV2 *admin.APIClient, apiKeyID string) (*admin.ApiKeyUserDetails, string, error) { + root, _, err := connV2.RootApi.GetSystemStatus(ctx).Execute() + if err != nil { + return nil, "", err + } + for _, role := range root.ApiKey.GetRoles() { + if orgID := role.GetOrgId(); orgID != "" { + key, _, err := connV2.ProgrammaticAPIKeysApi.GetApiKey(ctx, orgID, apiKeyID).Execute() + if err != nil { + if admin.IsErrorCode(err, "API_KEY_NOT_FOUND") { + return nil, orgID, nil + } + return nil, orgID, fmt.Errorf("error getting api key information: %s", err) + } + return key, orgID, nil + } + } + return nil, "", nil +} + +func validateUniqueProjectIDs(d *schema.ResourceData) error { + if projectAssignments, ok := d.GetOk("project_assignment"); ok { + uniqueIDs := make(map[string]bool) + for _, val := range projectAssignments.(*schema.Set).List() { + projectID := val.(map[string]any)["project_id"].(string) + if uniqueIDs[projectID] { + return fmt.Errorf("duplicated projectID in assignments: %s", projectID) + } + uniqueIDs[projectID] = true + } + } + return nil +} diff --git a/internal/service/projectapikey/resource_project_api_key.go b/internal/service/projectapikey/resource_project_api_key.go index 1a7109e7f2..903c3540c1 100644 --- a/internal/service/projectapikey/resource_project_api_key.go +++ b/internal/service/projectapikey/resource_project_api_key.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "net/http" "strings" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -14,10 +13,6 @@ import ( "go.mongodb.org/atlas-sdk/v20240805005/admin" ) -const ( - ErrorProjectSetting = "error setting `%s` for project (%s): %s" -) - func Resource() *schema.Resource { return &schema.Resource{ CreateContext: resourceCreate, @@ -69,64 +64,47 @@ func Resource() *schema.Resource { } } -type APIProjectAssignmentKeyInput struct { - ProjectID string `json:"desc,omitempty"` - RoleNames []string `json:"roles,omitempty"` -} - -const errorNoProjectAssignmentDefined = "could not obtain a project id as no assignments are defined" - func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + if err := validateUniqueProjectIDs(d); err != nil { + return diag.FromErr(err) + } connV2 := meta.(*config.MongoDBClient).AtlasV2 - - var apiKey *admin.ApiKeyUserDetails - var resp *http.Response - var err error - - createRequest := &admin.CreateAtlasProjectApiKey{ - Desc: d.Get("description").(string), + val, ok := d.GetOk("project_assignment") + if !ok { + return diag.FromErr(errors.New("project_assignment not found")) } - - if projectAssignments, ok := d.GetOk("project_assignment"); ok { - projectAssignmentList := ExpandProjectAssignmentSet(projectAssignments.(*schema.Set)) - - // creates api key using project id of first defined project assignment - firstAssignment := projectAssignmentList[0] - createRequest.Roles = firstAssignment.RoleNames - apiKey, resp, err = connV2.ProgrammaticAPIKeysApi.CreateProjectApiKey(ctx, firstAssignment.ProjectID, createRequest).Execute() - if err != nil { - if resp != nil && resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - return diag.FromErr(err) - } - - // assign created api key to remaining project assignments - for _, apiKeyList := range projectAssignmentList[1:] { - assignment := []admin.UserAccessRoleAssignment{{Roles: &apiKeyList.RoleNames}} - _, _, err := connV2.ProgrammaticAPIKeysApi.AddProjectApiKey(ctx, apiKeyList.ProjectID, apiKey.GetId(), &assignment).Execute() - if err != nil { - if resp != nil && resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - } - } + assignments := expandProjectAssignments(val.(*schema.Set)) + projectIDs := make([]string, 0, len(assignments)) + for projectID := range assignments { + projectIDs = append(projectIDs, projectID) } - if err := d.Set("public_key", apiKey.GetPublicKey()); err != nil { - return diag.FromErr(fmt.Errorf("error setting `public_key`: %s", err)) + req := &admin.CreateAtlasProjectApiKey{ + Desc: d.Get("description").(string), + Roles: assignments[projectIDs[0]], } - - if err := d.Set("private_key", apiKey.GetPrivateKey()); err != nil { - return diag.FromErr(fmt.Errorf("error setting `private_key`: %s", err)) + ret, _, err := connV2.ProgrammaticAPIKeysApi.CreateProjectApiKey(ctx, projectIDs[0], req).Execute() + if err != nil { + return diag.FromErr(err) } - + apiKeyID := ret.GetId() d.SetId(conversion.EncodeStateID(map[string]string{ - "api_key_id": apiKey.GetId(), + "api_key_id": apiKeyID, })) + if err := d.Set("public_key", ret.GetPublicKey()); err != nil { + return diag.FromErr(fmt.Errorf("error setting `public_key`: %s", err)) + } + if err := d.Set("private_key", ret.GetPrivateKey()); err != nil { + return diag.FromErr(fmt.Errorf("error setting `private_key`: %s", err)) + } + for _, projectID := range projectIDs[1:] { + roles := assignments[projectID] + req := &[]admin.UserAccessRoleAssignment{{Roles: &roles}} + if _, _, err := connV2.ProgrammaticAPIKeysApi.AddProjectApiKey(ctx, projectID, apiKeyID, req).Execute(); err != nil { + return diag.FromErr(err) + } + } return resourceRead(ctx, d, meta) } @@ -135,106 +113,83 @@ func resourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Di ids := conversion.DecodeStateID(d.Id()) apiKeyID := ids["api_key_id"] - firstProjectID, err := getFirstProjectIDFromAssignments(d) + details, _, err := getKeyDetails(ctx, connV2, apiKeyID) if err != nil { - return diag.FromErr(fmt.Errorf("could not obtain a project id from state: %s", err)) + return diag.FromErr(err) } - - projectAPIKeys, _, err := connV2.ProgrammaticAPIKeysApi.ListProjectApiKeys(ctx, *firstProjectID).Execute() - if err != nil { - return diag.FromErr(fmt.Errorf("error getting api key information: %s", err)) + if details == nil { + d.SetId("") + return nil } - apiKeyIsPresent := false - for _, val := range projectAPIKeys.GetResults() { - if val.GetId() != apiKeyID { - continue - } - - apiKeyIsPresent = true - if err := d.Set("api_key_id", val.GetId()); err != nil { - return diag.FromErr(fmt.Errorf("error setting `api_key_id`: %s", err)) - } - if err := d.Set("description", val.GetDesc()); err != nil { - return diag.FromErr(fmt.Errorf("error setting `description`: %s", err)) - } - - if err := d.Set("public_key", val.GetPublicKey()); err != nil { - return diag.FromErr(fmt.Errorf("error setting `public_key`: %s", err)) - } + if err := d.Set("api_key_id", details.GetId()); err != nil { + return diag.FromErr(fmt.Errorf("error setting `api_key_id`: %s", err)) + } - if projectAssignments, err := newProjectAssignment(ctx, connV2, apiKeyID); err == nil { - if err := d.Set("project_assignment", projectAssignments); err != nil { - return diag.Errorf("error setting `project_assignment` : %s", err) - } - } + if err := d.Set("description", details.GetDesc()); err != nil { + return diag.FromErr(fmt.Errorf("error setting `description`: %s", err)) } - if !apiKeyIsPresent { - // api key has been deleted, marking resource as destroyed - d.SetId("") - return nil + + if err := d.Set("public_key", details.GetPublicKey()); err != nil { + return diag.FromErr(fmt.Errorf("error setting `public_key`: %s", err)) } + if err := d.Set("project_assignment", flattenProjectAssignments(details.GetRoles())); err != nil { + return diag.Errorf("error setting `project_assignment` : %s", err) + } return nil } func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { - connV2 := meta.(*config.MongoDBClient).AtlasV2 + if err := validateUniqueProjectIDs(d); err != nil { + return diag.FromErr(err) + } + connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) apiKeyID := ids["api_key_id"] + details, orgID, err := getKeyDetails(ctx, connV2, apiKeyID) + if err != nil { + return diag.FromErr(err) + } + if details == nil { + return diag.Errorf("error updating project api_key (%s): not found", apiKeyID) + } + if d.HasChange("project_assignment") { - // Getting the changes to api key project assignments - newAssignments, changedAssignments, removedAssignments := getStateProjectAssignmentAPIKeys(d) + add, remove, update := getAssignmentChanges(d) - // Adding new projects assignments - if len(newAssignments) > 0 { - for _, apiKey := range newAssignments { - projectID := apiKey.(map[string]any)["project_id"].(string) - roles := conversion.ExpandStringList(apiKey.(map[string]any)["role_names"].(*schema.Set).List()) - assignment := []admin.UserAccessRoleAssignment{{Roles: &roles}} - _, _, err := connV2.ProgrammaticAPIKeysApi.AddProjectApiKey(ctx, projectID, apiKeyID, &assignment).Execute() - if err != nil { - return diag.Errorf("error assigning api_keys into the project(%s): %s", projectID, err) + for projectID := range remove { + _, _, err := connV2.ProgrammaticAPIKeysApi.RemoveProjectApiKey(ctx, projectID, apiKeyID).Execute() + if err != nil { + if admin.IsErrorCode(err, "GROUP_NOT_FOUND") { + continue // allows removing assignment for a project that has been deleted } + return diag.Errorf("error removing project_api_key(%s) from project(%s): %s", apiKeyID, projectID, err) } } - // Removing projects assignments - for _, apiKey := range removedAssignments { - projectID := apiKey.(map[string]any)["project_id"].(string) - _, _, err := connV2.ProgrammaticAPIKeysApi.RemoveProjectApiKey(ctx, projectID, apiKeyID).Execute() - if err != nil && strings.Contains(err.Error(), "GROUP_NOT_FOUND") { - continue // allows removing assignment for a project that has been deleted - } + for projectID, roles := range add { + req := &[]admin.UserAccessRoleAssignment{{Roles: &roles}} + _, _, err := connV2.ProgrammaticAPIKeysApi.AddProjectApiKey(ctx, projectID, apiKeyID, req).Execute() if err != nil { - return diag.Errorf("error removing api_key(%s) from the project(%s): %s", apiKeyID, projectID, err) + return diag.Errorf("error adding project_api_key(%s) to project(%s): %s", apiKeyID, projectID, err) } } - // Updating the role names for the project assignments - for _, apiKey := range changedAssignments { - projectID := apiKey.(map[string]any)["project_id"].(string) - roles := conversion.ExpandStringList(apiKey.(map[string]any)["role_names"].(*schema.Set).List()) - assignment := []admin.UserAccessRoleAssignment{{Roles: &roles}} - _, _, err := connV2.ProgrammaticAPIKeysApi.AddProjectApiKey(ctx, projectID, apiKeyID, &assignment).Execute() + for projectID, roles := range update { + req := &admin.UpdateAtlasProjectApiKey{Roles: &roles} + _, _, err := connV2.ProgrammaticAPIKeysApi.UpdateApiKeyRoles(ctx, projectID, apiKeyID, req).Execute() if err != nil { - return diag.Errorf("error updating role names for the api_key(%s): %s", apiKey, err) + return diag.Errorf("error changing project_api_key(%s) in project(%s): %s", apiKeyID, projectID, err) } } } - firstProjectID, err := getFirstProjectIDFromAssignments(d) - if err != nil { - return diag.FromErr(fmt.Errorf("could not obtain a project id from state: %s", err)) - } - if d.HasChange("description") { - newDescription := d.Get("description").(string) - if _, _, err := connV2.ProgrammaticAPIKeysApi.UpdateApiKeyRoles(ctx, *firstProjectID, apiKeyID, &admin.UpdateAtlasProjectApiKey{ - Desc: &newDescription, - }).Execute(); err != nil { + req := &admin.UpdateAtlasOrganizationApiKey{Desc: conversion.StringPtr(d.Get("description").(string))} + if _, _, err := connV2.ProgrammaticAPIKeysApi.UpdateApiKey(ctx, orgID, apiKeyID, req).Execute(); err != nil { return diag.Errorf("error updating description in api key(%s): %s", apiKeyID, err) } } @@ -246,223 +201,30 @@ func resourceDelete(ctx context.Context, d *schema.ResourceData, meta any) diag. connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) apiKeyID := ids["api_key_id"] - var orgID string - - firstProjectID, err := getFirstProjectIDFromAssignments(d) - if err != nil { - return diag.FromErr(fmt.Errorf("could not obtain a project id from state: %s", err)) - } - - projectAPIKeys, _, err := connV2.ProgrammaticAPIKeysApi.ListProjectApiKeys(ctx, *firstProjectID).Execute() - if err != nil { - return diag.FromErr(fmt.Errorf("error getting api key information: %s", err)) - } - - for _, val := range projectAPIKeys.GetResults() { - if val.GetId() == apiKeyID { - for i, role := range val.GetRoles() { - if strings.HasPrefix(role.GetRoleName(), "ORG_") { - orgID = val.GetRoles()[i].GetOrgId() - } - } - } - } - - apiKeyOrgList, _, err := connV2.RootApi.GetSystemStatus(ctx).Execute() - if err != nil { - return diag.FromErr(fmt.Errorf("error getting api key information: %s", err)) - } - - projectAssignments, err := getAPIProjectAssignments(ctx, connV2, apiKeyOrgList, apiKeyID) + details, orgID, err := getKeyDetails(ctx, connV2, apiKeyID) if err != nil { - return diag.FromErr(fmt.Errorf("error getting api key information: %s", err)) - } - - for _, apiKey := range projectAssignments { - _, _, err = connV2.ProgrammaticAPIKeysApi.RemoveProjectApiKey(ctx, apiKey.ProjectID, apiKeyID).Execute() - if err != nil { - return diag.FromErr(fmt.Errorf("error deleting project api key: %s", err)) - } + return diag.FromErr(err) } - - if orgID != "" { + if details != nil && orgID != "" { if _, _, err = connV2.ProgrammaticAPIKeysApi.DeleteApiKey(ctx, orgID, apiKeyID).Execute(); err != nil { - return diag.FromErr(fmt.Errorf("error unable to delete Key (%s): %s", apiKeyID, err)) + return diag.FromErr(fmt.Errorf("error deleting project key (%s): %s", apiKeyID, err)) } } - d.SetId("") return nil } func resourceImportState(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) { - connV2 := meta.(*config.MongoDBClient).AtlasV2 - parts := strings.SplitN(d.Id(), "-", 2) if len(parts) != 2 { return nil, errors.New("import format error: to import a api key use the format {project_id}-{api_key_id}") } - projectID := parts[0] + // projectID is not needed for import any more, but kept to maintain import format and avoid breaking changes apiKeyID := parts[1] - projectAPIKeys, _, err := connV2.ProgrammaticAPIKeysApi.ListProjectApiKeys(ctx, projectID).Execute() - if err != nil { - return nil, fmt.Errorf("couldn't import api key %s in project %s, error: %s", projectID, apiKeyID, err) - } - for _, val := range projectAPIKeys.GetResults() { - if val.GetId() == apiKeyID { - if err := d.Set("description", val.GetDesc()); err != nil { - return nil, fmt.Errorf("error setting `description`: %s", err) - } - - if err := d.Set("public_key", val.GetPublicKey()); err != nil { - return nil, fmt.Errorf("error setting `public_key`: %s", err) - } - - if projectAssignments, err := newProjectAssignment(ctx, connV2, apiKeyID); err == nil { - if err := d.Set("project_assignment", projectAssignments); err != nil { - return nil, fmt.Errorf("error setting `project_assignment`: %s", err) - } - } - - d.SetId(conversion.EncodeStateID(map[string]string{ - "api_key_id": val.GetId(), - })) - } - } + d.SetId(conversion.EncodeStateID(map[string]string{ + "api_key_id": apiKeyID, + })) return []*schema.ResourceData{d}, nil } - -func getFirstProjectIDFromAssignments(d *schema.ResourceData) (*string, error) { - if projectAssignments, ok := d.GetOk("project_assignment"); ok { - projectAssignmentList := ExpandProjectAssignmentSet(projectAssignments.(*schema.Set)) - if len(projectAssignmentList) < 1 { - return nil, errors.New(errorNoProjectAssignmentDefined) - } - return admin.PtrString(projectAssignmentList[0].ProjectID), nil // can safely assume at least one assigment is defined because of schema definition - } - return nil, errors.New(errorNoProjectAssignmentDefined) -} - -func flattenProjectAPIKeyRoles(projectID string, apiKeyRoles []admin.CloudAccessRoleAssignment) []string { - if len(apiKeyRoles) == 0 { - return nil - } - - flattenedOrgRoles := []string{} - - for _, role := range apiKeyRoles { - if strings.HasPrefix(role.GetRoleName(), "GROUP_") && role.GetGroupId() == projectID { - flattenedOrgRoles = append(flattenedOrgRoles, role.GetRoleName()) - } - } - - return flattenedOrgRoles -} - -func ExpandProjectAssignmentSet(projectAssignments *schema.Set) []*APIProjectAssignmentKeyInput { - res := make([]*APIProjectAssignmentKeyInput, projectAssignments.Len()) - - for i, value := range projectAssignments.List() { - v := value.(map[string]any) - res[i] = &APIProjectAssignmentKeyInput{ - ProjectID: v["project_id"].(string), - RoleNames: conversion.ExpandStringList(v["role_names"].(*schema.Set).List()), - } - } - - return res -} - -func newProjectAssignment(ctx context.Context, connV2 *admin.APIClient, apiKeyID string) ([]map[string]any, error) { - apiKeyOrgList, _, err := connV2.RootApi.GetSystemStatus(ctx).Execute() - if err != nil { - return nil, fmt.Errorf("error getting api key information: %s", err) - } - - projectAssignments, err := getAPIProjectAssignments(ctx, connV2, apiKeyOrgList, apiKeyID) - if err != nil { - return nil, fmt.Errorf("error getting api key information: %s", err) - } - - var results []map[string]any - var atlasRoles []admin.CloudAccessRoleAssignment - if len(projectAssignments) > 0 { - results = make([]map[string]any, len(projectAssignments)) - for k, apiKey := range projectAssignments { - for _, roleName := range apiKey.RoleNames { - atlasRole := admin.CloudAccessRoleAssignment{ - GroupId: &apiKey.ProjectID, - RoleName: &roleName, - } - - atlasRoles = append(atlasRoles, atlasRole) - } - results[k] = map[string]any{ - "project_id": apiKey.ProjectID, - "role_names": flattenProjectAPIKeyRoles(apiKey.ProjectID, atlasRoles), - } - } - } - return results, nil -} - -func getStateProjectAssignmentAPIKeys(d *schema.ResourceData) (newAssignments, changedAssignments, removedAssignments []any) { - prevAssignments, currAssignments := d.GetChange("project_assignment") - - rAssignments := prevAssignments.(*schema.Set).Difference(currAssignments.(*schema.Set)) - nAssignments := currAssignments.(*schema.Set).Difference(prevAssignments.(*schema.Set)) - changedAssignments = make([]any, 0) - - for _, changed := range nAssignments.List() { - for _, removed := range rAssignments.List() { - if changed.(map[string]any)["project_id"] == removed.(map[string]any)["project_id"] { - rAssignments.Remove(removed) - } - } - - for _, current := range prevAssignments.(*schema.Set).List() { - if changed.(map[string]any)["project_id"] == current.(map[string]any)["project_id"] { - changedAssignments = append(changedAssignments, changed.(map[string]any)) - nAssignments.Remove(changed) - } - } - } - - newAssignments = nAssignments.List() - removedAssignments = rAssignments.List() - - return -} - -func getAPIProjectAssignments(ctx context.Context, connV2 *admin.APIClient, apiKeyOrgList *admin.SystemStatus, apiKeyID string) ([]APIProjectAssignmentKeyInput, error) { - projectAssignments := []APIProjectAssignmentKeyInput{} - for idx, role := range apiKeyOrgList.ApiKey.GetRoles() { - if !strings.HasPrefix(*role.RoleName, "ORG_") { - continue - } - roles := apiKeyOrgList.ApiKey.GetRoles() - orgKeys, _, err := connV2.ProgrammaticAPIKeysApi.ListApiKeys(ctx, *roles[idx].OrgId).Execute() - if err != nil { - return nil, fmt.Errorf("error getting api key information: %s", err) - } - for _, val := range orgKeys.GetResults() { - if val.GetId() == apiKeyID { - for _, r := range val.GetRoles() { - temp := new(APIProjectAssignmentKeyInput) - if strings.HasPrefix(r.GetRoleName(), "GROUP_") { - temp.ProjectID = r.GetGroupId() - for _, l := range val.GetRoles() { - if l.GetGroupId() == temp.ProjectID { - temp.RoleNames = append(temp.RoleNames, l.GetRoleName()) - } - } - projectAssignments = append(projectAssignments, *temp) - } - } - } - } - } - return projectAssignments, nil -} diff --git a/internal/service/projectapikey/resource_project_api_key_test.go b/internal/service/projectapikey/resource_project_api_key_test.go index 481b3c89c8..d33537d3f7 100644 --- a/internal/service/projectapikey/resource_project_api_key_test.go +++ b/internal/service/projectapikey/resource_project_api_key_test.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "regexp" + "strconv" "strings" "testing" @@ -15,40 +16,37 @@ import ( ) const ( - resourceName = "mongodbatlas_project_api_key.test" - roleName = "GROUP_OWNER" + resourceName = "mongodbatlas_project_api_key.test" + dataSourceName = "data.mongodbatlas_project_api_key.test" + roleName = "GROUP_OWNER" + updatedRoleName = "GROUP_READ_ONLY" ) func TestAccProjectAPIKey_basic(t *testing.T) { resource.ParallelTest(t, *basicTestCase(t)) } -func basicTestCase(tb testing.TB) *resource.TestCase { - tb.Helper() - +func basicTestCase(t *testing.T) *resource.TestCase { + t.Helper() var ( - projectID = acc.ProjectIDExecution(tb) + projectID = acc.ProjectIDExecution(t) description = acc.RandomName() ) - return &resource.TestCase{ - PreCheck: func() { acc.PreCheckBasic(tb) }, + PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy(projectID), Steps: []resource.TestStep{ { - Config: configBasic(projectID, description, roleName), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "description", description), - resource.TestCheckResourceAttrSet(resourceName, "public_key"), - resource.TestCheckResourceAttr(resourceName, "project_assignment.#", "1"), - ), + Config: configBasic(description, projectID, roleName), + Check: check(description, projectID, roleName), }, { - ResourceName: resourceName, - ImportStateIdFunc: importStateIDFunc(resourceName), - ImportState: true, - ImportStateVerify: false, + ResourceName: resourceName, + ImportStateIdFunc: importStateIDFunc(resourceName, projectID), + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"private_key"}, }, }, } @@ -68,62 +66,53 @@ func TestAccProjectAPIKey_changingSingleProject(t *testing.T) { CheckDestroy: checkDestroy(projectID1), Steps: []resource.TestStep{ { - Config: configChangingProject(orgID, projectName2, description, fmt.Sprintf("%q", projectID1)), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "description", description), - resource.TestCheckResourceAttrSet(resourceName, "public_key"), - resource.TestCheckResourceAttr(resourceName, "project_assignment.#", "1"), - ), + Config: configChangingProject(orgID, projectID1, projectName2, description, roleName, true), + Check: check(description, projectID1, roleName), }, { - Config: configChangingProject(orgID, projectName2, description, "mongodbatlas_project.proj2.id"), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "description", description), - resource.TestCheckResourceAttrSet(resourceName, "public_key"), - resource.TestCheckResourceAttr(resourceName, "project_assignment.#", "1"), - ), + Config: configChangingProject(orgID, projectID1, projectName2, description, roleName, false), + Check: check(description, projectName2, roleName), + }, + { + Config: configChangingProject(orgID, projectID1, projectName2, description, roleName+","+updatedRoleName, false), + Check: check(description, projectName2, roleName+","+updatedRoleName), + }, + { + Config: configChangingProject(orgID, projectID1, projectName2, description, roleName+","+updatedRoleName, true), + Check: check(description, projectID1, roleName+","+updatedRoleName), }, }, }) } -func TestAccProjectAPIKey_multiple(t *testing.T) { +func TestAccProjectAPIKey_updateDescription(t *testing.T) { var ( - dataSourceName = "data.mongodbatlas_project_api_key.test" - dataSourcesName = "data.mongodbatlas_project_api_keys.test" - projectID = acc.ProjectIDExecution(t) - description = acc.RandomName() + projectID = acc.ProjectIDExecution(t) + description = acc.RandomName() + updatedDescription = acc.RandomName() ) - resource.Test(t, resource.TestCase{ + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy(projectID), Steps: []resource.TestStep{ { - Config: configMultiple(projectID, description, roleName), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet(resourceName, "description"), - resource.TestCheckResourceAttr(resourceName, "description", description), - resource.TestCheckResourceAttrSet(resourceName, "project_assignment.0.project_id"), - resource.TestCheckResourceAttrSet(resourceName, "project_assignment.0.role_names.0"), - resource.TestCheckResourceAttrSet(dataSourceName, "project_assignment.0.project_id"), - resource.TestCheckResourceAttrSet(dataSourceName, "project_assignment.0.role_names.0"), - resource.TestCheckResourceAttrSet(dataSourceName, "project_id"), - resource.TestCheckResourceAttrSet(dataSourceName, "description"), - resource.TestCheckResourceAttrSet(dataSourcesName, "results.0.project_assignment.0.project_id"), - resource.TestCheckResourceAttrSet(dataSourcesName, "results.0.project_assignment.0.role_names.0"), - ), + Config: configBasic(description, projectID, roleName), + Check: check(description, projectID, roleName), + }, + { + Config: configBasic(updatedDescription, projectID, roleName), + Check: check(updatedDescription, projectID, roleName), }, }, }) } -func TestAccProjectAPIKey_updateDescription(t *testing.T) { +func TestAccProjectAPIKey_updateRole(t *testing.T) { var ( - projectID = acc.ProjectIDExecution(t) - description = acc.RandomName() - updatedDescription = acc.RandomName() + projectID = acc.ProjectIDExecution(t) + description = acc.RandomName() ) resource.ParallelTest(t, resource.TestCase{ @@ -132,18 +121,31 @@ func TestAccProjectAPIKey_updateDescription(t *testing.T) { CheckDestroy: checkDestroy(projectID), Steps: []resource.TestStep{ { - Config: configBasic(projectID, description, roleName), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet(resourceName, "description"), - resource.TestCheckResourceAttr(resourceName, "description", description), - ), + Config: configBasic(description, projectID, roleName), + Check: check(description, projectID, roleName), }, { - Config: configBasic(projectID, updatedDescription, roleName), - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet(resourceName, "description"), - resource.TestCheckResourceAttr(resourceName, "description", updatedDescription), - ), + Config: configBasic(description, projectID, updatedRoleName), + Check: check(description, projectID, updatedRoleName), + }, + }, + }) +} + +func TestAccProjectAPIKey_duplicateProject(t *testing.T) { + var ( + projectID = acc.ProjectIDExecution(t) + description = acc.RandomName() + ) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acc.PreCheckBasic(t) }, + ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, + CheckDestroy: checkDestroy(projectID), + Steps: []resource.TestStep{ + { + Config: configDuplicatedProject(description, projectID, roleName, updatedRoleName), + ExpectError: regexp.MustCompile("duplicated projectID in assignments: " + projectID), }, }, }) @@ -155,20 +157,17 @@ func TestAccProjectAPIKey_recreateWhenDeletedExternally(t *testing.T) { projectID = acc.ProjectIDExecution(t) descriptionPrefix = acc.RandomName() description = descriptionPrefix + "-" + acc.RandomName() + config = configBasic(description, projectID, roleName) ) - projectAPIKeyConfig := configBasic(projectID, description, roleName) - resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acc.PreCheckBasic(t) }, ProtoV6ProviderFactories: acc.TestAccProviderV6Factories, CheckDestroy: checkDestroy(projectID), Steps: []resource.TestStep{ { - Config: projectAPIKeyConfig, - Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet(resourceName, "description"), - ), + Config: config, + Check: check(description, projectID, roleName), }, { PreConfig: func() { @@ -176,7 +175,7 @@ func TestAccProjectAPIKey_recreateWhenDeletedExternally(t *testing.T) { t.Fatalf("failed to manually delete API key resource: %s", err) } }, - Config: projectAPIKeyConfig, + Config: config, PlanOnly: true, ExpectNonEmptyPlan: true, // should detect that api key has to be recreated }, @@ -218,7 +217,6 @@ func TestAccProjectAPIKey_invalidRole(t *testing.T) { var ( projectID = acc.ProjectIDExecution(t) description = fmt.Sprintf("desc-%s", projectID) - roleName = "INVALID_ROLE" ) resource.ParallelTest(t, resource.TestCase{ @@ -227,7 +225,7 @@ func TestAccProjectAPIKey_invalidRole(t *testing.T) { CheckDestroy: checkDestroy(projectID), Steps: []resource.TestStep{ { - Config: configBasic(projectID, description, roleName), + Config: configBasic(description, projectID, "INVALID_ROLE"), ExpectError: regexp.MustCompile("INVALID_ENUM_VALUE"), }, }, @@ -262,7 +260,7 @@ func checkDestroy(projectID string) resource.TestCheckFunc { ids := conversion.DecodeStateID(rs.Primary.ID) for _, val := range projectAPIKeys.GetResults() { if val.GetId() == ids["api_key_id"] { - return fmt.Errorf("Project API Key (%s) still exists", ids["role_name"]) + return fmt.Errorf("Project API Key (%s) still exists", ids["api_key_id"]) } } } @@ -270,32 +268,69 @@ func checkDestroy(projectID string) resource.TestCheckFunc { } } -func importStateIDFunc(resourceName string) resource.ImportStateIdFunc { +func checkExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("not found: %s", resourceName) + } + if rs.Primary.ID == "" { + return fmt.Errorf("no ID is set") + } + ids := conversion.DecodeStateID(rs.Primary.ID) + apiKeyID := ids["api_key_id"] + orgID := os.Getenv("MONGODB_ATLAS_ORG_ID") + if found, _, _ := acc.ConnV2().ProgrammaticAPIKeysApi.GetApiKey(context.Background(), orgID, apiKeyID).Execute(); found == nil { + return fmt.Errorf("API Key (%s) does not exist", apiKeyID) + } + return nil + } +} + +func importStateIDFunc(resourceName, projectID string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] if !ok { return "", fmt.Errorf("not found: %s", resourceName) } - - projectID := rs.Primary.Attributes["project_assignment.0.project_id"] - return fmt.Sprintf("%s-%s", projectID, rs.Primary.Attributes["api_key_id"]), nil } } -func configBasic(projectID, description, roleNames string) string { +func configBasic(description, projectID, roleNames string) string { return fmt.Sprintf(` resource "mongodbatlas_project_api_key" "test" { - description = %[2]q + description = %[1]q project_assignment { - project_id = %[1]q + project_id = %[2]q role_names = [%[3]q] } } - `, projectID, description, roleNames) + %[4]s + `, description, projectID, roleNames, configDataSources(fmt.Sprintf("%q", projectID))) } -func configChangingProject(orgID, projectName2, description, assignedProject string) string { +func configDuplicatedProject(description, projectID, roleNames1, roleName2 string) string { + return fmt.Sprintf(` + resource "mongodbatlas_project_api_key" "test" { + description = %[1]q + project_assignment { + project_id = %[2]q + role_names = [%[3]q] + } + project_assignment { + project_id = %[2]q + role_names = [%[4]q] + } + } + `, description, projectID, roleNames1, roleName2) +} + +func configChangingProject(orgID, projectID1, projectName2, description, roleNames string, useProject1 bool) string { + projectIDStr := "mongodbatlas_project.proj2.id" + if useProject1 { + projectIDStr = fmt.Sprintf("%q", projectID1) + } return fmt.Sprintf(` resource "mongodbatlas_project" "proj2" { org_id = %[1]q @@ -306,30 +341,28 @@ func configChangingProject(orgID, projectName2, description, assignedProject str description = %[3]q project_assignment { project_id = %[4]s - role_names = ["GROUP_OWNER"] + role_names = %[5]s } - } - `, orgID, projectName2, description, assignedProject) + depends_on = [mongodbatlas_project.proj2] + } + %[6]s + `, orgID, projectName2, description, projectIDStr, getRoleNamesStr(roleNames), configDataSources(projectIDStr)) } -func configMultiple(projectID, description, roleNames string) string { - return fmt.Sprintf(` - resource "mongodbatlas_project_api_key" "test" { - description = %[2]q - project_assignment { - project_id = %[1]q - role_names = [%[3]q] - } - } - data "mongodbatlas_project_api_key" "test" { - project_id = %[1]q - api_key_id = mongodbatlas_project_api_key.test.api_key_id - } - - data "mongodbatlas_project_api_keys" "test" { - project_id = %[1]q - } - `, projectID, description, roleNames) +func getRoleNames(roleNames string) []string { + var ret []string + for _, role := range strings.Split(roleNames, ",") { + ret = append(ret, strings.TrimSpace(role)) + } + return ret +} + +func getRoleNamesStr(roleNames string) string { + var quoted []string + for _, role := range strings.Split(roleNames, ",") { + quoted = append(quoted, fmt.Sprintf("%q", strings.TrimSpace(role))) + } + return fmt.Sprintf("[%s]", strings.Join(quoted, ", ")) } func configDeletedProjectAndAssignment(orgID, projectID1, projectName2, description string, includeSecondProject bool) string { @@ -360,3 +393,38 @@ func configDeletedProjectAndAssignment(orgID, projectID1, projectName2, descript } `, projectID1, description, secondProject, secondProjectAssignment) } + +func configDataSources(projectIDStr string) string { + return fmt.Sprintf(` + data "mongodbatlas_project_api_key" "test" { + project_id = %[1]s + api_key_id = mongodbatlas_project_api_key.test.api_key_id + } + + data "mongodbatlas_project_api_keys" "test" { + project_id = %[1]s + depends_on = [mongodbatlas_project_api_key.test] + } + `, projectIDStr) +} + +func check(description, projectNameOrID, roleNames string) resource.TestCheckFunc { + roles := getRoleNames(roleNames) + attrsMap := map[string]string{ + "description": description, + "project_assignment.#": "1", + "project_assignment.0.role_names.#": strconv.Itoa(len(roles)), + } + attrs := []string{"public_key", "private_key"} + checks := []resource.TestCheckFunc{ + checkExists(resourceName), + resource.TestCheckResourceAttrWith(resourceName, "project_assignment.0.project_id", acc.IsProjectNameOrID(projectNameOrID)), + resource.TestCheckResourceAttrWith(dataSourceName, "project_assignment.0.project_id", acc.IsProjectNameOrID(projectNameOrID)), + } + for _, role := range roles { + checks = append(checks, + resource.TestCheckTypeSetElemAttr(resourceName, "project_assignment.0.role_names.*", role), + resource.TestCheckTypeSetElemAttr(dataSourceName, "project_assignment.0.role_names.*", role)) + } + return acc.CheckRSAndDS(resourceName, conversion.Pointer(dataSourceName), nil, attrs, attrsMap, checks...) +} diff --git a/internal/testutil/acc/attribute_checks.go b/internal/testutil/acc/attribute_checks.go index b0e1f6e7a4..398d92a4e2 100644 --- a/internal/testutil/acc/attribute_checks.go +++ b/internal/testutil/acc/attribute_checks.go @@ -1,6 +1,7 @@ package acc import ( + "context" "encoding/json" "fmt" "net" @@ -65,6 +66,24 @@ func JSONEquals(expected string) resource.CheckResourceAttrWithFunc { } } +// IsProjectNameOrID accepts a project id or name and checks if the input project id matches the expected project +func IsProjectNameOrID(expected string) resource.CheckResourceAttrWithFunc { + return func(input string) error { + projectID := expected + if startNumber, _ := regexp.MatchString(`^\d`, expected); !startNumber { + resp, _, _ := ConnV2().ProjectsApi.GetProjectByName(context.Background(), expected).Execute() + projectID = resp.GetId() + if projectID == "" { + return fmt.Errorf("project not found %q", expected) + } + } + if projectID != input { + return fmt.Errorf("project expected %q but got %q", projectID, input) + } + return nil + } +} + // CheckRSAndDS returns a check function that asserts a set of attributes (presence and values) in resource and data sources. // If a plural data source name is provided, it will apply checks over first result func CheckRSAndDS(resourceName string, dataSourceName, pluralDataSourceName *string, attrsSet []string, attrsMap map[string]string, extra ...resource.TestCheckFunc) resource.TestCheckFunc { From a0388f1de8071d6d04afa2cdd1f78b75e15486df Mon Sep 17 00:00:00 2001 From: svc-apix-bot Date: Tue, 29 Oct 2024 09:39:25 +0000 Subject: [PATCH 23/35] chore: Updates CHANGELOG.md for #2737 --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index faf591f23f..232d6d6ff5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ ENHANCEMENTS: * data-source/mongodbatlas_resource_policies: Adds `results` attribute ([#2740](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2740)) +BUG FIXES: + +* resource/mongodbatlas_project_api_key: Validates `project_id` are unique across `project_assignment` blocks and fixes update issues with error `API_KEY_ALREADY_IN_GROUP` ([#2737](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2737)) + ## 1.21.3 (October 25, 2024) NOTES: From 203bd19e7aff2011b5722ffd3b67fbfa2bc23434 Mon Sep 17 00:00:00 2001 From: svc-apix-bot Date: Tue, 29 Oct 2024 09:46:32 +0000 Subject: [PATCH 24/35] chore: Updates examples link in index.md for v1.21.4 release --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index 28c6661683..b294bf3c00 100644 --- a/docs/index.md +++ b/docs/index.md @@ -220,7 +220,7 @@ We ship binaries but do not prioritize fixes for the following operating system ## Examples from MongoDB and the Community -We have [example configurations](https://github.com/mongodb/terraform-provider-mongodbatlas/tree/v1.21.3/examples) +We have [example configurations](https://github.com/mongodb/terraform-provider-mongodbatlas/tree/v1.21.4/examples) in our GitHub repo that will help both beginner and more advanced users. Have a good example you've created and want to share? From 6206f2ed99b9b10011a173ac9facb40ba1aa4d18 Mon Sep 17 00:00:00 2001 From: svc-apix-bot Date: Tue, 29 Oct 2024 09:47:02 +0000 Subject: [PATCH 25/35] chore: Updates CHANGELOG.md header for v1.21.4 release --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 232d6d6ff5..30e87feaff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ ## (Unreleased) +## 1.21.4 (October 29, 2024) + NOTES: * data-source/mongodbatlas_resource_policies: Deprecates `resource_policies` attribute ([#2740](https://github.com/mongodb/terraform-provider-mongodbatlas/pull/2740)) From 5aa19bbf7b56c3fd757ded143c93defceb0fbdbb Mon Sep 17 00:00:00 2001 From: Agustin Bettati Date: Tue, 29 Oct 2024 12:30:02 +0000 Subject: [PATCH 26/35] chore: Support computability override in schema generation config (#2743) * test without parsing config options * add support for override of computability in config * refactor tests removing redudant code * extract common api spec path, handle computed only case --- .../api_to_provider_spec_mapper_test.go | 564 +++++++++--------- tools/codegen/codespec/config.go | 20 +- tools/codegen/codespec/testdata/api-spec.yml | 6 + .../config-nested-schema-overrides.yml | 5 + tools/codegen/config/config_model.go | 2 +- 5 files changed, 309 insertions(+), 288 deletions(-) diff --git a/tools/codegen/codespec/api_to_provider_spec_mapper_test.go b/tools/codegen/codespec/api_to_provider_spec_mapper_test.go index 6eb7129d87..4eb8281883 100644 --- a/tools/codegen/codespec/api_to_provider_spec_mapper_test.go +++ b/tools/codegen/codespec/api_to_provider_spec_mapper_test.go @@ -11,9 +11,10 @@ import ( ) const ( - testFieldDesc = "Test field description" - testResourceDesc = "POST API description" - testPathParamDesc = "Path param test description" + testFieldDesc = "Test field description" + testResourceDesc = "POST API description" + testPathParamDesc = "Path param test description" + testDataAPISpecPath = "testdata/api-spec.yml" ) type convertToSpecTestCase struct { @@ -24,327 +25,318 @@ type convertToSpecTestCase struct { } func TestConvertToProviderSpec(t *testing.T) { - testCases := map[string]convertToSpecTestCase{ - "Valid input": { - inputOpenAPISpecPath: "testdata/api-spec.yml", - inputConfigPath: "testdata/config-no-schema-opts.yml", - inputResourceName: "test_resource", + tc := convertToSpecTestCase{ + inputOpenAPISpecPath: testDataAPISpecPath, + inputConfigPath: "testdata/config-no-schema-opts.yml", + inputResourceName: "test_resource", - expectedResult: &codespec.Model{ - Resources: []codespec.Resource{{ - Schema: &codespec.Schema{ - Description: conversion.StringPtr(testResourceDesc), - Attributes: codespec.Attributes{ - { - Name: "bool_default_attr", - ComputedOptionalRequired: codespec.ComputedOptional, - Bool: &codespec.BoolAttribute{Default: conversion.Pointer(false)}, - }, - { - Name: "count", - ComputedOptionalRequired: codespec.Optional, - Int64: &codespec.Int64Attribute{}, - Description: conversion.StringPtr(testFieldDesc), - }, - { - Name: "create_date", - String: &codespec.StringAttribute{}, - ComputedOptionalRequired: codespec.Computed, - Description: conversion.StringPtr(testFieldDesc), - }, - { - Name: "group_id", - ComputedOptionalRequired: codespec.Required, - String: &codespec.StringAttribute{}, - Description: conversion.StringPtr(testPathParamDesc), - }, - { - Name: "num_double_default_attr", - Float64: &codespec.Float64Attribute{Default: conversion.Pointer(2.0)}, - ComputedOptionalRequired: codespec.ComputedOptional, - }, - { - Name: "str_computed_attr", - ComputedOptionalRequired: codespec.Computed, - String: &codespec.StringAttribute{}, - Description: conversion.StringPtr(testFieldDesc), - }, - { - Name: "str_req_attr1", - ComputedOptionalRequired: codespec.Required, - String: &codespec.StringAttribute{}, - Description: conversion.StringPtr(testFieldDesc), - }, - { - Name: "str_req_attr2", - ComputedOptionalRequired: codespec.Required, - String: &codespec.StringAttribute{}, - Description: conversion.StringPtr(testFieldDesc), - }, - { - Name: "str_req_attr3", - String: &codespec.StringAttribute{}, - ComputedOptionalRequired: codespec.Required, - Description: conversion.StringPtr(testFieldDesc), - }, + expectedResult: &codespec.Model{ + Resources: []codespec.Resource{{ + Schema: &codespec.Schema{ + Description: conversion.StringPtr(testResourceDesc), + Attributes: codespec.Attributes{ + { + Name: "bool_default_attr", + ComputedOptionalRequired: codespec.ComputedOptional, + Bool: &codespec.BoolAttribute{Default: conversion.Pointer(false)}, + }, + { + Name: "count", + ComputedOptionalRequired: codespec.Optional, + Int64: &codespec.Int64Attribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "create_date", + String: &codespec.StringAttribute{}, + ComputedOptionalRequired: codespec.Computed, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "group_id", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testPathParamDesc), + }, + { + Name: "num_double_default_attr", + Float64: &codespec.Float64Attribute{Default: conversion.Pointer(2.0)}, + ComputedOptionalRequired: codespec.ComputedOptional, + }, + { + Name: "str_computed_attr", + ComputedOptionalRequired: codespec.Computed, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "str_req_attr1", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "str_req_attr2", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "str_req_attr3", + String: &codespec.StringAttribute{}, + ComputedOptionalRequired: codespec.Required, + Description: conversion.StringPtr(testFieldDesc), }, }, - Name: "test_resource", }, - }, - }, + Name: "test_resource", + }}, }, } - - for name, tc := range testCases { - t.Run(name, func(t *testing.T) { - result, err := codespec.ToCodeSpecModel(tc.inputOpenAPISpecPath, tc.inputConfigPath, &tc.inputResourceName) - require.NoError(t, err) - assert.Equal(t, tc.expectedResult, result, "Expected result to match the specified structure") - }) - } + runTestCase(t, tc) } func TestConvertToProviderSpec_nested(t *testing.T) { - testCases := map[string]convertToSpecTestCase{ - "Valid input": { - inputOpenAPISpecPath: "testdata/api-spec.yml", - inputConfigPath: "testdata/config-nested-schema.yml", - inputResourceName: "test_resource_with_nested_attr", + tc := convertToSpecTestCase{ + inputOpenAPISpecPath: testDataAPISpecPath, + inputConfigPath: "testdata/config-nested-schema.yml", + inputResourceName: "test_resource_with_nested_attr", - expectedResult: &codespec.Model{ - Resources: []codespec.Resource{{ - Schema: &codespec.Schema{ - Description: conversion.StringPtr(testResourceDesc), - Attributes: codespec.Attributes{ - { - Name: "cluster_name", - ComputedOptionalRequired: codespec.Required, - String: &codespec.StringAttribute{}, - Description: conversion.StringPtr(testPathParamDesc), - }, - { - Name: "group_id", - ComputedOptionalRequired: codespec.Required, - String: &codespec.StringAttribute{}, - Description: conversion.StringPtr(testPathParamDesc), - }, - { - Name: "list_primitive_string_attr", - ComputedOptionalRequired: codespec.Computed, - List: &codespec.ListAttribute{ - ElementType: codespec.String, - }, - Description: conversion.StringPtr(testFieldDesc), + expectedResult: &codespec.Model{ + Resources: []codespec.Resource{{ + Schema: &codespec.Schema{ + Description: conversion.StringPtr(testResourceDesc), + Attributes: codespec.Attributes{ + { + Name: "cluster_name", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testPathParamDesc), + }, + { + Name: "group_id", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testPathParamDesc), + }, + { + Name: "list_primitive_string_attr", + ComputedOptionalRequired: codespec.Computed, + List: &codespec.ListAttribute{ + ElementType: codespec.String, }, - { - Name: "nested_list_array_attr", - ComputedOptionalRequired: codespec.Required, - ListNested: &codespec.ListNestedAttribute{ - NestedObject: codespec.NestedAttributeObject{ - Attributes: codespec.Attributes{ - { - Name: "inner_num_attr", - ComputedOptionalRequired: codespec.Required, - Int64: &codespec.Int64Attribute{}, - Description: conversion.StringPtr(testFieldDesc), - }, - { - Name: "list_primitive_string_attr", - ComputedOptionalRequired: codespec.Optional, - List: &codespec.ListAttribute{ - ElementType: codespec.String, - }, - Description: conversion.StringPtr(testFieldDesc), + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "nested_list_array_attr", + ComputedOptionalRequired: codespec.Required, + ListNested: &codespec.ListNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "inner_num_attr", + ComputedOptionalRequired: codespec.Required, + Int64: &codespec.Int64Attribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "list_primitive_string_attr", + ComputedOptionalRequired: codespec.Optional, + List: &codespec.ListAttribute{ + ElementType: codespec.String, }, - { - Name: "list_primitive_string_computed_attr", - ComputedOptionalRequired: codespec.Computed, - List: &codespec.ListAttribute{ - ElementType: codespec.String, - }, - Description: conversion.StringPtr(testFieldDesc), + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "list_primitive_string_computed_attr", + ComputedOptionalRequired: codespec.Computed, + List: &codespec.ListAttribute{ + ElementType: codespec.String, }, + Description: conversion.StringPtr(testFieldDesc), }, }, }, - Description: conversion.StringPtr(testFieldDesc), }, - { - Name: "nested_map_object_attr", - ComputedOptionalRequired: codespec.Computed, - MapNested: &codespec.MapNestedAttribute{ - NestedObject: codespec.NestedAttributeObject{ - Attributes: codespec.Attributes{ - { - Name: "attr", - ComputedOptionalRequired: codespec.Computed, - String: &codespec.StringAttribute{}, - }, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "nested_map_object_attr", + ComputedOptionalRequired: codespec.Computed, + MapNested: &codespec.MapNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "attr", + ComputedOptionalRequired: codespec.Computed, + String: &codespec.StringAttribute{}, }, }, }, }, - { - Name: "nested_set_array_attr", - ComputedOptionalRequired: codespec.Computed, - SetNested: &codespec.SetNestedAttribute{ - NestedObject: codespec.NestedAttributeObject{ - Attributes: codespec.Attributes{ - { - Name: "inner_num_attr", - ComputedOptionalRequired: codespec.Computed, - Int64: &codespec.Int64Attribute{}, - Description: conversion.StringPtr(testFieldDesc), - }, - { - Name: "list_primitive_string_attr", - ComputedOptionalRequired: codespec.Computed, - List: &codespec.ListAttribute{ - ElementType: codespec.String, - }, - Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "nested_set_array_attr", + ComputedOptionalRequired: codespec.Computed, + SetNested: &codespec.SetNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "inner_num_attr", + ComputedOptionalRequired: codespec.Computed, + Int64: &codespec.Int64Attribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "list_primitive_string_attr", + ComputedOptionalRequired: codespec.Computed, + List: &codespec.ListAttribute{ + ElementType: codespec.String, }, + Description: conversion.StringPtr(testFieldDesc), }, }, }, - Description: conversion.StringPtr(testFieldDesc), }, - { - Name: "set_primitive_string_attr", - ComputedOptionalRequired: codespec.Computed, - Set: &codespec.SetAttribute{ - ElementType: codespec.String, - }, - Description: conversion.StringPtr(testFieldDesc), + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "optional_string_attr", + ComputedOptionalRequired: codespec.Optional, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr("Optional string"), + }, + { + Name: "set_primitive_string_attr", + ComputedOptionalRequired: codespec.Computed, + Set: &codespec.SetAttribute{ + ElementType: codespec.String, }, - { - Name: "single_nested_attr", - ComputedOptionalRequired: codespec.Computed, - SingleNested: &codespec.SingleNestedAttribute{ - NestedObject: codespec.NestedAttributeObject{ - Attributes: codespec.Attributes{ - { - Name: "inner_int_attr", - ComputedOptionalRequired: codespec.Computed, - Int64: &codespec.Int64Attribute{}, - Description: conversion.StringPtr(testFieldDesc), - }, - { - Name: "inner_str_attr", - ComputedOptionalRequired: codespec.Computed, - String: &codespec.StringAttribute{}, - Description: conversion.StringPtr(testFieldDesc), - }, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "single_nested_attr", + ComputedOptionalRequired: codespec.Computed, + SingleNested: &codespec.SingleNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "inner_int_attr", + ComputedOptionalRequired: codespec.Computed, + Int64: &codespec.Int64Attribute{}, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "inner_str_attr", + ComputedOptionalRequired: codespec.Computed, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testFieldDesc), }, }, }, - Description: conversion.StringPtr(testFieldDesc), }, - { - Name: "single_nested_attr_with_nested_maps", - ComputedOptionalRequired: codespec.Computed, - SingleNested: &codespec.SingleNestedAttribute{ - NestedObject: codespec.NestedAttributeObject{ - Attributes: codespec.Attributes{ - { - Name: "map_attr1", - ComputedOptionalRequired: codespec.Computed, - Map: &codespec.MapAttribute{ - ElementType: codespec.String, - }, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "single_nested_attr_with_nested_maps", + ComputedOptionalRequired: codespec.Computed, + SingleNested: &codespec.SingleNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "map_attr1", + ComputedOptionalRequired: codespec.Computed, + Map: &codespec.MapAttribute{ + ElementType: codespec.String, }, - { - Name: "map_attr2", - ComputedOptionalRequired: codespec.Computed, - Map: &codespec.MapAttribute{ - ElementType: codespec.String, - }, + }, + { + Name: "map_attr2", + ComputedOptionalRequired: codespec.Computed, + Map: &codespec.MapAttribute{ + ElementType: codespec.String, }, }, }, }, - Description: conversion.StringPtr(testFieldDesc), }, + Description: conversion.StringPtr(testFieldDesc), }, }, - Name: "test_resource_with_nested_attr", - }, }, + Name: "test_resource_with_nested_attr", + }, }, }, } - - for name, tc := range testCases { - t.Run(name, func(t *testing.T) { - result, err := codespec.ToCodeSpecModel(tc.inputOpenAPISpecPath, tc.inputConfigPath, &tc.inputResourceName) - require.NoError(t, err) - assert.Equal(t, tc.expectedResult, result, "Expected result to match the specified structure") - }) - } + runTestCase(t, tc) } func TestConvertToProviderSpec_nested_schemaOverrides(t *testing.T) { - testCases := map[string]convertToSpecTestCase{ - "Valid input": { - inputOpenAPISpecPath: "testdata/api-spec.yml", - inputConfigPath: "testdata/config-nested-schema-overrides.yml", - inputResourceName: "test_resource_with_nested_attr_overrides", + tc := convertToSpecTestCase{ + inputOpenAPISpecPath: testDataAPISpecPath, + inputConfigPath: "testdata/config-nested-schema-overrides.yml", + inputResourceName: "test_resource_with_nested_attr_overrides", - expectedResult: &codespec.Model{ - Resources: []codespec.Resource{{ - Schema: &codespec.Schema{ - Description: conversion.StringPtr(testResourceDesc), - Attributes: codespec.Attributes{ - { - Name: "project_id", - ComputedOptionalRequired: codespec.Required, - String: &codespec.StringAttribute{}, - Description: conversion.StringPtr(testPathParamDesc), - }, - { - Name: "nested_list_array_attr", - ComputedOptionalRequired: codespec.Required, - ListNested: &codespec.ListNestedAttribute{ - NestedObject: codespec.NestedAttributeObject{ - Attributes: codespec.Attributes{ - { - Name: "inner_num_attr_alias", - ComputedOptionalRequired: codespec.Required, - Int64: &codespec.Int64Attribute{}, - Description: conversion.StringPtr("Overridden inner_num_attr_alias description"), - }, - { - Name: "list_primitive_string_computed_attr", - ComputedOptionalRequired: codespec.Computed, - List: &codespec.ListAttribute{ - ElementType: codespec.String, - }, - Description: conversion.StringPtr(testFieldDesc), + expectedResult: &codespec.Model{ + Resources: []codespec.Resource{{ + Schema: &codespec.Schema{ + Description: conversion.StringPtr(testResourceDesc), + Attributes: codespec.Attributes{ + { + Name: "project_id", + ComputedOptionalRequired: codespec.Required, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr(testPathParamDesc), + }, + { + Name: "nested_list_array_attr", + ComputedOptionalRequired: codespec.Required, + ListNested: &codespec.ListNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "inner_num_attr_alias", + ComputedOptionalRequired: codespec.Required, + Int64: &codespec.Int64Attribute{}, + Description: conversion.StringPtr("Overridden inner_num_attr_alias description"), + }, + { + Name: "list_primitive_string_computed_attr", + ComputedOptionalRequired: codespec.Computed, + List: &codespec.ListAttribute{ + ElementType: codespec.String, }, + Description: conversion.StringPtr(testFieldDesc), }, }, }, - Description: conversion.StringPtr(testFieldDesc), }, - { - Name: "outer_object", - ComputedOptionalRequired: codespec.Computed, - SingleNested: &codespec.SingleNestedAttribute{ - NestedObject: codespec.NestedAttributeObject{ - Attributes: codespec.Attributes{ - { - Name: "nested_level1", - ComputedOptionalRequired: codespec.Computed, - SingleNested: &codespec.SingleNestedAttribute{ - NestedObject: codespec.NestedAttributeObject{ - Attributes: codespec.Attributes{ - { - Name: "level_field1_alias", - ComputedOptionalRequired: codespec.Computed, - String: &codespec.StringAttribute{}, - Description: conversion.StringPtr("Overridden level_field1_alias description"), - }, + Description: conversion.StringPtr(testFieldDesc), + }, + { + Name: "optional_string_attr", + ComputedOptionalRequired: codespec.ComputedOptional, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr("Optional string that has config override to optional/computed"), + }, + { + Name: "outer_object", + ComputedOptionalRequired: codespec.Computed, + SingleNested: &codespec.SingleNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "nested_level1", + ComputedOptionalRequired: codespec.Computed, + SingleNested: &codespec.SingleNestedAttribute{ + NestedObject: codespec.NestedAttributeObject{ + Attributes: codespec.Attributes{ + { + Name: "level_field1_alias", + ComputedOptionalRequired: codespec.Computed, + String: &codespec.StringAttribute{}, + Description: conversion.StringPtr("Overridden level_field1_alias description"), }, }, }, @@ -353,26 +345,26 @@ func TestConvertToProviderSpec_nested_schemaOverrides(t *testing.T) { }, }, }, - { - Name: "timeouts", - Timeouts: &codespec.TimeoutsAttribute{ - ConfigurableTimeouts: []codespec.Operation{codespec.Create, codespec.Read, codespec.Update, codespec.Delete}, - }, + }, + { + Name: "timeouts", + Timeouts: &codespec.TimeoutsAttribute{ + ConfigurableTimeouts: []codespec.Operation{codespec.Create, codespec.Read, codespec.Update, codespec.Delete}, }, }, }, - Name: "test_resource_with_nested_attr_overrides", - }, }, + Name: "test_resource_with_nested_attr_overrides", + }, }, }, } + runTestCase(t, tc) +} - for name, tc := range testCases { - t.Run(name, func(t *testing.T) { - result, err := codespec.ToCodeSpecModel(tc.inputOpenAPISpecPath, tc.inputConfigPath, &tc.inputResourceName) - require.NoError(t, err) - assert.Equal(t, tc.expectedResult, result, "Expected result to match the specified structure") - }) - } +func runTestCase(t *testing.T, tc convertToSpecTestCase) { + t.Helper() + result, err := codespec.ToCodeSpecModel(tc.inputOpenAPISpecPath, tc.inputConfigPath, &tc.inputResourceName) + require.NoError(t, err) + assert.Equal(t, tc.expectedResult, result, "Expected result to match the specified structure") } diff --git a/tools/codegen/codespec/config.go b/tools/codegen/codespec/config.go index f935472bad..092c344712 100644 --- a/tools/codegen/codespec/config.go +++ b/tools/codegen/codespec/config.go @@ -80,8 +80,26 @@ func applyAlias(attr *Attribute, attrPathName *string, schemaOptions config.Sche func applyOverrides(attr *Attribute, attrPathName string, schemaOptions config.SchemaOptions) { if override, ok := schemaOptions.Overrides[attrPathName]; ok { - attr.Description = &override.Description + if override.Description != "" { + attr.Description = &override.Description + } + if override.Computability != nil { + attr.ComputedOptionalRequired = getComputabilityFromConfig(*override.Computability) + } + } +} + +func getComputabilityFromConfig(computability config.Computability) ComputedOptionalRequired { + if computability.Computed && computability.Optional { + return ComputedOptional + } + if computability.Computed { + return Computed + } + if computability.Optional { + return Optional } + return Required } func processNestedAttributes(attr *Attribute, schemaOptions config.SchemaOptions, attrPathName string) { diff --git a/tools/codegen/codespec/testdata/api-spec.yml b/tools/codegen/codespec/testdata/api-spec.yml index 42eda820a7..99af61c3dd 100644 --- a/tools/codegen/codespec/testdata/api-spec.yml +++ b/tools/codegen/codespec/testdata/api-spec.yml @@ -380,6 +380,9 @@ components: $ref: "#/components/schemas/SingleNestedAttr" nestedMapObjectAttr: $ref: "#/components/schemas/NestedMapObjectAttr" + optional_string_attr: + type: string + description: Optional string SingleNestedAttrWithNestedMaps: type: object description: Test field description @@ -437,6 +440,9 @@ components: $ref: "#/components/schemas/NestedObjectAttr" maxItems: 1 minItems: 1 + optional_string_attr: + type: string + description: Optional string required: - nestedListArrayAttr SimpleStringRefObject: diff --git a/tools/codegen/codespec/testdata/config-nested-schema-overrides.yml b/tools/codegen/codespec/testdata/config-nested-schema-overrides.yml index 95b2f7a9ee..3f19b87374 100644 --- a/tools/codegen/codespec/testdata/config-nested-schema-overrides.yml +++ b/tools/codegen/codespec/testdata/config-nested-schema-overrides.yml @@ -25,4 +25,9 @@ resources: description: "Overridden inner_num_attr_alias description" outer_object.nested_level1.level_field1_alias: description: "Overridden level_field1_alias description" + optional_string_attr: + computability: + optional: true + computed: true + description: "Optional string that has config override to optional/computed" timeouts: ["create", "read", "update", "delete"] diff --git a/tools/codegen/config/config_model.go b/tools/codegen/config/config_model.go index 322fc44962..6a6dcb5221 100644 --- a/tools/codegen/config/config_model.go +++ b/tools/codegen/config/config_model.go @@ -25,10 +25,10 @@ type SchemaOptions struct { } type Override struct { + Computability *Computability `yaml:"computability,omitempty"` Description string `yaml:"description"` PlanModifiers []PlanModifier `yaml:"plan_modifiers"` Validators []Validator `yaml:"validators"` - Computability Computability `yaml:"computability"` } type PlanModifier struct { From 254ce64245680371988542eb544f8ad2fb7de528 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 30 Oct 2024 07:24:53 +0100 Subject: [PATCH 27/35] chore: Bump crazy-max/ghaction-import-gpg from 6.1.0 to 6.2.0 (#2754) Bumps [crazy-max/ghaction-import-gpg](https://github.com/crazy-max/ghaction-import-gpg) from 6.1.0 to 6.2.0. - [Release notes](https://github.com/crazy-max/ghaction-import-gpg/releases) - [Commits](https://github.com/crazy-max/ghaction-import-gpg/compare/01dd5d3ca463c7f10f7f4f7b4f177225ac661ee4...cb9bde2e2525e640591a934b1fd28eef1dcaf5e5) --- updated-dependencies: - dependency-name: crazy-max/ghaction-import-gpg dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/release.yml | 2 +- .github/workflows/run-script-and-commit.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1da129336a..bb4c71eee3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -140,7 +140,7 @@ jobs: go-version-file: 'go.mod' - name: Import GPG key id: import_gpg - uses: crazy-max/ghaction-import-gpg@01dd5d3ca463c7f10f7f4f7b4f177225ac661ee4 + uses: crazy-max/ghaction-import-gpg@cb9bde2e2525e640591a934b1fd28eef1dcaf5e5 with: gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }} passphrase: ${{ secrets.PASSPHRASE }} diff --git a/.github/workflows/run-script-and-commit.yml b/.github/workflows/run-script-and-commit.yml index 88cbc3bb9e..35a6536791 100644 --- a/.github/workflows/run-script-and-commit.yml +++ b/.github/workflows/run-script-and-commit.yml @@ -42,7 +42,7 @@ jobs: - name: Import GPG key id: import_gpg - uses: crazy-max/ghaction-import-gpg@01dd5d3ca463c7f10f7f4f7b4f177225ac661ee4 + uses: crazy-max/ghaction-import-gpg@cb9bde2e2525e640591a934b1fd28eef1dcaf5e5 with: gpg_private_key: ${{ secrets.gpg_private_key }} passphrase: ${{ secrets.passphrase }} From a512db669ccba2c8011888985e50d3b85ec66bd4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 30 Oct 2024 07:25:15 +0100 Subject: [PATCH 28/35] chore: Bump actions/setup-go from 5.0.2 to 5.1.0 (#2753) Bumps [actions/setup-go](https://github.com/actions/setup-go) from 5.0.2 to 5.1.0. - [Release notes](https://github.com/actions/setup-go/releases) - [Commits](https://github.com/actions/setup-go/compare/0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32...41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed) --- updated-dependencies: - dependency-name: actions/setup-go dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/acceptance-tests-runner.yml | 46 +++++++++---------- .../workflows/check-changelog-entry-file.yml | 2 +- .github/workflows/code-health.yml | 6 +-- .github/workflows/examples.yml | 4 +- .github/workflows/jira-release-version.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/run-script-and-commit.yml | 2 +- .github/workflows/update-sdk.yml | 2 +- 8 files changed, 33 insertions(+), 33 deletions(-) diff --git a/.github/workflows/acceptance-tests-runner.yml b/.github/workflows/acceptance-tests-runner.yml index 5e64956b37..82cf7f7cef 100644 --- a/.github/workflows/acceptance-tests-runner.yml +++ b/.github/workflows/acceptance-tests-runner.yml @@ -327,7 +327,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -349,7 +349,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -373,7 +373,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -413,7 +413,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -451,7 +451,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -473,7 +473,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -495,7 +495,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -517,7 +517,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -563,7 +563,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -599,7 +599,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -621,7 +621,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -659,7 +659,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -686,7 +686,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -708,7 +708,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -737,7 +737,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -759,7 +759,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -804,7 +804,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -842,7 +842,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -867,7 +867,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -894,7 +894,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -916,7 +916,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -938,7 +938,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -964,7 +964,7 @@ jobs: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 with: ref: ${{ inputs.ref || github.ref }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd diff --git a/.github/workflows/check-changelog-entry-file.yml b/.github/workflows/check-changelog-entry-file.yml index 6bbcf6e5aa..8ff60ced4d 100644 --- a/.github/workflows/check-changelog-entry-file.yml +++ b/.github/workflows/check-changelog-entry-file.yml @@ -14,7 +14,7 @@ jobs: permissions: {} steps: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - run: make check-changelog-entry-file diff --git a/.github/workflows/code-health.yml b/.github/workflows/code-health.yml index b5f1623f5c..27a356d969 100644 --- a/.github/workflows/code-health.yml +++ b/.github/workflows/code-health.yml @@ -18,7 +18,7 @@ jobs: permissions: {} steps: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - name: Build @@ -30,7 +30,7 @@ jobs: pull-requests: write # Needed by sticky-pull-request-comment steps: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - name: Unit Test @@ -42,7 +42,7 @@ jobs: - name: Checkout uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 - name: Install Go - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' cache: false # see https://github.com/golangci/golangci-lint-action/issues/807 diff --git a/.github/workflows/examples.yml b/.github/workflows/examples.yml index e5114f0de9..0defbdbd42 100644 --- a/.github/workflows/examples.yml +++ b/.github/workflows/examples.yml @@ -18,7 +18,7 @@ jobs: permissions: {} steps: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd @@ -32,7 +32,7 @@ jobs: permissions: {} steps: - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - name: tflint diff --git a/.github/workflows/jira-release-version.yml b/.github/workflows/jira-release-version.yml index ae85851e59..5a3ec4906a 100644 --- a/.github/workflows/jira-release-version.yml +++ b/.github/workflows/jira-release-version.yml @@ -24,7 +24,7 @@ jobs: - name: Validation of version format, no pre-releases run: | echo "${{ inputs.version_number }}" | grep -P '^v\d+\.\d+\.\d+$' - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - run: make jira-release-version diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bb4c71eee3..d7bd46d764 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -135,7 +135,7 @@ jobs: with: ref: ${{ inputs.version_number }} - name: Set up Go - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - name: Import GPG key diff --git a/.github/workflows/run-script-and-commit.yml b/.github/workflows/run-script-and-commit.yml index 35a6536791..6db8bc3c3e 100644 --- a/.github/workflows/run-script-and-commit.yml +++ b/.github/workflows/run-script-and-commit.yml @@ -33,7 +33,7 @@ jobs: with: fetch-depth: 0 token: ${{ secrets.apix_bot_pat }} - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' diff --git a/.github/workflows/update-sdk.yml b/.github/workflows/update-sdk.yml index 5bfb6ebecc..ff3a7c68ec 100644 --- a/.github/workflows/update-sdk.yml +++ b/.github/workflows/update-sdk.yml @@ -14,7 +14,7 @@ jobs: steps: - name: Checkout uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 - - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 + - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' - name: Update files From 0f37d127dc97a18890cda94a9141f166705167c4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 30 Oct 2024 07:25:47 +0100 Subject: [PATCH 29/35] chore: Bump github.com/pb33f/libopenapi from 0.18.1 to 0.18.6 (#2750) Bumps [github.com/pb33f/libopenapi](https://github.com/pb33f/libopenapi) from 0.18.1 to 0.18.6. - [Release notes](https://github.com/pb33f/libopenapi/releases) - [Commits](https://github.com/pb33f/libopenapi/compare/v0.18.1...v0.18.6) --- updated-dependencies: - dependency-name: github.com/pb33f/libopenapi dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 33cf3e63f1..b6018e7d1b 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/hashicorp/terraform-plugin-testing v1.9.0 github.com/huandu/xstrings v1.3.3 github.com/mongodb-forks/digest v1.1.0 - github.com/pb33f/libopenapi v0.18.1 + github.com/pb33f/libopenapi v0.18.6 github.com/sebdah/goldie/v2 v2.5.5 github.com/spf13/cast v1.6.0 github.com/stretchr/testify v1.9.0 diff --git a/go.sum b/go.sum index 395935e231..948e8b5dd1 100644 --- a/go.sum +++ b/go.sum @@ -692,8 +692,8 @@ github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI= github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M= github.com/openlyinc/pointy v1.1.2 h1:LywVV2BWC5Sp5v7FoP4bUD+2Yn5k0VNeRbU5vq9jUMY= github.com/openlyinc/pointy v1.1.2/go.mod h1:w2Sytx+0FVuMKn37xpXIAyBNhFNBIJGR/v2m7ik1WtM= -github.com/pb33f/libopenapi v0.18.1 h1:Z2lWZ7A7G1u8gwx8A7IwuLwSToP8m55ZlzAagcLHh2U= -github.com/pb33f/libopenapi v0.18.1/go.mod h1:9ap4lXBHgxGyFwxtOfa+B1C3IQ0rvnqteqjJvJ11oiQ= +github.com/pb33f/libopenapi v0.18.6 h1:adxzZUnOBOAuKxFAIrtb1Qt8GA4XnDWUAxEnqiSoTh0= +github.com/pb33f/libopenapi v0.18.6/go.mod h1:qZRs2IHIcs9SjHPmQfSUCyeD3OY9JkLJQOuFxd0bYCY= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pjbgf/sha1cd v0.3.0 h1:4D5XXmUUBUl/xQ6IjCkEAbqXskkq/4O7LmGn0AqMDs4= github.com/pjbgf/sha1cd v0.3.0/go.mod h1:nZ1rrWOcGJ5uZgEEVL1VUM9iRQiZvWdbZjkKyFzPPsI= @@ -714,10 +714,10 @@ github.com/rogpeppe/go-charset v0.0.0-20180617210344-2471d30d28b4/go.mod h1:qgYe github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= -github.com/sebdah/goldie/v2 v2.5.5 h1:rx1mwF95RxZ3/83sdS4Yp7t2C5TCokvWP4TBRbAyEWY= -github.com/sebdah/goldie/v2 v2.5.5/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI= github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/sebdah/goldie/v2 v2.5.5 h1:rx1mwF95RxZ3/83sdS4Yp7t2C5TCokvWP4TBRbAyEWY= +github.com/sebdah/goldie/v2 v2.5.5/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= From 4fd1b7c902ae4b4bf237ff85113ebf6a5e65cf3f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 30 Oct 2024 07:27:02 +0100 Subject: [PATCH 30/35] chore: Bump tj-actions/verify-changed-files (#2751) Bumps [tj-actions/verify-changed-files](https://github.com/tj-actions/verify-changed-files) from 54483a2138ca67989bc40785aa22faee8b085894 to 530d86d0a237225c87beaa000750988f8965ee31. - [Release notes](https://github.com/tj-actions/verify-changed-files/releases) - [Changelog](https://github.com/tj-actions/verify-changed-files/blob/main/HISTORY.md) - [Commits](https://github.com/tj-actions/verify-changed-files/compare/54483a2138ca67989bc40785aa22faee8b085894...530d86d0a237225c87beaa000750988f8965ee31) --- updated-dependencies: - dependency-name: tj-actions/verify-changed-files dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/update-sdk.yml | 2 +- .github/workflows/update_tf_compatibility_matrix.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/update-sdk.yml b/.github/workflows/update-sdk.yml index ff3a7c68ec..d5f69e70ca 100644 --- a/.github/workflows/update-sdk.yml +++ b/.github/workflows/update-sdk.yml @@ -20,7 +20,7 @@ jobs: - name: Update files run: make tools update-atlas-sdk - name: Verify Changed files - uses: tj-actions/verify-changed-files@54483a2138ca67989bc40785aa22faee8b085894 + uses: tj-actions/verify-changed-files@530d86d0a237225c87beaa000750988f8965ee31 id: verify-changed-files - name: Create PR uses: peter-evans/create-pull-request@5e914681df9dc83aa4e4905692ca88beb2f9e91f diff --git a/.github/workflows/update_tf_compatibility_matrix.yml b/.github/workflows/update_tf_compatibility_matrix.yml index 195a377889..18038dd237 100644 --- a/.github/workflows/update_tf_compatibility_matrix.yml +++ b/.github/workflows/update_tf_compatibility_matrix.yml @@ -19,7 +19,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: make update-tf-compatibility-matrix - name: Verify Changed files - uses: tj-actions/verify-changed-files@54483a2138ca67989bc40785aa22faee8b085894 + uses: tj-actions/verify-changed-files@530d86d0a237225c87beaa000750988f8965ee31 id: verify-changed-files - name: Create PR uses: peter-evans/create-pull-request@5e914681df9dc83aa4e4905692ca88beb2f9e91f From 8e79adb6d4d140fa1018b65e8c7430f34fcb2dd5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 30 Oct 2024 10:08:03 +0100 Subject: [PATCH 31/35] chore: Bump actions/checkout from 4.2.1 to 4.2.2 (#2752) * chore: Bump actions/checkout from 4.2.1 to 4.2.2 Bumps [actions/checkout](https://github.com/actions/checkout) from 4.2.1 to 4.2.2. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871...11bd71901bbe5b1630ceea73d27597364c9af683) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] * Trigger Build --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Leo Antoli <430982+lantoli@users.noreply.github.com> --- .github/workflows/acceptance-tests-runner.yml | 50 +++++++++---------- .../workflows/check-changelog-entry-file.yml | 2 +- .github/workflows/check-migration-guide.yml | 2 +- .github/workflows/cleanup-test-env.yml | 4 +- .github/workflows/code-health.yml | 10 ++-- .github/workflows/examples.yml | 4 +- .github/workflows/jira-release-version.yml | 2 +- .github/workflows/notify-docs-team.yml | 2 +- .github/workflows/release.yml | 6 +-- .github/workflows/run-script-and-commit.yml | 2 +- .../terraform-compatibility-matrix.yml | 4 +- .github/workflows/update-sdk.yml | 2 +- .../update_tf_compatibility_matrix.yml | 2 +- 13 files changed, 46 insertions(+), 46 deletions(-) diff --git a/.github/workflows/acceptance-tests-runner.yml b/.github/workflows/acceptance-tests-runner.yml index 82cf7f7cef..a20e1887e9 100644 --- a/.github/workflows/acceptance-tests-runner.yml +++ b/.github/workflows/acceptance-tests-runner.yml @@ -187,7 +187,7 @@ jobs: provider_version: ${{ inputs.provider_version || steps.get_last_release.outputs.last_provider_version }} steps: - name: Checkout - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Get Last Release id: get_last_release shell: bash @@ -226,7 +226,7 @@ jobs: serverless: ${{ steps.filter.outputs.serverless == 'true' || env.mustTrigger == 'true' }} stream: ${{ steps.filter.outputs.stream == 'true' || env.mustTrigger == 'true' }} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 id: filter if: ${{ inputs.test_group == '' && env.mustTrigger == 'false' }} @@ -324,7 +324,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -346,7 +346,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -370,7 +370,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -410,7 +410,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -448,7 +448,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -470,7 +470,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -492,7 +492,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -514,7 +514,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -560,7 +560,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -596,7 +596,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -618,7 +618,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -656,7 +656,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -683,7 +683,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -705,7 +705,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -734,7 +734,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -756,7 +756,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -801,7 +801,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -839,7 +839,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -864,7 +864,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -891,7 +891,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -913,7 +913,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -935,7 +935,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed @@ -961,7 +961,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.ref || github.ref }} - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed diff --git a/.github/workflows/check-changelog-entry-file.yml b/.github/workflows/check-changelog-entry-file.yml index 8ff60ced4d..e83f27cd4c 100644 --- a/.github/workflows/check-changelog-entry-file.yml +++ b/.github/workflows/check-changelog-entry-file.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' diff --git a/.github/workflows/check-migration-guide.yml b/.github/workflows/check-migration-guide.yml index 9ea5e908f9..ec705d1ad5 100644 --- a/.github/workflows/check-migration-guide.yml +++ b/.github/workflows/check-migration-guide.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 id: changes with: diff --git a/.github/workflows/cleanup-test-env.yml b/.github/workflows/cleanup-test-env.yml index fde55e57e0..007c8de9c9 100644 --- a/.github/workflows/cleanup-test-env.yml +++ b/.github/workflows/cleanup-test-env.yml @@ -11,7 +11,7 @@ jobs: permissions: {} steps: - name: Checkout - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: sparse-checkout: | scripts @@ -29,7 +29,7 @@ jobs: permissions: {} steps: - name: Checkout - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: sparse-checkout: | scripts diff --git a/.github/workflows/code-health.yml b/.github/workflows/code-health.yml index 27a356d969..0a0c8b7c18 100644 --- a/.github/workflows/code-health.yml +++ b/.github/workflows/code-health.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' @@ -29,7 +29,7 @@ jobs: permissions: pull-requests: write # Needed by sticky-pull-request-comment steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' @@ -40,7 +40,7 @@ jobs: permissions: {} steps: - name: Checkout - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Install Go uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: @@ -60,14 +60,14 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Run ShellCheck uses: bewuethr/shellcheck-action@d01912909579c4b1a335828b8fca197fbb8e0aa4 generate-doc-check: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - run: make tools generate-docs-all - name: Find mutations id: self_mutation diff --git a/.github/workflows/examples.yml b/.github/workflows/examples.yml index 0defbdbd42..fd1f4afff1 100644 --- a/.github/workflows/examples.yml +++ b/.github/workflows/examples.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' @@ -31,7 +31,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' diff --git a/.github/workflows/jira-release-version.yml b/.github/workflows/jira-release-version.yml index 5a3ec4906a..0ca985de78 100644 --- a/.github/workflows/jira-release-version.yml +++ b/.github/workflows/jira-release-version.yml @@ -20,7 +20,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Validation of version format, no pre-releases run: | echo "${{ inputs.version_number }}" | grep -P '^v\d+\.\d+\.\d+$' diff --git a/.github/workflows/notify-docs-team.yml b/.github/workflows/notify-docs-team.yml index e40c9081fe..52c474a581 100644 --- a/.github/workflows/notify-docs-team.yml +++ b/.github/workflows/notify-docs-team.yml @@ -13,7 +13,7 @@ jobs: permissions: pull-requests: read steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 id: changes with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d7bd46d764..1fef5e49aa 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -41,7 +41,7 @@ jobs: run: | echo "${{ inputs.version_number }}" | grep -P '^v\d+\.\d+\.\d+(-pre[A-Za-z0-9-]*)?$' - name: Checkout - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.use_existing_tag == 'true' && inputs.version_number || 'master' }} - name: Check for Upgrade Guide @@ -94,7 +94,7 @@ jobs: && needs.release-config.outputs.creates_new_tag == 'true' steps: - name: Checkout - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: 'master' - name: Get the latest commit SHA @@ -131,7 +131,7 @@ jobs: && !contains(needs.*.result, 'failure') steps: - name: Checkout - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ inputs.version_number }} - name: Set up Go diff --git a/.github/workflows/run-script-and-commit.yml b/.github/workflows/run-script-and-commit.yml index 6db8bc3c3e..23d1212210 100644 --- a/.github/workflows/run-script-and-commit.yml +++ b/.github/workflows/run-script-and-commit.yml @@ -29,7 +29,7 @@ jobs: permissions: {} steps: - name: Checkout repository - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: fetch-depth: 0 token: ${{ secrets.apix_bot_pat }} diff --git a/.github/workflows/terraform-compatibility-matrix.yml b/.github/workflows/terraform-compatibility-matrix.yml index 98a83ade9b..5eb6c2d7cc 100644 --- a/.github/workflows/terraform-compatibility-matrix.yml +++ b/.github/workflows/terraform-compatibility-matrix.yml @@ -20,7 +20,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Get HashiCorp Terraform supported versions shell: bash id: get-terraform-supported-versions @@ -56,7 +56,7 @@ jobs: runs-on: ubuntu-latest permissions: {} steps: - - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Get content of slack message id: slack-payload run: | diff --git a/.github/workflows/update-sdk.yml b/.github/workflows/update-sdk.yml index d5f69e70ca..1cddac5c79 100644 --- a/.github/workflows/update-sdk.yml +++ b/.github/workflows/update-sdk.yml @@ -13,7 +13,7 @@ jobs: pull-requests: write steps: - name: Checkout - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed with: go-version-file: 'go.mod' diff --git a/.github/workflows/update_tf_compatibility_matrix.yml b/.github/workflows/update_tf_compatibility_matrix.yml index 18038dd237..c2ae4ee7ae 100644 --- a/.github/workflows/update_tf_compatibility_matrix.yml +++ b/.github/workflows/update_tf_compatibility_matrix.yml @@ -13,7 +13,7 @@ jobs: pull-requests: write steps: - name: Checkout - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Update files env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 32f7ea7d5c1fae79e8fe58819c2d8c3f221ebe4e Mon Sep 17 00:00:00 2001 From: maastha <122359335+maastha@users.noreply.github.com> Date: Wed, 30 Oct 2024 11:08:31 +0000 Subject: [PATCH 32/35] chore: Automatically updates Terraform version used in repository and test-suite (#2755) --- .../update_tf_compatibility_matrix.yml | 27 +++++++++++- GNUmakefile | 4 ++ scripts/get-terraform-supported-versions.sh | 43 ++++++++++++++++--- scripts/update-tf-version-in-repository.sh | 40 +++++++++++++++++ 4 files changed, 107 insertions(+), 7 deletions(-) create mode 100755 scripts/update-tf-version-in-repository.sh diff --git a/.github/workflows/update_tf_compatibility_matrix.yml b/.github/workflows/update_tf_compatibility_matrix.yml index c2ae4ee7ae..4d0d7008c1 100644 --- a/.github/workflows/update_tf_compatibility_matrix.yml +++ b/.github/workflows/update_tf_compatibility_matrix.yml @@ -30,4 +30,29 @@ jobs: commit-message: "doc: Updates Terraform Compatibility Matrix documentation" delete-branch: true branch: terraform-compatibility-matrix-update - body: "Automatic updates for Terraform Compatibility Matrix documentation. **Action Required**: Update test-suite.yml, .tools-version files, and TF_VERSION_LATEST GitHub environment variable if needed." + body: "Automatic updates for Terraform Compatibility Matrix documentation. **Action Required**: Update TF_VERSION_LATEST GitHub environment variable if needed." + + update-tf-version-in-repository: + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - name: Checkout + uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 + - name: Update files + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: make update-tf-version-in-repository + - name: Verify Changed files + uses: tj-actions/verify-changed-files@54483a2138ca67989bc40785aa22faee8b085894 + id: verify-changed-files + - name: Create PR + uses: peter-evans/create-pull-request@5e914681df9dc83aa4e4905692ca88beb2f9e91f + if: steps.verify-changed-files.outputs.files_changed == 'true' + with: + token: ${{ secrets.APIX_BOT_PAT }} + title: "chore: Updates repository to use supported Terraform versions" + commit-message: "chore: Updates repository to use supported Terraform versions" + delete-branch: true + branch: terraform-versions-update + body: "Automatic updates for our repository to use supported Terraform versions." diff --git a/GNUmakefile b/GNUmakefile index 25e6b83d76..e60e77780d 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -145,6 +145,10 @@ generate-docs-all: update-tf-compatibility-matrix: ## Update Terraform Compatibility Matrix documentation ./scripts/update-tf-compatibility-matrix.sh +.PHONY: update-tf-version-in-repository +update-tf-version-in-repository: ## Update Terraform versions + ./scripts/update-tf-version-in-repository.sh + .PHONY: update-changelog-unreleased-section update-changelog-unreleased-section: ./scripts/update-changelog-unreleased-section.sh diff --git a/scripts/get-terraform-supported-versions.sh b/scripts/get-terraform-supported-versions.sh index 0ef168a7a6..e698713d7b 100755 --- a/scripts/get-terraform-supported-versions.sh +++ b/scripts/get-terraform-supported-versions.sh @@ -22,6 +22,16 @@ usage() { exit 1 } +fetch_terraform_releases_page() { + local page="$1" + local api_version="2022-11-28" + curl -s \ + --request GET \ + --url "https://api.github.com/repos/hashicorp/terraform/releases?per_page=100&page=$page" \ + --header "Authorization: Bearer $GITHUB_TOKEN" \ + --header "X-GitHub-Api-Version: $api_version" +} + get_last_day_of_month() { last_day_of_month=0 case $1 in @@ -66,14 +76,9 @@ add_end_support_date() { get_terraform_supported_versions_details() { page=1 - api_version="2022-11-28" while true; do - response=$(curl -s \ - --request GET \ - --url "https://api.github.com/repos/hashicorp/terraform/releases?per_page=100&page=$page" \ - --header "Authorization: Bearer $GITHUB_TOKEN" \ - --header "X-GitHub-Api-Version: $api_version") + response=$(fetch_terraform_releases_page "$page") if [[ "$(printf '%s\n' "$response" | jq -e 'length == 0')" == "true" ]]; then break else @@ -106,6 +111,30 @@ get_terraform_supported_versions() { echo "[$formatted_output]" | jq -c . } +get_latest_terraform_version() { + api_version="2022-11-28" + latest_version="" + + for page in 1 2; do + response=$(fetch_terraform_releases_page "$page") + + if [[ "$(printf '%s\n' "$response" | jq -e 'length == 0')" == "true" ]]; then + break + fi + + versions=$(echo "$response" | jq -r '.[] | select(.tag_name | test("alpha|beta|rc"; "i") | not) | .tag_name') + + for version in $versions; do + version_cleaned="${version#v}" + if [[ -z "$latest_version" || "$(echo -e "$latest_version\n$version_cleaned" | sort -V | tail -n 1)" == "$version_cleaned" ]]; then + latest_version="$version_cleaned" + fi + done + done + + echo "$latest_version" +} + if [ $# -ne 1 ]; then usage fi @@ -115,6 +144,8 @@ if [ "$get_details" = "true" ]; then get_terraform_supported_versions_details elif [ "$get_details" = "false" ]; then get_terraform_supported_versions +elif [ "$get_details" = "latest" ]; then + get_latest_terraform_version else echo "Invalid parameter." usage diff --git a/scripts/update-tf-version-in-repository.sh b/scripts/update-tf-version-in-repository.sh new file mode 100755 index 0000000000..2d7e2ee797 --- /dev/null +++ b/scripts/update-tf-version-in-repository.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash + +# Copyright 2024 MongoDB Inc +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +set -euo pipefail + +# example value of TF_VERSIONS_ARR='["1.9.x", "1.8.x", "1.7.x"]' +TF_VERSIONS_ARR=$(./scripts/get-terraform-supported-versions.sh "false") + +TEST_SUITE_YAML_FILE=".github/workflows/test-suite.yml" +TOOL_VERSIONS_FILE=".tool-versions" +DOC_SCRIPT="scripts/generate-doc.sh" +DOC_ALL_SCRIPT="scripts/generate-docs-all.sh" + +LATEST_TF_VERSION=$(echo "$TF_VERSIONS_ARR" | sed -E 's/^\["([^"]+).*/\1/') + +# Update Terraform versions in test-suite.yml +sed -i.bak -E "/^ *terraform_matrix:/,/^ *provider_matrix:/ s|(default: ')[^']*(')|\1$TF_VERSIONS_ARR\2|" "$TEST_SUITE_YAML_FILE" + +sed -i.bak -E "s|schedule_terraform_matrix: '.*'|schedule_terraform_matrix: '[\"$LATEST_TF_VERSION\"]'|" "$TEST_SUITE_YAML_FILE" + +# Update patch version occurrences +LATEST_TF_PATCH_VERSION=$(./scripts/get-terraform-supported-versions.sh "latest") + +# Update Terraform versions in .tool-versions +sed -i.bak -E "s|^(terraform) [0-9]+\.[0-9]+\.[0-9]+|\1 $LATEST_TF_PATCH_VERSION|" "$TOOL_VERSIONS_FILE" +# Update Terraform versions in generate-doc scripts +sed -i.bak -E "/TF_VERSION=/ s/[0-9]+\.[0-9]+\.[0-9]+/$LATEST_TF_PATCH_VERSION/g" "$DOC_SCRIPT" +sed -i.bak -E "/TF_VERSION=/ s/[0-9]+\.[0-9]+\.[0-9]+/$LATEST_TF_PATCH_VERSION/g" "$DOC_ALL_SCRIPT" From 82bc44564404abaaaa3ce1173f0f94239a5f74cc Mon Sep 17 00:00:00 2001 From: maastha <122359335+maastha@users.noreply.github.com> Date: Wed, 30 Oct 2024 14:39:34 +0000 Subject: [PATCH 33/35] rename workflow (#2761) --- ...pdate_tf_compatibility_matrix.yml => update-tf-versions.yml} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename .github/workflows/{update_tf_compatibility_matrix.yml => update-tf-versions.yml} (97%) diff --git a/.github/workflows/update_tf_compatibility_matrix.yml b/.github/workflows/update-tf-versions.yml similarity index 97% rename from .github/workflows/update_tf_compatibility_matrix.yml rename to .github/workflows/update-tf-versions.yml index 4d0d7008c1..45500dbb4d 100644 --- a/.github/workflows/update_tf_compatibility_matrix.yml +++ b/.github/workflows/update-tf-versions.yml @@ -1,4 +1,4 @@ -name: Update Terraform Compatibility Matrix documentation +name: Update Terraform Versions # Checks if any changes are required to be made to our documentation for supported Terraform versions. Runs daily and can be triggered manually. on: From 876f9f2da58b0c27f71e2c36f1c3e0fb888603ce Mon Sep 17 00:00:00 2001 From: svc-apix-Bot <142542575+svc-apix-Bot@users.noreply.github.com> Date: Wed, 30 Oct 2024 15:38:52 +0000 Subject: [PATCH 34/35] chore: Updates Atlas Go SDK (#2748) * build(deps): bump go.mongodb.org/atlas-sdk * Pin cluster POST and PATCH operations to 2024-08-05 avoiding any unintentional shard level autoscaling * unifying version clarification in comments * use sdk utility function for checking error code value * adjust conditional of error checking preserving behaviour --------- Co-authored-by: AgustinBettati <20469408+AgustinBettati@users.noreply.github.com> Co-authored-by: Agustin Bettati --- go.mod | 1 + go.sum | 2 + internal/common/conversion/flatten_expand.go | 16 ++- internal/config/client.go | 26 ++++- .../data_source_accesslist_api_keys.go | 2 +- .../resource_access_list_api_key.go | 2 +- .../data_source_advanced_clusters.go | 2 +- .../advancedcluster/model_advanced_cluster.go | 47 ++++---- .../model_advanced_cluster_test.go | 9 +- .../model_sdk_version_conversion.go | 21 ++-- .../resource_advanced_cluster.go | 38 ++++--- .../resource_advanced_cluster_test.go | 2 +- .../advancedcluster/resource_update_logic.go | 15 +-- .../resource_update_logic_test.go | 103 +++++++++--------- internal/service/advancedclustertpf/model.go | 2 +- .../data_source_alert_configuration.go | 2 +- .../data_source_alert_configurations.go | 2 +- .../model_alert_configuration.go | 2 +- .../model_alert_configuration_test.go | 2 +- .../resource_alert_configuration.go | 2 +- .../service/apikey/data_source_api_keys.go | 2 +- internal/service/apikey/resource_api_key.go | 2 +- .../atlasuser/data_source_atlas_user.go | 2 +- .../atlasuser/data_source_atlas_user_test.go | 2 +- .../atlasuser/data_source_atlas_users.go | 2 +- .../atlasuser/data_source_atlas_users_test.go | 2 +- .../service/auditing/resource_auditing.go | 2 +- .../resource_backup_compliance_policy.go | 2 +- .../data_source_cloud_backup_schedule.go | 2 +- .../model_cloud_backup_schedule.go | 2 +- .../model_cloud_backup_schedule_test.go | 2 +- .../model_sdk_version_conversion.go | 2 +- .../resource_cloud_backup_schedule.go | 2 +- .../data_source_cloud_backup_snapshots.go | 2 +- .../model_cloud_backup_snapshot.go | 2 +- .../model_cloud_backup_snapshot_test.go | 2 +- .../resource_cloud_backup_snapshot.go | 2 +- ...ce_cloud_backup_snapshot_export_buckets.go | 4 +- ...rce_cloud_backup_snapshot_export_bucket.go | 4 +- ...ource_cloud_backup_snapshot_export_jobs.go | 2 +- ...source_cloud_backup_snapshot_export_job.go | 2 +- ...urce_cloud_backup_snapshot_restore_jobs.go | 2 +- ...ource_cloud_backup_snapshot_restore_job.go | 2 +- ...rce_cloud_provider_access_authorization.go | 2 +- .../resource_cloud_provider_access_setup.go | 2 +- internal/service/cluster/new_atlas.go | 10 +- internal/service/cluster/resource_cluster.go | 8 +- .../resource_cluster_outage_simulation.go | 2 +- .../service/controlplaneipaddresses/model.go | 2 +- .../controlplaneipaddresses/model_test.go | 2 +- .../data_source_custom_db_roles.go | 2 +- .../customdbrole/resource_custom_db_role.go | 2 +- .../resource_custom_db_role_test.go | 2 +- ...ce_custom_dns_configuration_cluster_aws.go | 2 +- .../databaseuser/model_database_user.go | 2 +- .../databaseuser/model_database_user_test.go | 2 +- .../resource_database_user_migration_test.go | 2 +- .../resource_database_user_test.go | 2 +- .../data_source_data_lake_pipeline_run.go | 2 +- .../data_source_data_lake_pipeline_runs.go | 2 +- .../data_source_data_lake_pipelines.go | 2 +- .../resource_data_lake_pipeline.go | 2 +- .../encryptionatrest/data_source_schema.go | 2 +- internal/service/encryptionatrest/model.go | 2 +- .../service/encryptionatrest/model_test.go | 2 +- internal/service/encryptionatrest/resource.go | 2 +- .../resource_migration_test.go | 2 +- .../service/encryptionatrest/resource_test.go | 4 +- .../encryptionatrestprivateendpoint/model.go | 2 +- .../model_test.go | 2 +- .../plural_data_source.go | 2 +- .../resource.go | 2 +- .../resource_test.go | 2 +- .../state_transition.go | 2 +- .../state_transition_test.go | 4 +- ...source_federated_database_instance_test.go | 2 +- ...ata_source_federated_database_instances.go | 2 +- .../resource_federated_database_instance.go | 2 +- .../data_source_federated_query_limits.go | 2 +- .../resource_federated_query_limit.go | 2 +- ...e_federated_settings_identity_providers.go | 2 +- ...el_federated_settings_identity_provider.go | 2 +- ...derated_settings_identity_provider_test.go | 2 +- .../data_source_federated_settings.go | 2 +- ...ource_federated_settings_connected_orgs.go | 2 +- ...model_federated_settings_connected_orgs.go | 2 +- ...ce_federated_settings_org_role_mappings.go | 2 +- ...del_federated_settings_org_role_mapping.go | 2 +- ...rce_federated_settings_org_role_mapping.go | 2 +- .../resource_global_cluster_config.go | 2 +- .../resource_ldap_configuration.go | 2 +- .../ldapverify/resource_ldap_verify.go | 2 +- .../resource_maintenance_window.go | 2 +- .../mongodbemployeeaccessgrant/model.go | 2 +- .../mongodbemployeeaccessgrant/model_test.go | 2 +- .../data_source_network_containers.go | 2 +- .../resource_network_container.go | 2 +- .../data_source_network_peering.go | 2 +- .../data_source_network_peerings.go | 2 +- .../resource_network_peering.go | 2 +- .../onlinearchive/resource_online_archive.go | 2 +- .../organization/data_source_organizations.go | 2 +- .../organization/resource_organization.go | 2 +- .../resource_organization_test.go | 2 +- .../orginvitation/resource_org_invitation.go | 2 +- ...resource_private_endpoint_regional_mode.go | 2 +- .../resource_privatelink_endpoint.go | 2 +- ...esource_privatelink_endpoint_serverless.go | 2 +- .../resource_privatelink_endpoint_service.go | 2 +- ...service_data_federation_online_archives.go | 2 +- ..._service_data_federation_online_archive.go | 2 +- ...rivatelink_endpoints_service_serverless.go | 2 +- ...privatelink_endpoint_service_serverless.go | 2 +- .../service/project/data_source_project.go | 2 +- .../service/project/data_source_projects.go | 2 +- internal/service/project/model_project.go | 2 +- .../service/project/model_project_test.go | 2 +- internal/service/project/resource_project.go | 7 +- .../resource_project_migration_test.go | 2 +- .../service/project/resource_project_test.go | 4 +- .../data_source_project_api_keys.go | 2 +- .../projectapikey/model_project_api_key.go | 2 +- .../projectapikey/resource_project_api_key.go | 2 +- .../resource_project_invitation.go | 2 +- .../model_project_ip_access_list.go | 2 +- .../model_project_ip_access_list_test.go | 2 +- .../resource_project_ip_access_list.go | 2 +- internal/service/projectipaddresses/model.go | 2 +- .../service/projectipaddresses/model_test.go | 2 +- internal/service/pushbasedlogexport/model.go | 2 +- .../service/pushbasedlogexport/model_test.go | 2 +- .../service/pushbasedlogexport/resource.go | 2 +- .../pushbasedlogexport/state_transition.go | 2 +- .../state_transition_test.go | 4 +- internal/service/resourcepolicy/model.go | 2 +- internal/service/resourcepolicy/model_test.go | 2 +- internal/service/resourcepolicy/resource.go | 2 +- .../model_search_deployment.go | 2 +- .../model_search_deployment_test.go | 2 +- .../state_transition_search_deployment.go | 2 +- ...state_transition_search_deployment_test.go | 4 +- .../searchindex/data_source_search_indexes.go | 2 +- .../service/searchindex/model_search_index.go | 2 +- .../searchindex/resource_search_index.go | 2 +- .../data_source_serverless_instances.go | 2 +- .../resource_serverless_instance.go | 2 +- .../resource_serverless_instance_test.go | 2 +- ...a_source_cloud_shared_tier_restore_jobs.go | 2 +- .../data_source_shared_tier_snapshots.go | 2 +- .../data_source_stream_connections.go | 2 +- .../data_source_stream_connections_test.go | 2 +- .../model_stream_connection.go | 2 +- .../model_stream_connection_test.go | 2 +- .../data_source_stream_instances.go | 2 +- .../data_source_stream_instances_test.go | 2 +- .../streaminstance/model_stream_instance.go | 2 +- .../model_stream_instance_test.go | 2 +- internal/service/streamprocessor/model.go | 2 +- .../service/streamprocessor/model_test.go | 2 +- .../streamprocessor/plural_data_source.go | 2 +- internal/service/streamprocessor/resource.go | 2 +- .../streamprocessor/state_transition.go | 2 +- .../streamprocessor/state_transition_test.go | 4 +- internal/service/team/data_source_team.go | 2 +- internal/service/team/resource_team.go | 2 +- internal/service/team/update_user.go | 2 +- internal/service/team/update_user_test.go | 4 +- .../data_source_third_party_integrations.go | 2 +- ...ource_x509_authentication_database_user.go | 2 +- internal/testutil/acc/advanced_cluster.go | 2 +- internal/testutil/acc/atlas.go | 2 +- internal/testutil/acc/cluster.go | 2 +- internal/testutil/acc/config_cluster.go | 2 +- internal/testutil/acc/database_user.go | 2 +- internal/testutil/acc/encryption_at_rest.go | 2 +- internal/testutil/acc/factory.go | 2 +- internal/testutil/acc/project.go | 2 +- internal/testutil/acc/serverless.go | 2 +- 178 files changed, 353 insertions(+), 298 deletions(-) diff --git a/go.mod b/go.mod index b6018e7d1b..270280b285 100644 --- a/go.mod +++ b/go.mod @@ -28,6 +28,7 @@ require ( go.mongodb.org/atlas v0.37.0 go.mongodb.org/atlas-sdk/v20240530005 v20240530005.0.0 go.mongodb.org/atlas-sdk/v20240805005 v20240805005.0.0 + go.mongodb.org/atlas-sdk/v20241023001 v20241023001.0.0 go.mongodb.org/realm v0.1.0 gopkg.in/yaml.v3 v3.0.1 ) diff --git a/go.sum b/go.sum index 948e8b5dd1..e0616c5f6e 100644 --- a/go.sum +++ b/go.sum @@ -806,6 +806,8 @@ go.mongodb.org/atlas-sdk/v20240530005 v20240530005.0.0 h1:d/gbYJ+obR0EM/3DZf7+ZM go.mongodb.org/atlas-sdk/v20240530005 v20240530005.0.0/go.mod h1:O47ZrMMfcWb31wznNIq2PQkkdoFoK0ea2GlmRqGJC2s= go.mongodb.org/atlas-sdk/v20240805005 v20240805005.0.0 h1:EGTT54tKbDbkhhK+jH5AqINFQbHdvaOSpI0oeI5Tl1s= go.mongodb.org/atlas-sdk/v20240805005 v20240805005.0.0/go.mod h1:UTNpAyiKm/7utu+Nl0FafgjgvS+ONNGEoxBT5g/40WM= +go.mongodb.org/atlas-sdk/v20241023001 v20241023001.0.0 h1:dkol8aWch89Jsx9aFKiRkP5LsV1ujPNt8IMK22y4fI0= +go.mongodb.org/atlas-sdk/v20241023001 v20241023001.0.0/go.mod h1:fIIKE86gLwxoK6QoMuJyEuPwbPmf0NbVmNNf70avUAE= go.mongodb.org/realm v0.1.0 h1:zJiXyLaZrznQ+Pz947ziSrDKUep39DO4SfA0Fzx8M4M= go.mongodb.org/realm v0.1.0/go.mod h1:4Vj6iy+Puo1TDERcoh4XZ+pjtwbOzPpzqy3Cwe8ZmDM= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= diff --git a/internal/common/conversion/flatten_expand.go b/internal/common/conversion/flatten_expand.go index 06fd326f17..69015d33c1 100644 --- a/internal/common/conversion/flatten_expand.go +++ b/internal/common/conversion/flatten_expand.go @@ -3,7 +3,8 @@ package conversion import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + admin20240805 "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func FlattenLinks(links []admin.Link) []map[string]string { @@ -28,6 +29,19 @@ func FlattenTags(tags []admin.ResourceTag) []map[string]string { return ret } +func ExpandTagsFromSetSchemaV220240805(d *schema.ResourceData) *[]admin20240805.ResourceTag { + list := d.Get("tags").(*schema.Set) + ret := make([]admin20240805.ResourceTag, list.Len()) + for i, item := range list.List() { + tag := item.(map[string]any) + ret[i] = admin20240805.ResourceTag{ + Key: tag["key"].(string), + Value: tag["value"].(string), + } + } + return &ret +} + func ExpandTagsFromSetSchema(d *schema.ResourceData) *[]admin.ResourceTag { list := d.Get("tags").(*schema.Set) ret := make([]admin.ResourceTag, list.Len()) diff --git a/internal/config/client.go b/internal/config/client.go index 7b4aa4db77..7631358496 100644 --- a/internal/config/client.go +++ b/internal/config/client.go @@ -10,7 +10,8 @@ import ( "time" admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + admin20240805 "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" matlasClient "go.mongodb.org/atlas/mongodbatlas" realmAuth "go.mongodb.org/realm/auth" "go.mongodb.org/realm/realm" @@ -31,7 +32,8 @@ const ( type MongoDBClient struct { Atlas *matlasClient.Client AtlasV2 *admin.APIClient - AtlasV220240530 *admin20240530.APIClient // used in advanced_cluster and cloud_backup_schedule for avoiding breaking changes + AtlasV220240805 *admin20240805.APIClient // used in advanced_cluster to avoid adopting 2024-10-23 release with ISS autoscaling + AtlasV220240530 *admin20240530.APIClient // used in advanced_cluster and cloud_backup_schedule for avoiding breaking changes (supporting deprecated replication_specs.id) Config *Config } @@ -110,10 +112,16 @@ func (c *Config) NewClient(ctx context.Context) (any, error) { return nil, err } + sdkV220240805Client, err := c.newSDKV220240805Client(client) + if err != nil { + return nil, err + } + clients := &MongoDBClient{ Atlas: atlasClient, AtlasV2: sdkV2Client, AtlasV220240530: sdkV220240530Client, + AtlasV220240805: sdkV220240805Client, Config: c, } return clients, nil @@ -147,6 +155,20 @@ func (c *Config) newSDKV220240530Client(client *http.Client) (*admin20240530.API return sdk, nil } +func (c *Config) newSDKV220240805Client(client *http.Client) (*admin20240805.APIClient, error) { + opts := []admin20240805.ClientModifier{ + admin20240805.UseHTTPClient(client), + admin20240805.UseUserAgent(userAgent(c)), + admin20240805.UseBaseURL(c.BaseURL), + admin20240805.UseDebug(false)} + + sdk, err := admin20240805.NewClient(opts...) + if err != nil { + return nil, err + } + return sdk, nil +} + func (c *MongoDBClient) GetRealmClient(ctx context.Context) (*realm.Client, error) { // Realm if c.Config.PublicKey == "" && c.Config.PrivateKey == "" { diff --git a/internal/service/accesslistapikey/data_source_accesslist_api_keys.go b/internal/service/accesslistapikey/data_source_accesslist_api_keys.go index 8499b6c921..599d9a3662 100644 --- a/internal/service/accesslistapikey/data_source_accesslist_api_keys.go +++ b/internal/service/accesslistapikey/data_source_accesslist_api_keys.go @@ -10,7 +10,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/accesslistapikey/resource_access_list_api_key.go b/internal/service/accesslistapikey/resource_access_list_api_key.go index 446a0557f7..f53fdbf6c3 100644 --- a/internal/service/accesslistapikey/resource_access_list_api_key.go +++ b/internal/service/accesslistapikey/resource_access_list_api_key.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" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func Resource() *schema.Resource { diff --git a/internal/service/advancedcluster/data_source_advanced_clusters.go b/internal/service/advancedcluster/data_source_advanced_clusters.go index 598dd16ede..f7c291b102 100644 --- a/internal/service/advancedcluster/data_source_advanced_clusters.go +++ b/internal/service/advancedcluster/data_source_advanced_clusters.go @@ -7,7 +7,7 @@ import ( "net/http" admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" diff --git a/internal/service/advancedcluster/model_advanced_cluster.go b/internal/service/advancedcluster/model_advanced_cluster.go index e7d1b32b6a..679b2333d5 100644 --- a/internal/service/advancedcluster/model_advanced_cluster.go +++ b/internal/service/advancedcluster/model_advanced_cluster.go @@ -12,7 +12,8 @@ import ( "strings" admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + admin20240805 "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -400,7 +401,7 @@ func flattenTags(tags *[]admin.ResourceTag) []map[string]string { } // CheckRegionConfigsPriorityOrder will be deleted in CLOUDP-275825 -func CheckRegionConfigsPriorityOrder(regionConfigs []admin.ReplicationSpec20240805) error { +func CheckRegionConfigsPriorityOrder(regionConfigs []admin20240805.ReplicationSpec20240805) error { for _, spec := range regionConfigs { configs := spec.GetRegionConfigs() for i := 0; i < len(configs)-1; i++ { @@ -472,11 +473,11 @@ func flattenBiConnectorConfig(biConnector *admin.BiConnector) []map[string]any { } } -func expandBiConnectorConfig(d *schema.ResourceData) *admin.BiConnector { +func expandBiConnectorConfig(d *schema.ResourceData) *admin20240805.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{ + return &admin20240805.BiConnector{ Enabled: conversion.Pointer(cast.ToBool(biConnMap["enabled"])), ReadPreference: conversion.StringPtr(cast.ToString(biConnMap["read_preference"])), } @@ -694,11 +695,11 @@ func hwSpecToDedicatedHwSpec(apiObject *admin.HardwareSpec20240805) *admin.Dedic } } -func dedicatedHwSpecToHwSpec(apiObject *admin.DedicatedHardwareSpec20240805) *admin.HardwareSpec20240805 { +func dedicatedHwSpecToHwSpec(apiObject *admin20240805.DedicatedHardwareSpec20240805) *admin20240805.HardwareSpec20240805 { if apiObject == nil { return nil } - return &admin.HardwareSpec20240805{ + return &admin20240805.HardwareSpec20240805{ DiskSizeGB: apiObject.DiskSizeGB, NodeCount: apiObject.NodeCount, DiskIOPS: apiObject.DiskIOPS, @@ -871,16 +872,16 @@ func IsChangeStreamOptionsMinRequiredMajorVersion(input *string) bool { return value >= minVersionForChangeStreamOptions } -func expandLabelSliceFromSetSchema(d *schema.ResourceData) ([]admin.ComponentLabel, diag.Diagnostics) { +func expandLabelSliceFromSetSchema(d *schema.ResourceData) ([]admin20240805.ComponentLabel, diag.Diagnostics) { list := d.Get("labels").(*schema.Set) - res := make([]admin.ComponentLabel, list.Len()) + res := make([]admin20240805.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{ + res[i] = admin20240805.ComponentLabel{ Key: conversion.StringPtr(key), Value: conversion.StringPtr(v["value"].(string)), } @@ -888,8 +889,8 @@ func expandLabelSliceFromSetSchema(d *schema.ResourceData) ([]admin.ComponentLab return res, nil } -func expandAdvancedReplicationSpecs(tfList []any, rootDiskSizeGB *float64) *[]admin.ReplicationSpec20240805 { - var apiObjects []admin.ReplicationSpec20240805 +func expandAdvancedReplicationSpecs(tfList []any, rootDiskSizeGB *float64) *[]admin20240805.ReplicationSpec20240805 { + var apiObjects []admin20240805.ReplicationSpec20240805 for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]any) if !ok || tfMap == nil { @@ -926,8 +927,8 @@ func expandAdvancedReplicationSpecsOldSDK(tfList []any) *[]admin20240530.Replica return &apiObjects } -func expandAdvancedReplicationSpec(tfMap map[string]any, rootDiskSizeGB *float64) *admin.ReplicationSpec20240805 { - apiObject := &admin.ReplicationSpec20240805{ +func expandAdvancedReplicationSpec(tfMap map[string]any, rootDiskSizeGB *float64) *admin20240805.ReplicationSpec20240805 { + apiObject := &admin20240805.ReplicationSpec20240805{ ZoneName: conversion.StringPtr(tfMap["zone_name"].(string)), RegionConfigs: expandRegionConfigs(tfMap["region_configs"].([]any), rootDiskSizeGB), } @@ -949,8 +950,8 @@ func expandAdvancedReplicationSpecOldSDK(tfMap map[string]any) *admin20240530.Re return apiObject } -func expandRegionConfigs(tfList []any, rootDiskSizeGB *float64) *[]admin.CloudRegionConfig20240805 { - var apiObjects []admin.CloudRegionConfig20240805 +func expandRegionConfigs(tfList []any, rootDiskSizeGB *float64) *[]admin20240805.CloudRegionConfig20240805 { + var apiObjects []admin20240805.CloudRegionConfig20240805 for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]any) if !ok || tfMap == nil { @@ -965,9 +966,9 @@ func expandRegionConfigs(tfList []any, rootDiskSizeGB *float64) *[]admin.CloudRe return &apiObjects } -func expandRegionConfig(tfMap map[string]any, rootDiskSizeGB *float64) *admin.CloudRegionConfig20240805 { +func expandRegionConfig(tfMap map[string]any, rootDiskSizeGB *float64) *admin20240805.CloudRegionConfig20240805 { providerName := tfMap["provider_name"].(string) - apiObject := &admin.CloudRegionConfig20240805{ + apiObject := &admin20240805.CloudRegionConfig20240805{ Priority: conversion.Pointer(cast.ToInt(tfMap["priority"])), ProviderName: conversion.StringPtr(providerName), RegionName: conversion.StringPtr(tfMap["region_name"].(string)), @@ -994,9 +995,9 @@ func expandRegionConfig(tfMap map[string]any, rootDiskSizeGB *float64) *admin.Cl return apiObject } -func expandRegionConfigSpec(tfList []any, providerName string, rootDiskSizeGB *float64) *admin.DedicatedHardwareSpec20240805 { +func expandRegionConfigSpec(tfList []any, providerName string, rootDiskSizeGB *float64) *admin20240805.DedicatedHardwareSpec20240805 { tfMap, _ := tfList[0].(map[string]any) - apiObject := new(admin.DedicatedHardwareSpec20240805) + apiObject := new(admin20240805.DedicatedHardwareSpec20240805) if providerName == constant.AWS || providerName == constant.AZURE { if v, ok := tfMap["disk_iops"]; ok && v.(int) > 0 { apiObject.DiskIOPS = conversion.Pointer(v.(int)) @@ -1026,11 +1027,11 @@ func expandRegionConfigSpec(tfList []any, providerName string, rootDiskSizeGB *f return apiObject } -func expandRegionConfigAutoScaling(tfList []any) *admin.AdvancedAutoScalingSettings { +func expandRegionConfigAutoScaling(tfList []any) *admin20240805.AdvancedAutoScalingSettings { tfMap, _ := tfList[0].(map[string]any) - settings := admin.AdvancedAutoScalingSettings{ - DiskGB: new(admin.DiskGBAutoScaling), - Compute: new(admin.AdvancedComputeAutoScaling), + settings := admin20240805.AdvancedAutoScalingSettings{ + DiskGB: new(admin20240805.DiskGBAutoScaling), + Compute: new(admin20240805.AdvancedComputeAutoScaling), } if v, ok := tfMap["disk_gb_enabled"]; ok { diff --git a/internal/service/advancedcluster/model_advanced_cluster_test.go b/internal/service/advancedcluster/model_advanced_cluster_test.go index 2bac060c69..129d218f7f 100644 --- a/internal/service/advancedcluster/model_advanced_cluster_test.go +++ b/internal/service/advancedcluster/model_advanced_cluster_test.go @@ -8,8 +8,9 @@ import ( "testing" admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/mockadmin" + admin20240805 "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" + "go.mongodb.org/atlas-sdk/v20241023001/mockadmin" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/stretchr/testify/assert" @@ -450,13 +451,13 @@ func TestCheckRegionConfigsPriorityOrder(t *testing.T) { for name, tc := range testCases { t.Run(name, func(t *testing.T) { - configs := make([]admin.CloudRegionConfig20240805, len(tc.priorities)) + configs := make([]admin20240805.CloudRegionConfig20240805, len(tc.priorities)) configsOld := make([]admin20240530.CloudRegionConfig, len(tc.priorities)) for i, priority := range tc.priorities { configs[i].Priority = conversion.IntPtr(priority) configsOld[i].Priority = conversion.IntPtr(priority) } - err := advancedcluster.CheckRegionConfigsPriorityOrder([]admin.ReplicationSpec20240805{{RegionConfigs: &configs}}) + err := advancedcluster.CheckRegionConfigsPriorityOrder([]admin20240805.ReplicationSpec20240805{{RegionConfigs: &configs}}) assert.Equal(t, tc.errorExpected, err != nil) err = advancedcluster.CheckRegionConfigsPriorityOrderOld([]admin20240530.ReplicationSpec{{RegionConfigs: &configsOld}}) assert.Equal(t, tc.errorExpected, err != nil) diff --git a/internal/service/advancedcluster/model_sdk_version_conversion.go b/internal/service/advancedcluster/model_sdk_version_conversion.go index df477be914..e304771e1e 100644 --- a/internal/service/advancedcluster/model_sdk_version_conversion.go +++ b/internal/service/advancedcluster/model_sdk_version_conversion.go @@ -2,7 +2,8 @@ package advancedcluster import ( admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + admin20240805 "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" ) @@ -19,7 +20,7 @@ func convertTagsPtrToLatest(tags *[]admin20240530.ResourceTag) *[]admin.Resource return &result } -func convertTagsPtrToOldSDK(tags *[]admin.ResourceTag) *[]admin20240530.ResourceTag { +func convertTagsPtrToOldSDK(tags *[]admin20240805.ResourceTag) *[]admin20240530.ResourceTag { if tags == nil { return nil } @@ -47,7 +48,7 @@ func convertTagsToLatest(tags []admin20240530.ResourceTag) []admin.ResourceTag { return results } -func convertBiConnectToOldSDK(biconnector *admin.BiConnector) *admin20240530.BiConnector { +func convertBiConnectToOldSDK(biconnector *admin20240805.BiConnector) *admin20240530.BiConnector { if biconnector == nil { return nil } @@ -125,7 +126,7 @@ func convertLabelsToLatest(labels *[]admin20240530.ComponentLabel) *[]admin.Comp return &results } -func convertLabelSliceToOldSDK(slice []admin.ComponentLabel, err diag.Diagnostics) ([]admin20240530.ComponentLabel, diag.Diagnostics) { +func convertLabelSliceToOldSDK(slice []admin20240805.ComponentLabel, err diag.Diagnostics) ([]admin20240530.ComponentLabel, diag.Diagnostics) { if err != nil { return nil, err } @@ -140,7 +141,7 @@ func convertLabelSliceToOldSDK(slice []admin.ComponentLabel, err diag.Diagnostic return results, nil } -func convertRegionConfigSliceToOldSDK(slice *[]admin.CloudRegionConfig20240805) *[]admin20240530.CloudRegionConfig { +func convertRegionConfigSliceToOldSDK(slice *[]admin20240805.CloudRegionConfig20240805) *[]admin20240530.CloudRegionConfig { if slice == nil { return nil } @@ -163,7 +164,7 @@ func convertRegionConfigSliceToOldSDK(slice *[]admin.CloudRegionConfig20240805) return &results } -func convertHardwareSpecToOldSDK(hwspec *admin.HardwareSpec20240805) *admin20240530.HardwareSpec { +func convertHardwareSpecToOldSDK(hwspec *admin20240805.HardwareSpec20240805) *admin20240530.HardwareSpec { if hwspec == nil { return nil } @@ -175,7 +176,7 @@ func convertHardwareSpecToOldSDK(hwspec *admin.HardwareSpec20240805) *admin20240 } } -func convertAdvancedAutoScalingSettingsToOldSDK(settings *admin.AdvancedAutoScalingSettings) *admin20240530.AdvancedAutoScalingSettings { +func convertAdvancedAutoScalingSettingsToOldSDK(settings *admin20240805.AdvancedAutoScalingSettings) *admin20240530.AdvancedAutoScalingSettings { if settings == nil { return nil } @@ -185,7 +186,7 @@ func convertAdvancedAutoScalingSettingsToOldSDK(settings *admin.AdvancedAutoScal } } -func convertAdvancedComputeAutoScalingToOldSDK(settings *admin.AdvancedComputeAutoScaling) *admin20240530.AdvancedComputeAutoScaling { +func convertAdvancedComputeAutoScalingToOldSDK(settings *admin20240805.AdvancedComputeAutoScaling) *admin20240530.AdvancedComputeAutoScaling { if settings == nil { return nil } @@ -197,7 +198,7 @@ func convertAdvancedComputeAutoScalingToOldSDK(settings *admin.AdvancedComputeAu } } -func convertDiskGBAutoScalingToOldSDK(settings *admin.DiskGBAutoScaling) *admin20240530.DiskGBAutoScaling { +func convertDiskGBAutoScalingToOldSDK(settings *admin20240805.DiskGBAutoScaling) *admin20240530.DiskGBAutoScaling { if settings == nil { return nil } @@ -206,7 +207,7 @@ func convertDiskGBAutoScalingToOldSDK(settings *admin.DiskGBAutoScaling) *admin2 } } -func convertDedicatedHardwareSpecToOldSDK(spec *admin.DedicatedHardwareSpec20240805) *admin20240530.DedicatedHardwareSpec { +func convertDedicatedHardwareSpecToOldSDK(spec *admin20240805.DedicatedHardwareSpec20240805) *admin20240530.DedicatedHardwareSpec { if spec == nil { return nil } diff --git a/internal/service/advancedcluster/resource_advanced_cluster.go b/internal/service/advancedcluster/resource_advanced_cluster.go index 8903bf4574..f3ce41c2b1 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster.go +++ b/internal/service/advancedcluster/resource_advanced_cluster.go @@ -13,7 +13,8 @@ import ( "time" admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + admin20240805 "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -406,6 +407,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. } } connV220240530 := meta.(*config.MongoDBClient).AtlasV220240530 + connV220240805 := meta.(*config.MongoDBClient).AtlasV220240805 connV2 := meta.(*config.MongoDBClient).AtlasV2 projectID := d.Get("project_id").(string) @@ -414,7 +416,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. rootDiskSizeGB = conversion.Pointer(v.(float64)) } - params := &admin.ClusterDescription20240805{ + params := &admin20240805.ClusterDescription20240805{ Name: conversion.StringPtr(cast.ToString(d.Get("name"))), ClusterType: conversion.StringPtr(cast.ToString(d.Get("cluster_type"))), ReplicationSpecs: expandAdvancedReplicationSpecs(d.Get("replication_specs").([]any), rootDiskSizeGB), @@ -440,7 +442,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if _, ok := d.GetOk("tags"); ok { - params.Tags = conversion.ExpandTagsFromSetSchema(d) + params.Tags = conversion.ExpandTagsFromSetSchemaV220240805(d) } if v, ok := d.GetOk("mongo_db_major_version"); ok { params.MongoDBMajorVersion = conversion.StringPtr(FormatMongoDBMajorVersion(v.(string))) @@ -480,7 +482,8 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. if err := CheckRegionConfigsPriorityOrder(params.GetReplicationSpecs()); err != nil { return diag.FromErr(err) } - cluster, _, err := connV2.ClustersApi.CreateCluster(ctx, projectID, params).Execute() + // cannot call latest API (2024-10-23 or newer) as it can enable ISS autoscaling + cluster, _, err := connV220240805.ClustersApi.CreateCluster(ctx, projectID, params).Execute() if err != nil { return diag.FromErr(fmt.Errorf(errorCreate, err)) } @@ -507,10 +510,11 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if v := d.Get("paused").(bool); v { - request := &admin.ClusterDescription20240805{ + request := &admin20240805.ClusterDescription20240805{ Paused: conversion.Pointer(v), } - if _, _, err := connV2.ClustersApi.UpdateCluster(ctx, projectID, d.Get("name").(string), request).Execute(); err != nil { + // can call latest API (2024-10-23 or newer) as autoscaling property is not specified, using older version just for caution until iss autoscaling epic is done + if _, _, err := connV220240805.ClustersApi.UpdateCluster(ctx, projectID, d.Get("name").(string), request).Execute(); err != nil { return diag.FromErr(fmt.Errorf(errorUpdate, d.Get("name").(string), err)) } if err = waitForUpdateToFinish(ctx, connV2, projectID, d.Get("name").(string), timeout); err != nil { @@ -817,6 +821,7 @@ func resourceUpgrade(ctx context.Context, upgradeRequest *admin.LegacyAtlasTenan func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { connV220240530 := meta.(*config.MongoDBClient).AtlasV220240530 + connV220240805 := meta.(*config.MongoDBClient).AtlasV220240805 connV2 := meta.(*config.MongoDBClient).AtlasV2 ids := conversion.DecodeStateID(d.Id()) projectID := ids["project_id"] @@ -845,7 +850,7 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. waitOnUpdate = true } if d.HasChange("replica_set_scaling_strategy") || d.HasChange("redact_client_log_data") || d.HasChange("config_server_management_mode") { - request := new(admin.ClusterDescription20240805) + request := new(admin20240805.ClusterDescription20240805) if d.HasChange("replica_set_scaling_strategy") { request.ReplicaSetScalingStrategy = conversion.Pointer(d.Get("replica_set_scaling_strategy").(string)) } @@ -855,7 +860,8 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. if d.HasChange("config_server_management_mode") { request.ConfigServerManagementMode = conversion.StringPtr(d.Get("config_server_management_mode").(string)) } - if _, _, err := connV2.ClustersApi.UpdateCluster(ctx, projectID, clusterName, request).Execute(); err != nil { + // can call latest API (2024-10-23 or newer) as autoscaling property is not specified, using older version just for caution until iss autoscaling epic is done + if _, _, err := connV220240805.ClustersApi.UpdateCluster(ctx, projectID, clusterName, request).Execute(); err != nil { return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, err)) } waitOnUpdate = true @@ -875,7 +881,8 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. if err := CheckRegionConfigsPriorityOrder(req.GetReplicationSpecs()); err != nil { return diag.FromErr(err) } - if _, _, err := connV2.ClustersApi.UpdateCluster(ctx, projectID, clusterName, req).Execute(); err != nil { + // cannot call latest API (2024-10-23 or newer) as it can enable ISS autoscaling + if _, _, err := connV220240805.ClustersApi.UpdateCluster(ctx, projectID, clusterName, req).Execute(); err != nil { return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, err)) } if err := waitForUpdateToFinish(ctx, connV2, projectID, clusterName, timeout); err != nil { @@ -909,10 +916,11 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if d.Get("paused").(bool) { - clusterRequest := &admin.ClusterDescription20240805{ + clusterRequest := &admin20240805.ClusterDescription20240805{ Paused: conversion.Pointer(true), } - if _, _, err := connV2.ClustersApi.UpdateCluster(ctx, projectID, clusterName, clusterRequest).Execute(); err != nil { + // can call latest API (2024-10-23 or newer) as autoscaling property is not specified, using older version just for caution until iss autoscaling epic is done + if _, _, err := connV220240805.ClustersApi.UpdateCluster(ctx, projectID, clusterName, clusterRequest).Execute(); err != nil { return diag.FromErr(fmt.Errorf(errorUpdate, clusterName, err)) } if err := waitForUpdateToFinish(ctx, connV2, projectID, clusterName, timeout); err != nil { @@ -923,8 +931,8 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. return resourceRead(ctx, d, meta) } -func updateRequest(ctx context.Context, d *schema.ResourceData, projectID, clusterName string, connV2 *admin.APIClient) (*admin.ClusterDescription20240805, diag.Diagnostics) { - cluster := new(admin.ClusterDescription20240805) +func updateRequest(ctx context.Context, d *schema.ResourceData, projectID, clusterName string, connV2 *admin.APIClient) (*admin20240805.ClusterDescription20240805, diag.Diagnostics) { + cluster := new(admin20240805.ClusterDescription20240805) if d.HasChange("replication_specs") || d.HasChange("disk_size_gb") { var updatedDiskSizeGB *float64 @@ -971,7 +979,7 @@ func updateRequest(ctx context.Context, d *schema.ResourceData, projectID, clust } if d.HasChange("tags") { - cluster.Tags = conversion.ExpandTagsFromSetSchema(d) + cluster.Tags = conversion.ExpandTagsFromSetSchemaV220240805(d) } if d.HasChange("mongo_db_major_version") { @@ -1065,7 +1073,7 @@ func updateRequestOldAPI(d *schema.ResourceData, clusterName string) (*admin2024 } if d.HasChange("tags") { - cluster.Tags = convertTagsPtrToOldSDK(conversion.ExpandTagsFromSetSchema(d)) + cluster.Tags = convertTagsPtrToOldSDK(conversion.ExpandTagsFromSetSchemaV220240805(d)) } if d.HasChange("mongo_db_major_version") { diff --git a/internal/service/advancedcluster/resource_advanced_cluster_test.go b/internal/service/advancedcluster/resource_advanced_cluster_test.go index c56d9b2e86..94304dc902 100644 --- a/internal/service/advancedcluster/resource_advanced_cluster_test.go +++ b/internal/service/advancedcluster/resource_advanced_cluster_test.go @@ -8,7 +8,7 @@ import ( "testing" admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/internal/service/advancedcluster/resource_update_logic.go b/internal/service/advancedcluster/resource_update_logic.go index f35abdcfda..19d644c2be 100644 --- a/internal/service/advancedcluster/resource_update_logic.go +++ b/internal/service/advancedcluster/resource_update_logic.go @@ -6,10 +6,11 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + admin20240805 "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) -func noIDsPopulatedInReplicationSpecs(replicationSpecs *[]admin.ReplicationSpec20240805) bool { +func noIDsPopulatedInReplicationSpecs(replicationSpecs *[]admin20240805.ReplicationSpec20240805) bool { if replicationSpecs == nil || len(*replicationSpecs) == 0 { return false } @@ -21,7 +22,7 @@ func noIDsPopulatedInReplicationSpecs(replicationSpecs *[]admin.ReplicationSpec2 return true } -func populateIDValuesUsingNewAPI(ctx context.Context, projectID, clusterName string, connV2ClusterAPI admin.ClustersApi, replicationSpecs *[]admin.ReplicationSpec20240805) (*[]admin.ReplicationSpec20240805, diag.Diagnostics) { +func populateIDValuesUsingNewAPI(ctx context.Context, projectID, clusterName string, connV2ClusterAPI admin.ClustersApi, replicationSpecs *[]admin20240805.ReplicationSpec20240805) (*[]admin20240805.ReplicationSpec20240805, diag.Diagnostics) { if replicationSpecs == nil || len(*replicationSpecs) == 0 { return replicationSpecs, nil } @@ -35,7 +36,7 @@ func populateIDValuesUsingNewAPI(ctx context.Context, projectID, clusterName str return &result, nil } -func AddIDsToReplicationSpecs(replicationSpecs []admin.ReplicationSpec20240805, zoneToReplicationSpecsIDs map[string][]string) []admin.ReplicationSpec20240805 { +func AddIDsToReplicationSpecs(replicationSpecs []admin20240805.ReplicationSpec20240805, zoneToReplicationSpecsIDs map[string][]string) []admin20240805.ReplicationSpec20240805 { for zoneName, availableIDs := range zoneToReplicationSpecsIDs { var indexOfIDToUse = 0 for i := range replicationSpecs { @@ -64,12 +65,12 @@ func groupIDsByZone(specs []admin.ReplicationSpec20240805) map[string][]string { // - Existing replication specs can have the autoscaling values present in the state with default values even if not defined in the config (case when cluster is imported) // - API expects autoScaling and analyticsAutoScaling aligned cross all region configs in the PATCH request // This function is needed to avoid errors if a new replication spec is added, ensuring the PATCH request will have the auto scaling aligned with other replication specs when not present in config. -func SyncAutoScalingConfigs(replicationSpecs *[]admin.ReplicationSpec20240805) { +func SyncAutoScalingConfigs(replicationSpecs *[]admin20240805.ReplicationSpec20240805) { if replicationSpecs == nil || len(*replicationSpecs) == 0 { return } - var defaultAnalyticsAutoScaling, defaultAutoScaling *admin.AdvancedAutoScalingSettings + var defaultAnalyticsAutoScaling, defaultAutoScaling *admin20240805.AdvancedAutoScalingSettings for _, spec := range *replicationSpecs { for i := range *spec.RegionConfigs { @@ -85,7 +86,7 @@ func SyncAutoScalingConfigs(replicationSpecs *[]admin.ReplicationSpec20240805) { applyDefaultAutoScaling(replicationSpecs, defaultAutoScaling, defaultAnalyticsAutoScaling) } -func applyDefaultAutoScaling(replicationSpecs *[]admin.ReplicationSpec20240805, defaultAutoScaling, defaultAnalyticsAutoScaling *admin.AdvancedAutoScalingSettings) { +func applyDefaultAutoScaling(replicationSpecs *[]admin20240805.ReplicationSpec20240805, defaultAutoScaling, defaultAnalyticsAutoScaling *admin20240805.AdvancedAutoScalingSettings) { for _, spec := range *replicationSpecs { for i := range *spec.RegionConfigs { regionConfig := &(*spec.RegionConfigs)[i] diff --git a/internal/service/advancedcluster/resource_update_logic_test.go b/internal/service/advancedcluster/resource_update_logic_test.go index 398b169204..499f0a8e42 100644 --- a/internal/service/advancedcluster/resource_update_logic_test.go +++ b/internal/service/advancedcluster/resource_update_logic_test.go @@ -5,17 +5,18 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/advancedcluster" "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + admin20240805 "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func TestAddIDsToReplicationSpecs(t *testing.T) { testCases := map[string]struct { - ReplicationSpecs []admin.ReplicationSpec20240805 + ReplicationSpecs []admin20240805.ReplicationSpec20240805 ZoneToReplicationSpecsIDs map[string][]string - ExpectedReplicationSpecs []admin.ReplicationSpec20240805 + ExpectedReplicationSpecs []admin20240805.ReplicationSpec20240805 }{ "two zones with same amount of available ids and replication specs to populate": { - ReplicationSpecs: []admin.ReplicationSpec20240805{ + ReplicationSpecs: []admin20240805.ReplicationSpec20240805{ { ZoneName: admin.PtrString("Zone 1"), }, @@ -33,7 +34,7 @@ func TestAddIDsToReplicationSpecs(t *testing.T) { "Zone 1": {"zone1-id1", "zone1-id2"}, "Zone 2": {"zone2-id1", "zone2-id2"}, }, - ExpectedReplicationSpecs: []admin.ReplicationSpec20240805{ + ExpectedReplicationSpecs: []admin20240805.ReplicationSpec20240805{ { ZoneName: admin.PtrString("Zone 1"), Id: admin.PtrString("zone1-id1"), @@ -53,7 +54,7 @@ func TestAddIDsToReplicationSpecs(t *testing.T) { }, }, "less available ids than replication specs to populate": { - ReplicationSpecs: []admin.ReplicationSpec20240805{ + ReplicationSpecs: []admin20240805.ReplicationSpec20240805{ { ZoneName: admin.PtrString("Zone 1"), }, @@ -71,7 +72,7 @@ func TestAddIDsToReplicationSpecs(t *testing.T) { "Zone 1": {"zone1-id1"}, "Zone 2": {"zone2-id1"}, }, - ExpectedReplicationSpecs: []admin.ReplicationSpec20240805{ + ExpectedReplicationSpecs: []admin20240805.ReplicationSpec20240805{ { ZoneName: admin.PtrString("Zone 1"), Id: admin.PtrString("zone1-id1"), @@ -91,7 +92,7 @@ func TestAddIDsToReplicationSpecs(t *testing.T) { }, }, "more available ids than replication specs to populate": { - ReplicationSpecs: []admin.ReplicationSpec20240805{ + ReplicationSpecs: []admin20240805.ReplicationSpec20240805{ { ZoneName: admin.PtrString("Zone 1"), }, @@ -103,7 +104,7 @@ func TestAddIDsToReplicationSpecs(t *testing.T) { "Zone 1": {"zone1-id1", "zone1-id2"}, "Zone 2": {"zone2-id1", "zone2-id2"}, }, - ExpectedReplicationSpecs: []admin.ReplicationSpec20240805{ + ExpectedReplicationSpecs: []admin20240805.ReplicationSpec20240805{ { ZoneName: admin.PtrString("Zone 1"), Id: admin.PtrString("zone1-id1"), @@ -126,23 +127,23 @@ func TestAddIDsToReplicationSpecs(t *testing.T) { func TestSyncAutoScalingConfigs(t *testing.T) { testCases := map[string]struct { - ReplicationSpecs []admin.ReplicationSpec20240805 - ExpectedReplicationSpecs []admin.ReplicationSpec20240805 + ReplicationSpecs []admin20240805.ReplicationSpec20240805 + ExpectedReplicationSpecs []admin20240805.ReplicationSpec20240805 }{ "apply same autoscaling options for new replication spec which does not have autoscaling defined": { - ReplicationSpecs: []admin.ReplicationSpec20240805{ + ReplicationSpecs: []admin20240805.ReplicationSpec20240805{ { Id: admin.PtrString("id-1"), - RegionConfigs: &[]admin.CloudRegionConfig20240805{ + RegionConfigs: &[]admin20240805.CloudRegionConfig20240805{ { - AutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(false), ScaleDownEnabled: admin.PtrBool(false), }, }, - AnalyticsAutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AnalyticsAutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(false), ScaleDownEnabled: admin.PtrBool(false), }, @@ -152,7 +153,7 @@ func TestSyncAutoScalingConfigs(t *testing.T) { }, { Id: admin.PtrString("id-2"), - RegionConfigs: &[]admin.CloudRegionConfig20240805{ + RegionConfigs: &[]admin20240805.CloudRegionConfig20240805{ { AutoScaling: nil, AnalyticsAutoScaling: nil, @@ -160,19 +161,19 @@ func TestSyncAutoScalingConfigs(t *testing.T) { }, }, }, - ExpectedReplicationSpecs: []admin.ReplicationSpec20240805{ + ExpectedReplicationSpecs: []admin20240805.ReplicationSpec20240805{ { Id: admin.PtrString("id-1"), - RegionConfigs: &[]admin.CloudRegionConfig20240805{ + RegionConfigs: &[]admin20240805.CloudRegionConfig20240805{ { - AutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(false), ScaleDownEnabled: admin.PtrBool(false), }, }, - AnalyticsAutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AnalyticsAutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(false), ScaleDownEnabled: admin.PtrBool(false), }, @@ -182,16 +183,16 @@ func TestSyncAutoScalingConfigs(t *testing.T) { }, { Id: admin.PtrString("id-2"), - RegionConfigs: &[]admin.CloudRegionConfig20240805{ + RegionConfigs: &[]admin20240805.CloudRegionConfig20240805{ { - AutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(false), ScaleDownEnabled: admin.PtrBool(false), }, }, - AnalyticsAutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AnalyticsAutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(false), ScaleDownEnabled: admin.PtrBool(false), }, @@ -203,19 +204,19 @@ func TestSyncAutoScalingConfigs(t *testing.T) { }, // for this case the API will respond with an error and guide the user to align autoscaling options cross all nodes "when different autoscaling options are defined values will not be changed": { - ReplicationSpecs: []admin.ReplicationSpec20240805{ + ReplicationSpecs: []admin20240805.ReplicationSpec20240805{ { Id: admin.PtrString("id-1"), - RegionConfigs: &[]admin.CloudRegionConfig20240805{ + RegionConfigs: &[]admin20240805.CloudRegionConfig20240805{ { - AutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(false), ScaleDownEnabled: admin.PtrBool(false), }, }, - AnalyticsAutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AnalyticsAutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(true), ScaleDownEnabled: admin.PtrBool(true), }, @@ -225,15 +226,15 @@ func TestSyncAutoScalingConfigs(t *testing.T) { }, { Id: admin.PtrString("id-2"), - RegionConfigs: &[]admin.CloudRegionConfig20240805{ + RegionConfigs: &[]admin20240805.CloudRegionConfig20240805{ { - AutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(true), }, }, - AnalyticsAutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AnalyticsAutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(false), }, }, @@ -241,19 +242,19 @@ func TestSyncAutoScalingConfigs(t *testing.T) { }, }, }, - ExpectedReplicationSpecs: []admin.ReplicationSpec20240805{ + ExpectedReplicationSpecs: []admin20240805.ReplicationSpec20240805{ { Id: admin.PtrString("id-1"), - RegionConfigs: &[]admin.CloudRegionConfig20240805{ + RegionConfigs: &[]admin20240805.CloudRegionConfig20240805{ { - AutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(false), ScaleDownEnabled: admin.PtrBool(false), }, }, - AnalyticsAutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AnalyticsAutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(true), ScaleDownEnabled: admin.PtrBool(true), }, @@ -263,15 +264,15 @@ func TestSyncAutoScalingConfigs(t *testing.T) { }, { Id: admin.PtrString("id-2"), - RegionConfigs: &[]admin.CloudRegionConfig20240805{ + RegionConfigs: &[]admin20240805.CloudRegionConfig20240805{ { - AutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(true), }, }, - AnalyticsAutoScaling: &admin.AdvancedAutoScalingSettings{ - Compute: &admin.AdvancedComputeAutoScaling{ + AnalyticsAutoScaling: &admin20240805.AdvancedAutoScalingSettings{ + Compute: &admin20240805.AdvancedComputeAutoScaling{ Enabled: admin.PtrBool(false), }, }, diff --git a/internal/service/advancedclustertpf/model.go b/internal/service/advancedclustertpf/model.go index 3d3ffb13a6..c6809388db 100644 --- a/internal/service/advancedclustertpf/model.go +++ b/internal/service/advancedclustertpf/model.go @@ -4,7 +4,7 @@ import ( "context" "github.com/hashicorp/terraform-plugin-framework/diag" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewTFModel(ctx context.Context, apiResp *admin.ClusterDescription20240805) (*TFModel, diag.Diagnostics) { diff --git a/internal/service/alertconfiguration/data_source_alert_configuration.go b/internal/service/alertconfiguration/data_source_alert_configuration.go index 31283ca3db..ea26af85c1 100644 --- a/internal/service/alertconfiguration/data_source_alert_configuration.go +++ b/internal/service/alertconfiguration/data_source_alert_configuration.go @@ -14,7 +14,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "github.com/zclconf/go-cty/cty" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) var _ datasource.DataSource = &alertConfigurationDS{} diff --git a/internal/service/alertconfiguration/data_source_alert_configurations.go b/internal/service/alertconfiguration/data_source_alert_configurations.go index e37c93294a..123185ef73 100644 --- a/internal/service/alertconfiguration/data_source_alert_configurations.go +++ b/internal/service/alertconfiguration/data_source_alert_configurations.go @@ -11,7 +11,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const alertConfigurationsDataSourceName = "alert_configurations" diff --git a/internal/service/alertconfiguration/model_alert_configuration.go b/internal/service/alertconfiguration/model_alert_configuration.go index a54d7cf84a..a8b06c40d1 100644 --- a/internal/service/alertconfiguration/model_alert_configuration.go +++ b/internal/service/alertconfiguration/model_alert_configuration.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework/types" diff --git a/internal/service/alertconfiguration/model_alert_configuration_test.go b/internal/service/alertconfiguration/model_alert_configuration_test.go index c7f93a6db5..d2ddfda97e 100644 --- a/internal/service/alertconfiguration/model_alert_configuration_test.go +++ b/internal/service/alertconfiguration/model_alert_configuration_test.go @@ -7,7 +7,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/alertconfiguration" "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/alertconfiguration/resource_alert_configuration.go b/internal/service/alertconfiguration/resource_alert_configuration.go index 350b57fb92..80cedcba9a 100644 --- a/internal/service/alertconfiguration/resource_alert_configuration.go +++ b/internal/service/alertconfiguration/resource_alert_configuration.go @@ -6,7 +6,7 @@ import ( "reflect" "strings" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" diff --git a/internal/service/apikey/data_source_api_keys.go b/internal/service/apikey/data_source_api_keys.go index c02d397e73..ecf2a64985 100644 --- a/internal/service/apikey/data_source_api_keys.go +++ b/internal/service/apikey/data_source_api_keys.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/apikey/resource_api_key.go b/internal/service/apikey/resource_api_key.go index 264ee0e7d0..8bdc491093 100644 --- a/internal/service/apikey/resource_api_key.go +++ b/internal/service/apikey/resource_api_key.go @@ -12,7 +12,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func Resource() *schema.Resource { diff --git a/internal/service/atlasuser/data_source_atlas_user.go b/internal/service/atlasuser/data_source_atlas_user.go index 8c1e148d09..7c2d932589 100644 --- a/internal/service/atlasuser/data_source_atlas_user.go +++ b/internal/service/atlasuser/data_source_atlas_user.go @@ -12,7 +12,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/atlasuser/data_source_atlas_user_test.go b/internal/service/atlasuser/data_source_atlas_user_test.go index c4d7e8beda..0af7d324e1 100644 --- a/internal/service/atlasuser/data_source_atlas_user_test.go +++ b/internal/service/atlasuser/data_source_atlas_user_test.go @@ -10,7 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func TestAccConfigDSAtlasUser_ByUserID(t *testing.T) { diff --git a/internal/service/atlasuser/data_source_atlas_users.go b/internal/service/atlasuser/data_source_atlas_users.go index af477b073b..a4d9c577ea 100644 --- a/internal/service/atlasuser/data_source_atlas_users.go +++ b/internal/service/atlasuser/data_source_atlas_users.go @@ -13,7 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/atlasuser/data_source_atlas_users_test.go b/internal/service/atlasuser/data_source_atlas_users_test.go index b8699db6b7..10220c9a6e 100644 --- a/internal/service/atlasuser/data_source_atlas_users_test.go +++ b/internal/service/atlasuser/data_source_atlas_users_test.go @@ -11,7 +11,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/atlasuser" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func TestAccConfigDSAtlasUsers_ByOrgID(t *testing.T) { diff --git a/internal/service/auditing/resource_auditing.go b/internal/service/auditing/resource_auditing.go index 334023fe4b..5023f3e58a 100644 --- a/internal/service/auditing/resource_auditing.go +++ b/internal/service/auditing/resource_auditing.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/backupcompliancepolicy/resource_backup_compliance_policy.go b/internal/service/backupcompliancepolicy/resource_backup_compliance_policy.go index 1c0d783dc1..0f8d98e0e4 100644 --- a/internal/service/backupcompliancepolicy/resource_backup_compliance_policy.go +++ b/internal/service/backupcompliancepolicy/resource_backup_compliance_policy.go @@ -8,7 +8,7 @@ import ( "net/http" "strings" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" diff --git a/internal/service/cloudbackupschedule/data_source_cloud_backup_schedule.go b/internal/service/cloudbackupschedule/data_source_cloud_backup_schedule.go index b6c641fd1a..22ebe0ed7b 100644 --- a/internal/service/cloudbackupschedule/data_source_cloud_backup_schedule.go +++ b/internal/service/cloudbackupschedule/data_source_cloud_backup_schedule.go @@ -8,7 +8,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/cloudbackupschedule/model_cloud_backup_schedule.go b/internal/service/cloudbackupschedule/model_cloud_backup_schedule.go index 8c5e88b3f1..5d756ac92a 100644 --- a/internal/service/cloudbackupschedule/model_cloud_backup_schedule.go +++ b/internal/service/cloudbackupschedule/model_cloud_backup_schedule.go @@ -2,7 +2,7 @@ package cloudbackupschedule import ( admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func FlattenPolicyItem(items []admin.DiskBackupApiPolicyItem, frequencyType string) []map[string]any { diff --git a/internal/service/cloudbackupschedule/model_cloud_backup_schedule_test.go b/internal/service/cloudbackupschedule/model_cloud_backup_schedule_test.go index 753991dd63..b88fcc53a9 100644 --- a/internal/service/cloudbackupschedule/model_cloud_backup_schedule_test.go +++ b/internal/service/cloudbackupschedule/model_cloud_backup_schedule_test.go @@ -6,7 +6,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/cloudbackupschedule" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func TestFlattenPolicyItem(t *testing.T) { diff --git a/internal/service/cloudbackupschedule/model_sdk_version_conversion.go b/internal/service/cloudbackupschedule/model_sdk_version_conversion.go index a30e05ca11..b3d345eb5f 100644 --- a/internal/service/cloudbackupschedule/model_sdk_version_conversion.go +++ b/internal/service/cloudbackupschedule/model_sdk_version_conversion.go @@ -2,7 +2,7 @@ package cloudbackupschedule import ( admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) // Conversions from one SDK model version to another are used to avoid duplicating our flatten/expand conversion functions. diff --git a/internal/service/cloudbackupschedule/resource_cloud_backup_schedule.go b/internal/service/cloudbackupschedule/resource_cloud_backup_schedule.go index ddabb7607c..992051ba86 100644 --- a/internal/service/cloudbackupschedule/resource_cloud_backup_schedule.go +++ b/internal/service/cloudbackupschedule/resource_cloud_backup_schedule.go @@ -14,7 +14,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "github.com/spf13/cast" admin20240530 "go.mongodb.org/atlas-sdk/v20240530005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/cloudbackupsnapshot/data_source_cloud_backup_snapshots.go b/internal/service/cloudbackupsnapshot/data_source_cloud_backup_snapshots.go index 2128093af2..7400e27f68 100644 --- a/internal/service/cloudbackupsnapshot/data_source_cloud_backup_snapshots.go +++ b/internal/service/cloudbackupsnapshot/data_source_cloud_backup_snapshots.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/cloudbackupsnapshot/model_cloud_backup_snapshot.go b/internal/service/cloudbackupsnapshot/model_cloud_backup_snapshot.go index 014d8decfd..ec48ea5728 100644 --- a/internal/service/cloudbackupsnapshot/model_cloud_backup_snapshot.go +++ b/internal/service/cloudbackupsnapshot/model_cloud_backup_snapshot.go @@ -4,7 +4,7 @@ import ( "errors" "regexp" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func SplitSnapshotImportID(id string) (*admin.GetReplicaSetBackupApiParams, error) { diff --git a/internal/service/cloudbackupsnapshot/model_cloud_backup_snapshot_test.go b/internal/service/cloudbackupsnapshot/model_cloud_backup_snapshot_test.go index b7743f2ea8..ff8c8836ee 100644 --- a/internal/service/cloudbackupsnapshot/model_cloud_backup_snapshot_test.go +++ b/internal/service/cloudbackupsnapshot/model_cloud_backup_snapshot_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/cloudbackupsnapshot" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func TestSplitSnapshotImportID(t *testing.T) { diff --git a/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot.go b/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot.go index 54d4c93ffd..ac4209a445 100644 --- a/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot.go +++ b/internal/service/cloudbackupsnapshot/resource_cloud_backup_snapshot.go @@ -14,7 +14,7 @@ import ( "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" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func Resource() *schema.Resource { diff --git a/internal/service/cloudbackupsnapshotexportbucket/data_source_cloud_backup_snapshot_export_buckets.go b/internal/service/cloudbackupsnapshotexportbucket/data_source_cloud_backup_snapshot_export_buckets.go index a3ba47d412..72cea750d6 100644 --- a/internal/service/cloudbackupsnapshotexportbucket/data_source_cloud_backup_snapshot_export_buckets.go +++ b/internal/service/cloudbackupsnapshotexportbucket/data_source_cloud_backup_snapshot_export_buckets.go @@ -7,7 +7,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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { @@ -95,7 +95,7 @@ func dataSourceRead(ctx context.Context, d *schema.ResourceData, meta any) diag. return nil } -func flattenBuckets(buckets []admin.DiskBackupSnapshotExportBucket) []map[string]any { +func flattenBuckets(buckets []admin.DiskBackupSnapshotExportBucketResponse) []map[string]any { var results []map[string]any if len(buckets) == 0 { diff --git a/internal/service/cloudbackupsnapshotexportbucket/resource_cloud_backup_snapshot_export_bucket.go b/internal/service/cloudbackupsnapshotexportbucket/resource_cloud_backup_snapshot_export_bucket.go index e9c07d8e9f..1ff182b7b8 100644 --- a/internal/service/cloudbackupsnapshotexportbucket/resource_cloud_backup_snapshot_export_bucket.go +++ b/internal/service/cloudbackupsnapshotexportbucket/resource_cloud_backup_snapshot_export_bucket.go @@ -14,7 +14,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func Resource() *schema.Resource { @@ -84,7 +84,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. cloudProvider := d.Get("cloud_provider").(string) - request := &admin.DiskBackupSnapshotExportBucket{ + request := &admin.DiskBackupSnapshotExportBucketRequest{ IamRoleId: conversion.StringPtr(d.Get("iam_role_id").(string)), BucketName: d.Get("bucket_name").(string), RoleId: conversion.StringPtr(d.Get("role_id").(string)), diff --git a/internal/service/cloudbackupsnapshotexportjob/data_source_cloud_backup_snapshot_export_jobs.go b/internal/service/cloudbackupsnapshotexportjob/data_source_cloud_backup_snapshot_export_jobs.go index 7d2564b1a4..7727f542be 100644 --- a/internal/service/cloudbackupsnapshotexportjob/data_source_cloud_backup_snapshot_export_jobs.go +++ b/internal/service/cloudbackupsnapshotexportjob/data_source_cloud_backup_snapshot_export_jobs.go @@ -8,7 +8,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job.go b/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job.go index 7258144d05..92edd2cfeb 100644 --- a/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job.go +++ b/internal/service/cloudbackupsnapshotexportjob/resource_cloud_backup_snapshot_export_job.go @@ -10,7 +10,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func Resource() *schema.Resource { diff --git a/internal/service/cloudbackupsnapshotrestorejob/data_source_cloud_backup_snapshot_restore_jobs.go b/internal/service/cloudbackupsnapshotrestorejob/data_source_cloud_backup_snapshot_restore_jobs.go index 279a87be16..b9b7f2da20 100644 --- a/internal/service/cloudbackupsnapshotrestorejob/data_source_cloud_backup_snapshot_restore_jobs.go +++ b/internal/service/cloudbackupsnapshotrestorejob/data_source_cloud_backup_snapshot_restore_jobs.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/cloudbackupsnapshotrestorejob/resource_cloud_backup_snapshot_restore_job.go b/internal/service/cloudbackupsnapshotrestorejob/resource_cloud_backup_snapshot_restore_job.go index 79265ba2db..46b89309ab 100644 --- a/internal/service/cloudbackupsnapshotrestorejob/resource_cloud_backup_snapshot_restore_job.go +++ b/internal/service/cloudbackupsnapshotrestorejob/resource_cloud_backup_snapshot_restore_job.go @@ -12,7 +12,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func Resource() *schema.Resource { diff --git a/internal/service/cloudprovideraccess/resource_cloud_provider_access_authorization.go b/internal/service/cloudprovideraccess/resource_cloud_provider_access_authorization.go index 87a9cfaa9c..9b0688eed7 100644 --- a/internal/service/cloudprovideraccess/resource_cloud_provider_access_authorization.go +++ b/internal/service/cloudprovideraccess/resource_cloud_provider_access_authorization.go @@ -12,7 +12,7 @@ import ( "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/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) /* diff --git a/internal/service/cloudprovideraccess/resource_cloud_provider_access_setup.go b/internal/service/cloudprovideraccess/resource_cloud_provider_access_setup.go index 9021f7e21f..b49cf589d1 100644 --- a/internal/service/cloudprovideraccess/resource_cloud_provider_access_setup.go +++ b/internal/service/cloudprovideraccess/resource_cloud_provider_access_setup.go @@ -6,7 +6,7 @@ import ( "net/http" "regexp" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" diff --git a/internal/service/cluster/new_atlas.go b/internal/service/cluster/new_atlas.go index 74d96f1473..b12132c2f3 100644 --- a/internal/service/cluster/new_atlas.go +++ b/internal/service/cluster/new_atlas.go @@ -5,10 +5,11 @@ import ( "time" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/advancedcluster" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + admin20240805 "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) -func newAtlasUpdate(ctx context.Context, timeout time.Duration, connV2 *admin.APIClient, projectID, clusterName string, redactClientLogData bool) error { +func newAtlasUpdate(ctx context.Context, timeout time.Duration, connV2 *admin.APIClient, connV220240805 *admin20240805.APIClient, projectID, clusterName string, redactClientLogData bool) error { current, err := newAtlasGet(ctx, connV2, projectID, clusterName) if err != nil { return err @@ -16,10 +17,11 @@ func newAtlasUpdate(ctx context.Context, timeout time.Duration, connV2 *admin.AP if current == redactClientLogData { return nil } - req := &admin.ClusterDescription20240805{ + req := &admin20240805.ClusterDescription20240805{ RedactClientLogData: &redactClientLogData, } - if _, _, err = connV2.ClustersApi.UpdateCluster(ctx, projectID, clusterName, req).Execute(); err != nil { + // can call latest API (2024-10-23 or newer) as autoscaling property is not specified, using older version just for caution until iss autoscaling epic is done + if _, _, err = connV220240805.ClustersApi.UpdateCluster(ctx, projectID, clusterName, req).Execute(); err != nil { return err } stateConf := advancedcluster.CreateStateChangeConfig(ctx, connV2, projectID, clusterName, timeout) diff --git a/internal/service/cluster/resource_cluster.go b/internal/service/cluster/resource_cluster.go index 43bb2bc624..99b93ed3c2 100644 --- a/internal/service/cluster/resource_cluster.go +++ b/internal/service/cluster/resource_cluster.go @@ -11,7 +11,7 @@ import ( "regexp" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" matlas "go.mongodb.org/atlas/mongodbatlas" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -374,6 +374,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. var ( conn = meta.(*config.MongoDBClient).Atlas connV2 = meta.(*config.MongoDBClient).AtlasV2 + connV220240805 = meta.(*config.MongoDBClient).AtlasV220240805 projectID = d.Get("project_id").(string) clusterName = d.Get("name").(string) providerName = d.Get("provider_name").(string) @@ -577,7 +578,7 @@ func resourceCreate(ctx context.Context, d *schema.ResourceData, meta any) diag. } if v, ok := d.GetOk("redact_client_log_data"); ok { - if err := newAtlasUpdate(ctx, d.Timeout(schema.TimeoutCreate), connV2, projectID, clusterName, v.(bool)); err != nil { + if err := newAtlasUpdate(ctx, d.Timeout(schema.TimeoutCreate), connV2, connV220240805, projectID, clusterName, v.(bool)); err != nil { return diag.FromErr(fmt.Errorf(errorClusterUpdate, clusterName, err)) } } @@ -790,6 +791,7 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. var ( conn = meta.(*config.MongoDBClient).Atlas connV2 = meta.(*config.MongoDBClient).AtlasV2 + connV220240805 = meta.(*config.MongoDBClient).AtlasV220240805 ids = conversion.DecodeStateID(d.Id()) projectID = ids["project_id"] clusterName = ids["cluster_name"] @@ -1004,7 +1006,7 @@ func resourceUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag. if d.HasChange("redact_client_log_data") { redactClientLogData := d.Get("redact_client_log_data").(bool) - if err := newAtlasUpdate(ctx, d.Timeout(schema.TimeoutUpdate), connV2, projectID, clusterName, redactClientLogData); err != nil { + if err := newAtlasUpdate(ctx, d.Timeout(schema.TimeoutUpdate), connV2, connV220240805, projectID, clusterName, redactClientLogData); err != nil { return diag.FromErr(fmt.Errorf(errorClusterUpdate, clusterName, err)) } } diff --git a/internal/service/clusteroutagesimulation/resource_cluster_outage_simulation.go b/internal/service/clusteroutagesimulation/resource_cluster_outage_simulation.go index efa04665db..9badd4799c 100644 --- a/internal/service/clusteroutagesimulation/resource_cluster_outage_simulation.go +++ b/internal/service/clusteroutagesimulation/resource_cluster_outage_simulation.go @@ -12,7 +12,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/controlplaneipaddresses/model.go b/internal/service/controlplaneipaddresses/model.go index bc63ed43b4..7cd0139cb3 100644 --- a/internal/service/controlplaneipaddresses/model.go +++ b/internal/service/controlplaneipaddresses/model.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewTFControlPlaneIPAddresses(ctx context.Context, apiResp *admin.ControlPlaneIPAddresses) (*TFControlPlaneIpAddressesModel, diag.Diagnostics) { diff --git a/internal/service/controlplaneipaddresses/model_test.go b/internal/service/controlplaneipaddresses/model_test.go index 943617afe8..7ecb295302 100644 --- a/internal/service/controlplaneipaddresses/model_test.go +++ b/internal/service/controlplaneipaddresses/model_test.go @@ -9,7 +9,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/controlplaneipaddresses" "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) type sdkToTFModelTestCase struct { diff --git a/internal/service/customdbrole/data_source_custom_db_roles.go b/internal/service/customdbrole/data_source_custom_db_roles.go index b03e38f87b..8ab58f54c7 100644 --- a/internal/service/customdbrole/data_source_custom_db_roles.go +++ b/internal/service/customdbrole/data_source_custom_db_roles.go @@ -8,7 +8,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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/customdbrole/resource_custom_db_role.go b/internal/service/customdbrole/resource_custom_db_role.go index 80c4d2850a..aecfd685d1 100644 --- a/internal/service/customdbrole/resource_custom_db_role.go +++ b/internal/service/customdbrole/resource_custom_db_role.go @@ -17,7 +17,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/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func Resource() *schema.Resource { diff --git a/internal/service/customdbrole/resource_custom_db_role_test.go b/internal/service/customdbrole/resource_custom_db_role_test.go index 04b71898a6..82a45e8e1e 100644 --- a/internal/service/customdbrole/resource_custom_db_role_test.go +++ b/internal/service/customdbrole/resource_custom_db_role_test.go @@ -11,7 +11,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" "github.com/spf13/cast" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const resourceName = "mongodbatlas_custom_db_role.test" diff --git a/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws.go b/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws.go index 4f0e1edc3b..b538be4952 100644 --- a/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws.go +++ b/internal/service/customdnsconfigurationclusteraws/resource_custom_dns_configuration_cluster_aws.go @@ -9,7 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/databaseuser/model_database_user.go b/internal/service/databaseuser/model_database_user.go index 1df575ba49..0f2da2f97f 100644 --- a/internal/service/databaseuser/model_database_user.go +++ b/internal/service/databaseuser/model_database_user.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewMongoDBDatabaseUser(ctx context.Context, statePasswordValue types.String, dbUserModel *TfDatabaseUserModel) (*admin.CloudDatabaseUser, diag.Diagnostics) { diff --git a/internal/service/databaseuser/model_database_user_test.go b/internal/service/databaseuser/model_database_user_test.go index eb2a42d375..1b731b58a3 100644 --- a/internal/service/databaseuser/model_database_user_test.go +++ b/internal/service/databaseuser/model_database_user_test.go @@ -9,7 +9,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/databaseuser" "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) var ( diff --git a/internal/service/databaseuser/resource_database_user_migration_test.go b/internal/service/databaseuser/resource_database_user_migration_test.go index 2817e9b54e..215915e41c 100644 --- a/internal/service/databaseuser/resource_database_user_migration_test.go +++ b/internal/service/databaseuser/resource_database_user_migration_test.go @@ -3,7 +3,7 @@ package databaseuser_test import ( "testing" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" diff --git a/internal/service/databaseuser/resource_database_user_test.go b/internal/service/databaseuser/resource_database_user_test.go index ef56682512..3b419e3c61 100644 --- a/internal/service/databaseuser/resource_database_user_test.go +++ b/internal/service/databaseuser/resource_database_user_test.go @@ -11,7 +11,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/databaseuser" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/datalakepipeline/data_source_data_lake_pipeline_run.go b/internal/service/datalakepipeline/data_source_data_lake_pipeline_run.go index b0f98fe6ae..02e7114d92 100644 --- a/internal/service/datalakepipeline/data_source_data_lake_pipeline_run.go +++ b/internal/service/datalakepipeline/data_source_data_lake_pipeline_run.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const errorDataLakePipelineRunRead = "error reading MongoDB Atlas DataLake Run (%s): %s" diff --git a/internal/service/datalakepipeline/data_source_data_lake_pipeline_runs.go b/internal/service/datalakepipeline/data_source_data_lake_pipeline_runs.go index 660c7f647c..d8372595bc 100644 --- a/internal/service/datalakepipeline/data_source_data_lake_pipeline_runs.go +++ b/internal/service/datalakepipeline/data_source_data_lake_pipeline_runs.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const errorDataLakePipelineRunList = "error reading MongoDB Atlas DataLake Runs (%s): %s" diff --git a/internal/service/datalakepipeline/data_source_data_lake_pipelines.go b/internal/service/datalakepipeline/data_source_data_lake_pipelines.go index 4a46e80aa9..0fa0289b51 100644 --- a/internal/service/datalakepipeline/data_source_data_lake_pipelines.go +++ b/internal/service/datalakepipeline/data_source_data_lake_pipelines.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const errorDataLakePipelineList = "error creating MongoDB Atlas DataLake Pipelines: %s" diff --git a/internal/service/datalakepipeline/resource_data_lake_pipeline.go b/internal/service/datalakepipeline/resource_data_lake_pipeline.go index 4ed2b1b462..d280f822bd 100644 --- a/internal/service/datalakepipeline/resource_data_lake_pipeline.go +++ b/internal/service/datalakepipeline/resource_data_lake_pipeline.go @@ -11,7 +11,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/encryptionatrest/data_source_schema.go b/internal/service/encryptionatrest/data_source_schema.go index e42897179e..1ea995ce7d 100644 --- a/internal/service/encryptionatrest/data_source_schema.go +++ b/internal/service/encryptionatrest/data_source_schema.go @@ -3,7 +3,7 @@ package encryptionatrest import ( "context" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework/datasource/schema" "github.com/hashicorp/terraform-plugin-framework/types" diff --git a/internal/service/encryptionatrest/model.go b/internal/service/encryptionatrest/model.go index c86ff3e811..a7d8a5a1e4 100644 --- a/internal/service/encryptionatrest/model.go +++ b/internal/service/encryptionatrest/model.go @@ -3,7 +3,7 @@ package encryptionatrest import ( "context" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework/types" diff --git a/internal/service/encryptionatrest/model_test.go b/internal/service/encryptionatrest/model_test.go index 022d832401..55c4ce5d77 100644 --- a/internal/service/encryptionatrest/model_test.go +++ b/internal/service/encryptionatrest/model_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework/types" "github.com/stretchr/testify/assert" diff --git a/internal/service/encryptionatrest/resource.go b/internal/service/encryptionatrest/resource.go index b6a08cae0f..97e8ea5170 100644 --- a/internal/service/encryptionatrest/resource.go +++ b/internal/service/encryptionatrest/resource.go @@ -9,7 +9,7 @@ import ( "reflect" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" "github.com/hashicorp/terraform-plugin-framework/path" diff --git a/internal/service/encryptionatrest/resource_migration_test.go b/internal/service/encryptionatrest/resource_migration_test.go index 3ed1ff903f..2ee5589b2c 100644 --- a/internal/service/encryptionatrest/resource_migration_test.go +++ b/internal/service/encryptionatrest/resource_migration_test.go @@ -6,7 +6,7 @@ import ( "strconv" "testing" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/plancheck" diff --git a/internal/service/encryptionatrest/resource_test.go b/internal/service/encryptionatrest/resource_test.go index 119246763d..230479052f 100644 --- a/internal/service/encryptionatrest/resource_test.go +++ b/internal/service/encryptionatrest/resource_test.go @@ -7,8 +7,8 @@ import ( "os" "testing" - "go.mongodb.org/atlas-sdk/v20240805005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/mockadmin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" + "go.mongodb.org/atlas-sdk/v20241023001/mockadmin" "github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/internal/service/encryptionatrestprivateendpoint/model.go b/internal/service/encryptionatrestprivateendpoint/model.go index bdd99043e5..e3a0020db9 100644 --- a/internal/service/encryptionatrestprivateendpoint/model.go +++ b/internal/service/encryptionatrestprivateendpoint/model.go @@ -3,7 +3,7 @@ package encryptionatrestprivateendpoint import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewTFEarPrivateEndpoint(apiResp admin.EARPrivateEndpoint, projectID string) TFEarPrivateEndpointModel { diff --git a/internal/service/encryptionatrestprivateendpoint/model_test.go b/internal/service/encryptionatrestprivateendpoint/model_test.go index 2584919c12..d09c33c0cf 100644 --- a/internal/service/encryptionatrestprivateendpoint/model_test.go +++ b/internal/service/encryptionatrestprivateendpoint/model_test.go @@ -3,7 +3,7 @@ package encryptionatrestprivateendpoint_test import ( "testing" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework/types" "github.com/stretchr/testify/assert" diff --git a/internal/service/encryptionatrestprivateendpoint/plural_data_source.go b/internal/service/encryptionatrestprivateendpoint/plural_data_source.go index 2b7eb0fde3..800b8e094e 100644 --- a/internal/service/encryptionatrestprivateendpoint/plural_data_source.go +++ b/internal/service/encryptionatrestprivateendpoint/plural_data_source.go @@ -10,7 +10,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/dsschema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) var _ datasource.DataSource = &encryptionAtRestPrivateEndpointsDS{} diff --git a/internal/service/encryptionatrestprivateendpoint/resource.go b/internal/service/encryptionatrestprivateendpoint/resource.go index 8be2bae81a..a541641d07 100644 --- a/internal/service/encryptionatrestprivateendpoint/resource.go +++ b/internal/service/encryptionatrestprivateendpoint/resource.go @@ -6,7 +6,7 @@ import ( "net/http" "regexp" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/path" diff --git a/internal/service/encryptionatrestprivateendpoint/resource_test.go b/internal/service/encryptionatrestprivateendpoint/resource_test.go index 272ac732e3..95cddaaa45 100644 --- a/internal/service/encryptionatrestprivateendpoint/resource_test.go +++ b/internal/service/encryptionatrestprivateendpoint/resource_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/internal/service/encryptionatrestprivateendpoint/state_transition.go b/internal/service/encryptionatrestprivateendpoint/state_transition.go index 852f61135d..d9b4e0064a 100644 --- a/internal/service/encryptionatrestprivateendpoint/state_transition.go +++ b/internal/service/encryptionatrestprivateendpoint/state_transition.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/retrystrategy" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/encryptionatrestprivateendpoint/state_transition_test.go b/internal/service/encryptionatrestprivateendpoint/state_transition_test.go index 38f43532e3..2b662bdf56 100644 --- a/internal/service/encryptionatrestprivateendpoint/state_transition_test.go +++ b/internal/service/encryptionatrestprivateendpoint/state_transition_test.go @@ -13,8 +13,8 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/encryptionatrestprivateendpoint" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" - "go.mongodb.org/atlas-sdk/v20240805005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/mockadmin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" + "go.mongodb.org/atlas-sdk/v20241023001/mockadmin" ) type testCase struct { diff --git a/internal/service/federateddatabaseinstance/data_source_federated_database_instance_test.go b/internal/service/federateddatabaseinstance/data_source_federated_database_instance_test.go index 0d83e30ca4..a7389e00f7 100644 --- a/internal/service/federateddatabaseinstance/data_source_federated_database_instance_test.go +++ b/internal/service/federateddatabaseinstance/data_source_federated_database_instance_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" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func TestAccFederatedDatabaseInstanceDS_s3Bucket(t *testing.T) { diff --git a/internal/service/federateddatabaseinstance/data_source_federated_database_instances.go b/internal/service/federateddatabaseinstance/data_source_federated_database_instances.go index 161352fd86..525a5c92d6 100644 --- a/internal/service/federateddatabaseinstance/data_source_federated_database_instances.go +++ b/internal/service/federateddatabaseinstance/data_source_federated_database_instances.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" diff --git a/internal/service/federateddatabaseinstance/resource_federated_database_instance.go b/internal/service/federateddatabaseinstance/resource_federated_database_instance.go index 4e1cf879c4..9177120010 100644 --- a/internal/service/federateddatabaseinstance/resource_federated_database_instance.go +++ b/internal/service/federateddatabaseinstance/resource_federated_database_instance.go @@ -7,7 +7,7 @@ import ( "net/http" "strings" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" diff --git a/internal/service/federatedquerylimit/data_source_federated_query_limits.go b/internal/service/federatedquerylimit/data_source_federated_query_limits.go index d612180bac..bf93fb705b 100644 --- a/internal/service/federatedquerylimit/data_source_federated_query_limits.go +++ b/internal/service/federatedquerylimit/data_source_federated_query_limits.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/federatedquerylimit/resource_federated_query_limit.go b/internal/service/federatedquerylimit/resource_federated_query_limit.go index 1703c15d30..2460a15a94 100644 --- a/internal/service/federatedquerylimit/resource_federated_query_limit.go +++ b/internal/service/federatedquerylimit/resource_federated_query_limit.go @@ -11,7 +11,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/federatedsettingsidentityprovider/data_source_federated_settings_identity_providers.go b/internal/service/federatedsettingsidentityprovider/data_source_federated_settings_identity_providers.go index b0d2f9e621..254e9d33d1 100644 --- a/internal/service/federatedsettingsidentityprovider/data_source_federated_settings_identity_providers.go +++ b/internal/service/federatedsettingsidentityprovider/data_source_federated_settings_identity_providers.go @@ -5,7 +5,7 @@ import ( "errors" "fmt" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" diff --git a/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider.go b/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider.go index f8305bf278..27bcfbd71e 100644 --- a/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider.go +++ b/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider.go @@ -4,7 +4,7 @@ import ( "sort" "strings" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" diff --git a/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider_test.go b/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider_test.go index 3f84ed3808..ab5bac54ff 100644 --- a/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider_test.go +++ b/internal/service/federatedsettingsidentityprovider/model_federated_settings_identity_provider_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/stretchr/testify/assert" diff --git a/internal/service/federatedsettingsorgconfig/data_source_federated_settings.go b/internal/service/federatedsettingsorgconfig/data_source_federated_settings.go index a618aa8762..7222e6bf4c 100644 --- a/internal/service/federatedsettingsorgconfig/data_source_federated_settings.go +++ b/internal/service/federatedsettingsorgconfig/data_source_federated_settings.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func DataSourceSettings() *schema.Resource { diff --git a/internal/service/federatedsettingsorgconfig/data_source_federated_settings_connected_orgs.go b/internal/service/federatedsettingsorgconfig/data_source_federated_settings_connected_orgs.go index a8149e4071..f4433bcc4a 100644 --- a/internal/service/federatedsettingsorgconfig/data_source_federated_settings_connected_orgs.go +++ b/internal/service/federatedsettingsorgconfig/data_source_federated_settings_connected_orgs.go @@ -8,7 +8,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/federatedsettingsorgconfig/model_federated_settings_connected_orgs.go b/internal/service/federatedsettingsorgconfig/model_federated_settings_connected_orgs.go index cbd0a4b8e8..2fad36eee4 100644 --- a/internal/service/federatedsettingsorgconfig/model_federated_settings_connected_orgs.go +++ b/internal/service/federatedsettingsorgconfig/model_federated_settings_connected_orgs.go @@ -4,7 +4,7 @@ import ( "sort" "strings" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) type roleMappingsByGroupName []admin.AuthFederationRoleMapping diff --git a/internal/service/federatedsettingsorgrolemapping/data_source_federated_settings_org_role_mappings.go b/internal/service/federatedsettingsorgrolemapping/data_source_federated_settings_org_role_mappings.go index 83c2c83a7e..547aee5c5f 100644 --- a/internal/service/federatedsettingsorgrolemapping/data_source_federated_settings_org_role_mappings.go +++ b/internal/service/federatedsettingsorgrolemapping/data_source_federated_settings_org_role_mappings.go @@ -8,7 +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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/federatedsettingsorgrolemapping/model_federated_settings_org_role_mapping.go b/internal/service/federatedsettingsorgrolemapping/model_federated_settings_org_role_mapping.go index 9d354d1752..85a78829d4 100644 --- a/internal/service/federatedsettingsorgrolemapping/model_federated_settings_org_role_mapping.go +++ b/internal/service/federatedsettingsorgrolemapping/model_federated_settings_org_role_mapping.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) type mRoleAssignment []admin.RoleAssignment diff --git a/internal/service/federatedsettingsorgrolemapping/resource_federated_settings_org_role_mapping.go b/internal/service/federatedsettingsorgrolemapping/resource_federated_settings_org_role_mapping.go index f46ce908e9..6b692d3421 100644 --- a/internal/service/federatedsettingsorgrolemapping/resource_federated_settings_org_role_mapping.go +++ b/internal/service/federatedsettingsorgrolemapping/resource_federated_settings_org_role_mapping.go @@ -11,7 +11,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func Resource() *schema.Resource { diff --git a/internal/service/globalclusterconfig/resource_global_cluster_config.go b/internal/service/globalclusterconfig/resource_global_cluster_config.go index 9b09fb87b3..096696e17c 100644 --- a/internal/service/globalclusterconfig/resource_global_cluster_config.go +++ b/internal/service/globalclusterconfig/resource_global_cluster_config.go @@ -14,7 +14,7 @@ import ( "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/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/ldapconfiguration/resource_ldap_configuration.go b/internal/service/ldapconfiguration/resource_ldap_configuration.go index 59f545b4b4..f0d7f719db 100644 --- a/internal/service/ldapconfiguration/resource_ldap_configuration.go +++ b/internal/service/ldapconfiguration/resource_ldap_configuration.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/ldapverify/resource_ldap_verify.go b/internal/service/ldapverify/resource_ldap_verify.go index 0771a6f4bd..b79359ad33 100644 --- a/internal/service/ldapverify/resource_ldap_verify.go +++ b/internal/service/ldapverify/resource_ldap_verify.go @@ -13,7 +13,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/maintenancewindow/resource_maintenance_window.go b/internal/service/maintenancewindow/resource_maintenance_window.go index 6072acba29..ba1e3a20ed 100644 --- a/internal/service/maintenancewindow/resource_maintenance_window.go +++ b/internal/service/maintenancewindow/resource_maintenance_window.go @@ -10,7 +10,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/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/mongodbemployeeaccessgrant/model.go b/internal/service/mongodbemployeeaccessgrant/model.go index 8faaa5e45b..aaef58b9d5 100644 --- a/internal/service/mongodbemployeeaccessgrant/model.go +++ b/internal/service/mongodbemployeeaccessgrant/model.go @@ -5,7 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewTFModel(projectID, clusterName string, apiResp *admin.EmployeeAccessGrant) *TFModel { diff --git a/internal/service/mongodbemployeeaccessgrant/model_test.go b/internal/service/mongodbemployeeaccessgrant/model_test.go index 3ca097e287..0f43405783 100644 --- a/internal/service/mongodbemployeeaccessgrant/model_test.go +++ b/internal/service/mongodbemployeeaccessgrant/model_test.go @@ -7,7 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/mongodbemployeeaccessgrant" "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func TestNewTFModel(t *testing.T) { diff --git a/internal/service/networkcontainer/data_source_network_containers.go b/internal/service/networkcontainer/data_source_network_containers.go index 5a9161d45f..e8e74b7812 100644 --- a/internal/service/networkcontainer/data_source_network_containers.go +++ b/internal/service/networkcontainer/data_source_network_containers.go @@ -8,7 +8,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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/networkcontainer/resource_network_container.go b/internal/service/networkcontainer/resource_network_container.go index 6eb031a30c..0dfb4f7c06 100644 --- a/internal/service/networkcontainer/resource_network_container.go +++ b/internal/service/networkcontainer/resource_network_container.go @@ -17,7 +17,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/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/networkpeering/data_source_network_peering.go b/internal/service/networkpeering/data_source_network_peering.go index 06f40b7c3c..1cf43f9185 100644 --- a/internal/service/networkpeering/data_source_network_peering.go +++ b/internal/service/networkpeering/data_source_network_peering.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func DataSource() *schema.Resource { diff --git a/internal/service/networkpeering/data_source_network_peerings.go b/internal/service/networkpeering/data_source_network_peerings.go index c8f48e4040..05a972a44b 100644 --- a/internal/service/networkpeering/data_source_network_peerings.go +++ b/internal/service/networkpeering/data_source_network_peerings.go @@ -9,7 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/networkpeering/resource_network_peering.go b/internal/service/networkpeering/resource_network_peering.go index 5b80ddac40..1accba6dc4 100644 --- a/internal/service/networkpeering/resource_network_peering.go +++ b/internal/service/networkpeering/resource_network_peering.go @@ -16,7 +16,7 @@ import ( "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/networkcontainer" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/onlinearchive/resource_online_archive.go b/internal/service/onlinearchive/resource_online_archive.go index 1bc14ac71c..8bb1af3c37 100644 --- a/internal/service/onlinearchive/resource_online_archive.go +++ b/internal/service/onlinearchive/resource_online_archive.go @@ -15,7 +15,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" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/organization/data_source_organizations.go b/internal/service/organization/data_source_organizations.go index 43430e72d7..dc1797e331 100644 --- a/internal/service/organization/data_source_organizations.go +++ b/internal/service/organization/data_source_organizations.go @@ -5,7 +5,7 @@ import ( "fmt" "log" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" diff --git a/internal/service/organization/resource_organization.go b/internal/service/organization/resource_organization.go index 59f9650de9..5af532b538 100644 --- a/internal/service/organization/resource_organization.go +++ b/internal/service/organization/resource_organization.go @@ -7,7 +7,7 @@ import ( "net/http" "strings" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" diff --git a/internal/service/organization/resource_organization_test.go b/internal/service/organization/resource_organization_test.go index b2b0e8baae..803bed8123 100644 --- a/internal/service/organization/resource_organization_test.go +++ b/internal/service/organization/resource_organization_test.go @@ -7,7 +7,7 @@ import ( "regexp" "testing" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/internal/service/orginvitation/resource_org_invitation.go b/internal/service/orginvitation/resource_org_invitation.go index 318ffaf976..5b6967bec5 100644 --- a/internal/service/orginvitation/resource_org_invitation.go +++ b/internal/service/orginvitation/resource_org_invitation.go @@ -10,7 +10,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func Resource() *schema.Resource { diff --git a/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode.go b/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode.go index eece8288cd..cfa1a286ec 100644 --- a/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode.go +++ b/internal/service/privateendpointregionalmode/resource_private_endpoint_regional_mode.go @@ -12,7 +12,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/advancedcluster" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) type permCtxKey string diff --git a/internal/service/privatelinkendpoint/resource_privatelink_endpoint.go b/internal/service/privatelinkendpoint/resource_privatelink_endpoint.go index cd556267df..aa035f9d7f 100644 --- a/internal/service/privatelinkendpoint/resource_privatelink_endpoint.go +++ b/internal/service/privatelinkendpoint/resource_privatelink_endpoint.go @@ -15,7 +15,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" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless.go b/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless.go index ba78d00d19..50552018bb 100644 --- a/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless.go +++ b/internal/service/privatelinkendpointserverless/resource_privatelink_endpoint_serverless.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" diff --git a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go index ab1101564d..09e02e7fc6 100644 --- a/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go +++ b/internal/service/privatelinkendpointservice/resource_privatelink_endpoint_service.go @@ -16,7 +16,7 @@ import ( "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" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/privatelinkendpointservicedatafederationonlinearchive/data_source_privatelink_endpoint_service_data_federation_online_archives.go b/internal/service/privatelinkendpointservicedatafederationonlinearchive/data_source_privatelink_endpoint_service_data_federation_online_archives.go index 6a48a38fba..833dd3f369 100644 --- a/internal/service/privatelinkendpointservicedatafederationonlinearchive/data_source_privatelink_endpoint_service_data_federation_online_archives.go +++ b/internal/service/privatelinkendpointservicedatafederationonlinearchive/data_source_privatelink_endpoint_service_data_federation_online_archives.go @@ -9,7 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/datalakepipeline" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const errorPrivateEndpointServiceDataFederationOnlineArchiveList = "error reading Private Endpoings for projectId %s: %s" diff --git a/internal/service/privatelinkendpointservicedatafederationonlinearchive/resource_privatelink_endpoint_service_data_federation_online_archive.go b/internal/service/privatelinkendpointservicedatafederationonlinearchive/resource_privatelink_endpoint_service_data_federation_online_archive.go index 0785ddc6e5..21308b50c2 100644 --- a/internal/service/privatelinkendpointservicedatafederationonlinearchive/resource_privatelink_endpoint_service_data_federation_online_archive.go +++ b/internal/service/privatelinkendpointservicedatafederationonlinearchive/resource_privatelink_endpoint_service_data_federation_online_archive.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" diff --git a/internal/service/privatelinkendpointserviceserverless/data_source_privatelink_endpoints_service_serverless.go b/internal/service/privatelinkendpointserviceserverless/data_source_privatelink_endpoints_service_serverless.go index 1257ffc302..62d6e1c2c1 100644 --- a/internal/service/privatelinkendpointserviceserverless/data_source_privatelink_endpoints_service_serverless.go +++ b/internal/service/privatelinkendpointserviceserverless/data_source_privatelink_endpoints_service_serverless.go @@ -7,7 +7,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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless.go b/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless.go index 7127453fd9..07727479c9 100644 --- a/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless.go +++ b/internal/service/privatelinkendpointserviceserverless/resource_privatelink_endpoint_service_serverless.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" diff --git a/internal/service/project/data_source_project.go b/internal/service/project/data_source_project.go index 92c58af777..b6d3ab9a09 100644 --- a/internal/service/project/data_source_project.go +++ b/internal/service/project/data_source_project.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/datasource" diff --git a/internal/service/project/data_source_projects.go b/internal/service/project/data_source_projects.go index dd52e38449..8de0804c0f 100644 --- a/internal/service/project/data_source_projects.go +++ b/internal/service/project/data_source_projects.go @@ -12,7 +12,7 @@ import ( "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/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const projectsDataSourceName = "projects" diff --git a/internal/service/project/model_project.go b/internal/service/project/model_project.go index 4d44a6e5dc..692efa6e95 100644 --- a/internal/service/project/model_project.go +++ b/internal/service/project/model_project.go @@ -3,7 +3,7 @@ package project import ( "context" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework/attr" "github.com/hashicorp/terraform-plugin-framework/diag" diff --git a/internal/service/project/model_project_test.go b/internal/service/project/model_project_test.go index bbce058b87..a8b74112a1 100644 --- a/internal/service/project/model_project_test.go +++ b/internal/service/project/model_project_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework/attr" "github.com/hashicorp/terraform-plugin-framework/types" diff --git a/internal/service/project/resource_project.go b/internal/service/project/resource_project.go index 21ef55dcfe..5c51101ebe 100644 --- a/internal/service/project/resource_project.go +++ b/internal/service/project/resource_project.go @@ -10,7 +10,7 @@ import ( "sort" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework/attr" "github.com/hashicorp/terraform-plugin-framework/diag" @@ -679,7 +679,7 @@ func SetSlowOperationThresholding(ctx context.Context, performanceAdvisorAPI adm func ReadIsSlowMsThresholdingEnabled(ctx context.Context, api admin.PerformanceAdvisorApi, projectID string, warnings *diag.Diagnostics) (bool, error) { response, err := api.GetManagedSlowMs(ctx, projectID).Execute() if err != nil { - if apiError, ok := admin.AsError(err); ok && *apiError.ErrorCode == "USER_UNAUTHORIZED" { + if apiError, ok := admin.AsError(err); ok && apiError.ErrorCode == "USER_UNAUTHORIZED" { if warnings != nil { warnings.AddWarning("user does not have permission to read is_slow_operation_thresholding_enabled. Please read our documentation for more information.", fmt.Sprintf(ErrorProjectRead, projectID, err.Error())) } @@ -792,8 +792,7 @@ func UpdateProjectTeams(ctx context.Context, teamsAPI admin.TeamsApi, projectSta teamID := team.TeamID.ValueString() _, err := teamsAPI.RemoveProjectTeam(ctx, projectID, teamID).Execute() if err != nil { - apiError, ok := admin.AsError(err) - if ok && *apiError.ErrorCode != "USER_UNAUTHORIZED" { + if !admin.IsErrorCode(err, "USER_UNAUTHORIZED") { return fmt.Errorf("error removing team(%s) from the project(%s): %s", teamID, projectID, err) } log.Printf("[WARN] error removing team(%s) from the project(%s): %s", teamID, projectID, err) diff --git a/internal/service/project/resource_project_migration_test.go b/internal/service/project/resource_project_migration_test.go index 4c9c4c4dcd..80a836c68d 100644 --- a/internal/service/project/resource_project_migration_test.go +++ b/internal/service/project/resource_project_migration_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" diff --git a/internal/service/project/resource_project_test.go b/internal/service/project/resource_project_test.go index 73e9f3a270..dbb1ddaac5 100644 --- a/internal/service/project/resource_project_test.go +++ b/internal/service/project/resource_project_test.go @@ -12,8 +12,8 @@ import ( "strings" "testing" - "go.mongodb.org/atlas-sdk/v20240805005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/mockadmin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" + "go.mongodb.org/atlas-sdk/v20241023001/mockadmin" "github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-testing/helper/resource" diff --git a/internal/service/projectapikey/data_source_project_api_keys.go b/internal/service/projectapikey/data_source_project_api_keys.go index c0850baa2e..a408cffc7b 100644 --- a/internal/service/projectapikey/data_source_project_api_keys.go +++ b/internal/service/projectapikey/data_source_project_api_keys.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/projectapikey/model_project_api_key.go b/internal/service/projectapikey/model_project_api_key.go index 95db220ce8..6e3b0e143d 100644 --- a/internal/service/projectapikey/model_project_api_key.go +++ b/internal/service/projectapikey/model_project_api_key.go @@ -7,7 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func expandProjectAssignments(projectAssignments *schema.Set) map[string][]string { diff --git a/internal/service/projectapikey/resource_project_api_key.go b/internal/service/projectapikey/resource_project_api_key.go index 903c3540c1..7566b28857 100644 --- a/internal/service/projectapikey/resource_project_api_key.go +++ b/internal/service/projectapikey/resource_project_api_key.go @@ -10,7 +10,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func Resource() *schema.Resource { diff --git a/internal/service/projectinvitation/resource_project_invitation.go b/internal/service/projectinvitation/resource_project_invitation.go index bbe13e7d20..c01d8efa44 100644 --- a/internal/service/projectinvitation/resource_project_invitation.go +++ b/internal/service/projectinvitation/resource_project_invitation.go @@ -11,7 +11,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func Resource() *schema.Resource { diff --git a/internal/service/projectipaccesslist/model_project_ip_access_list.go b/internal/service/projectipaccesslist/model_project_ip_access_list.go index b2a5e8734b..e62b56e5a0 100644 --- a/internal/service/projectipaccesslist/model_project_ip_access_list.go +++ b/internal/service/projectipaccesslist/model_project_ip_access_list.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/types" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewMongoDBProjectIPAccessList(projectIPAccessListModel *TfProjectIPAccessListModel) *[]admin.NetworkPermissionEntry { diff --git a/internal/service/projectipaccesslist/model_project_ip_access_list_test.go b/internal/service/projectipaccesslist/model_project_ip_access_list_test.go index 5bc9dbe07b..f32d2e1122 100644 --- a/internal/service/projectipaccesslist/model_project_ip_access_list_test.go +++ b/internal/service/projectipaccesslist/model_project_ip_access_list_test.go @@ -9,7 +9,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/projectipaccesslist" "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) var ( diff --git a/internal/service/projectipaccesslist/resource_project_ip_access_list.go b/internal/service/projectipaccesslist/resource_project_ip_access_list.go index 64898643ad..0304dd88fe 100644 --- a/internal/service/projectipaccesslist/resource_project_ip_access_list.go +++ b/internal/service/projectipaccesslist/resource_project_ip_access_list.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" diff --git a/internal/service/projectipaddresses/model.go b/internal/service/projectipaddresses/model.go index 883b31b97a..f340f49494 100644 --- a/internal/service/projectipaddresses/model.go +++ b/internal/service/projectipaddresses/model.go @@ -5,7 +5,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/types" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewTFProjectIPAddresses(ctx context.Context, ipAddresses *admin.GroupIPAddresses) (*TFProjectIpAddressesModel, diag.Diagnostics) { diff --git a/internal/service/projectipaddresses/model_test.go b/internal/service/projectipaddresses/model_test.go index 7c272352ee..8a2d33095a 100644 --- a/internal/service/projectipaddresses/model_test.go +++ b/internal/service/projectipaddresses/model_test.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/projectipaddresses" "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/pushbasedlogexport/model.go b/internal/service/pushbasedlogexport/model.go index 6ec07b302f..921fbcd208 100644 --- a/internal/service/pushbasedlogexport/model.go +++ b/internal/service/pushbasedlogexport/model.go @@ -3,7 +3,7 @@ package pushbasedlogexport import ( "context" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts" "github.com/hashicorp/terraform-plugin-framework/diag" diff --git a/internal/service/pushbasedlogexport/model_test.go b/internal/service/pushbasedlogexport/model_test.go index 257f08c90b..c9d2c490ec 100644 --- a/internal/service/pushbasedlogexport/model_test.go +++ b/internal/service/pushbasedlogexport/model_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts" "github.com/hashicorp/terraform-plugin-framework/types" diff --git a/internal/service/pushbasedlogexport/resource.go b/internal/service/pushbasedlogexport/resource.go index 04a02aca78..95ab7646eb 100644 --- a/internal/service/pushbasedlogexport/resource.go +++ b/internal/service/pushbasedlogexport/resource.go @@ -7,7 +7,7 @@ import ( "slices" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" diff --git a/internal/service/pushbasedlogexport/state_transition.go b/internal/service/pushbasedlogexport/state_transition.go index 187c4c5c01..5f5c10fc07 100644 --- a/internal/service/pushbasedlogexport/state_transition.go +++ b/internal/service/pushbasedlogexport/state_transition.go @@ -5,7 +5,7 @@ import ( "errors" "fmt" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" diff --git a/internal/service/pushbasedlogexport/state_transition_test.go b/internal/service/pushbasedlogexport/state_transition_test.go index d0b183b81d..4f677ab564 100644 --- a/internal/service/pushbasedlogexport/state_transition_test.go +++ b/internal/service/pushbasedlogexport/state_transition_test.go @@ -7,8 +7,8 @@ import ( "testing" "time" - "go.mongodb.org/atlas-sdk/v20240805005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/mockadmin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" + "go.mongodb.org/atlas-sdk/v20241023001/mockadmin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" diff --git a/internal/service/resourcepolicy/model.go b/internal/service/resourcepolicy/model.go index bf514496ca..1d173dca95 100644 --- a/internal/service/resourcepolicy/model.go +++ b/internal/service/resourcepolicy/model.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/types" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewTFModel(ctx context.Context, input *admin.ApiAtlasResourcePolicy) (*TFModel, diag.Diagnostics) { diff --git a/internal/service/resourcepolicy/model_test.go b/internal/service/resourcepolicy/model_test.go index 6ca44af36c..1e06260ff1 100644 --- a/internal/service/resourcepolicy/model_test.go +++ b/internal/service/resourcepolicy/model_test.go @@ -11,7 +11,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/resourcepolicy" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/unit" "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) var ( diff --git a/internal/service/resourcepolicy/resource.go b/internal/service/resourcepolicy/resource.go index 5d24380045..dbcb43fe82 100644 --- a/internal/service/resourcepolicy/resource.go +++ b/internal/service/resourcepolicy/resource.go @@ -11,7 +11,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) var _ resource.ResourceWithConfigure = &resourcePolicyRS{} diff --git a/internal/service/searchdeployment/model_search_deployment.go b/internal/service/searchdeployment/model_search_deployment.go index d8ce3d143c..8afe742b88 100644 --- a/internal/service/searchdeployment/model_search_deployment.go +++ b/internal/service/searchdeployment/model_search_deployment.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts" "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/types" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewSearchDeploymentReq(ctx context.Context, searchDeploymentPlan *TFSearchDeploymentRSModel) admin.ApiSearchDeploymentRequest { diff --git a/internal/service/searchdeployment/model_search_deployment_test.go b/internal/service/searchdeployment/model_search_deployment_test.go index a51ec2b08f..f0a7c83c40 100644 --- a/internal/service/searchdeployment/model_search_deployment_test.go +++ b/internal/service/searchdeployment/model_search_deployment_test.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-framework/types/basetypes" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/searchdeployment" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) type sdkToTFModelTestCase struct { diff --git a/internal/service/searchdeployment/state_transition_search_deployment.go b/internal/service/searchdeployment/state_transition_search_deployment.go index 2a48a0b809..85f601ecd7 100644 --- a/internal/service/searchdeployment/state_transition_search_deployment.go +++ b/internal/service/searchdeployment/state_transition_search_deployment.go @@ -10,7 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/retrystrategy" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const SearchDeploymentDoesNotExistsError = "ATLAS_SEARCH_DEPLOYMENT_DOES_NOT_EXIST" diff --git a/internal/service/searchdeployment/state_transition_search_deployment_test.go b/internal/service/searchdeployment/state_transition_search_deployment_test.go index 6533d9fae7..1e90ab1dc7 100644 --- a/internal/service/searchdeployment/state_transition_search_deployment_test.go +++ b/internal/service/searchdeployment/state_transition_search_deployment_test.go @@ -12,8 +12,8 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/searchdeployment" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" - "go.mongodb.org/atlas-sdk/v20240805005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/mockadmin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" + "go.mongodb.org/atlas-sdk/v20241023001/mockadmin" ) var ( diff --git a/internal/service/searchindex/data_source_search_indexes.go b/internal/service/searchindex/data_source_search_indexes.go index bdf4c4ea86..31db560cf8 100644 --- a/internal/service/searchindex/data_source_search_indexes.go +++ b/internal/service/searchindex/data_source_search_indexes.go @@ -8,7 +8,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/searchindex/model_search_index.go b/internal/service/searchindex/model_search_index.go index d5a3bfb50a..65b52954b1 100644 --- a/internal/service/searchindex/model_search_index.go +++ b/internal/service/searchindex/model_search_index.go @@ -11,7 +11,7 @@ import ( "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/common/schemafunc" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func flattenSearchIndexSynonyms(synonyms []admin.SearchSynonymMappingDefinition) []map[string]any { diff --git a/internal/service/searchindex/resource_search_index.go b/internal/service/searchindex/resource_search_index.go index 86be0fdf8f..eb006b907f 100644 --- a/internal/service/searchindex/resource_search_index.go +++ b/internal/service/searchindex/resource_search_index.go @@ -13,7 +13,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/serverlessinstance/data_source_serverless_instances.go b/internal/service/serverlessinstance/data_source_serverless_instances.go index 469281324f..c9eea22533 100644 --- a/internal/service/serverlessinstance/data_source_serverless_instances.go +++ b/internal/service/serverlessinstance/data_source_serverless_instances.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/serverlessinstance/resource_serverless_instance.go b/internal/service/serverlessinstance/resource_serverless_instance.go index 1ca8ce6f82..53badc028e 100644 --- a/internal/service/serverlessinstance/resource_serverless_instance.go +++ b/internal/service/serverlessinstance/resource_serverless_instance.go @@ -15,7 +15,7 @@ import ( "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" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/serverlessinstance/resource_serverless_instance_test.go b/internal/service/serverlessinstance/resource_serverless_instance_test.go index 5f20bdbbbf..cf03545b5b 100644 --- a/internal/service/serverlessinstance/resource_serverless_instance_test.go +++ b/internal/service/serverlessinstance/resource_serverless_instance_test.go @@ -9,7 +9,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" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/sharedtier/data_source_cloud_shared_tier_restore_jobs.go b/internal/service/sharedtier/data_source_cloud_shared_tier_restore_jobs.go index a6b9684dab..ea63172a29 100644 --- a/internal/service/sharedtier/data_source_cloud_shared_tier_restore_jobs.go +++ b/internal/service/sharedtier/data_source_cloud_shared_tier_restore_jobs.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" diff --git a/internal/service/sharedtier/data_source_shared_tier_snapshots.go b/internal/service/sharedtier/data_source_shared_tier_snapshots.go index 7a8b34c044..7d12c216fc 100644 --- a/internal/service/sharedtier/data_source_shared_tier_snapshots.go +++ b/internal/service/sharedtier/data_source_shared_tier_snapshots.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" diff --git a/internal/service/streamconnection/data_source_stream_connections.go b/internal/service/streamconnection/data_source_stream_connections.go index 923c23f66b..051f8b96f2 100644 --- a/internal/service/streamconnection/data_source_stream_connections.go +++ b/internal/service/streamconnection/data_source_stream_connections.go @@ -10,7 +10,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/dsschema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) var _ datasource.DataSource = &streamConnectionsDS{} diff --git a/internal/service/streamconnection/data_source_stream_connections_test.go b/internal/service/streamconnection/data_source_stream_connections_test.go index 2c1c9cc1f7..93e364b757 100644 --- a/internal/service/streamconnection/data_source_stream_connections_test.go +++ b/internal/service/streamconnection/data_source_stream_connections_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func TestAccStreamDSStreamConnections_basic(t *testing.T) { diff --git a/internal/service/streamconnection/model_stream_connection.go b/internal/service/streamconnection/model_stream_connection.go index c2ed1f3657..c7e17222a9 100644 --- a/internal/service/streamconnection/model_stream_connection.go +++ b/internal/service/streamconnection/model_stream_connection.go @@ -9,7 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types/basetypes" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewStreamConnectionReq(ctx context.Context, plan *TFStreamConnectionModel) (*admin.StreamsConnection, diag.Diagnostics) { diff --git a/internal/service/streamconnection/model_stream_connection_test.go b/internal/service/streamconnection/model_stream_connection_test.go index c064eed634..4c27cd0d8c 100644 --- a/internal/service/streamconnection/model_stream_connection_test.go +++ b/internal/service/streamconnection/model_stream_connection_test.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/streamconnection" "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/streaminstance/data_source_stream_instances.go b/internal/service/streaminstance/data_source_stream_instances.go index fe36a065bd..4a85e08a0a 100644 --- a/internal/service/streaminstance/data_source_stream_instances.go +++ b/internal/service/streaminstance/data_source_stream_instances.go @@ -10,7 +10,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/dsschema" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) var _ datasource.DataSource = &streamInstancesDS{} diff --git a/internal/service/streaminstance/data_source_stream_instances_test.go b/internal/service/streaminstance/data_source_stream_instances_test.go index 8cefdaff7f..febcd531f8 100644 --- a/internal/service/streaminstance/data_source_stream_instances_test.go +++ b/internal/service/streaminstance/data_source_stream_instances_test.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func TestAccStreamDSStreamInstances_basic(t *testing.T) { diff --git a/internal/service/streaminstance/model_stream_instance.go b/internal/service/streaminstance/model_stream_instance.go index d331b6d42c..cedf37d44d 100644 --- a/internal/service/streaminstance/model_stream_instance.go +++ b/internal/service/streaminstance/model_stream_instance.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types/basetypes" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewStreamInstanceCreateReq(ctx context.Context, plan *TFStreamInstanceModel) (*admin.StreamsTenant, diag.Diagnostics) { diff --git a/internal/service/streaminstance/model_stream_instance_test.go b/internal/service/streaminstance/model_stream_instance_test.go index 82e00d784c..a80fc9ab1e 100644 --- a/internal/service/streaminstance/model_stream_instance_test.go +++ b/internal/service/streaminstance/model_stream_instance_test.go @@ -7,7 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/streaminstance" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/streamprocessor/model.go b/internal/service/streamprocessor/model.go index 2fa2ede5ba..0118d06297 100644 --- a/internal/service/streamprocessor/model.go +++ b/internal/service/streamprocessor/model.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-framework/types/basetypes" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/fwtypes" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func NewStreamProcessorReq(ctx context.Context, plan *TFStreamProcessorRSModel) (*admin.StreamsProcessor, diag.Diagnostics) { diff --git a/internal/service/streamprocessor/model_test.go b/internal/service/streamprocessor/model_test.go index e87d65a699..58975287ac 100644 --- a/internal/service/streamprocessor/model_test.go +++ b/internal/service/streamprocessor/model_test.go @@ -11,7 +11,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/schemafunc" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/streamprocessor" "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) var ( diff --git a/internal/service/streamprocessor/plural_data_source.go b/internal/service/streamprocessor/plural_data_source.go index 5235577106..8193a70c67 100644 --- a/internal/service/streamprocessor/plural_data_source.go +++ b/internal/service/streamprocessor/plural_data_source.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/dsschema" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func (d *streamProcessorsDS) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { diff --git a/internal/service/streamprocessor/resource.go b/internal/service/streamprocessor/resource.go index b0d8a85f70..43e4cf6bef 100644 --- a/internal/service/streamprocessor/resource.go +++ b/internal/service/streamprocessor/resource.go @@ -11,7 +11,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const StreamProcessorName = "stream_processor" diff --git a/internal/service/streamprocessor/state_transition.go b/internal/service/streamprocessor/state_transition.go index 0d689c724b..00e307340e 100644 --- a/internal/service/streamprocessor/state_transition.go +++ b/internal/service/streamprocessor/state_transition.go @@ -8,7 +8,7 @@ import ( "time" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/streamprocessor/state_transition_test.go b/internal/service/streamprocessor/state_transition_test.go index ec512d9ade..8c59bbfad6 100644 --- a/internal/service/streamprocessor/state_transition_test.go +++ b/internal/service/streamprocessor/state_transition_test.go @@ -6,8 +6,8 @@ import ( "net/http" "testing" - "go.mongodb.org/atlas-sdk/v20240805005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/mockadmin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" + "go.mongodb.org/atlas-sdk/v20241023001/mockadmin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" diff --git a/internal/service/team/data_source_team.go b/internal/service/team/data_source_team.go index 1932ffdfbb..89dd699d50 100644 --- a/internal/service/team/data_source_team.go +++ b/internal/service/team/data_source_team.go @@ -11,7 +11,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func DataSource() *schema.Resource { diff --git a/internal/service/team/resource_team.go b/internal/service/team/resource_team.go index 58a65f0240..ce28f836b4 100644 --- a/internal/service/team/resource_team.go +++ b/internal/service/team/resource_team.go @@ -15,7 +15,7 @@ import ( "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/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/service/team/update_user.go b/internal/service/team/update_user.go index 651e36a6ac..090363faa7 100644 --- a/internal/service/team/update_user.go +++ b/internal/service/team/update_user.go @@ -3,7 +3,7 @@ package team import ( "context" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func UpdateTeamUsers(teamsAPI admin.TeamsApi, usersAPI admin.MongoDBCloudUsersApi, existingTeamUsers *admin.PaginatedApiAppUser, newUsernames []string, orgID, teamID string) error { diff --git a/internal/service/team/update_user_test.go b/internal/service/team/update_user_test.go index f70a81cb30..236fc7b8c2 100644 --- a/internal/service/team/update_user_test.go +++ b/internal/service/team/update_user_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" - "go.mongodb.org/atlas-sdk/v20240805005/admin" - "go.mongodb.org/atlas-sdk/v20240805005/mockadmin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" + "go.mongodb.org/atlas-sdk/v20241023001/mockadmin" ) func TestGetChangesForTeamUsers(t *testing.T) { diff --git a/internal/service/thirdpartyintegration/data_source_third_party_integrations.go b/internal/service/thirdpartyintegration/data_source_third_party_integrations.go index fa7514f8d1..64843d08e1 100644 --- a/internal/service/thirdpartyintegration/data_source_third_party_integrations.go +++ b/internal/service/thirdpartyintegration/data_source_third_party_integrations.go @@ -9,7 +9,7 @@ import ( "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/config" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func PluralDataSource() *schema.Resource { diff --git a/internal/service/x509authenticationdatabaseuser/resource_x509_authentication_database_user.go b/internal/service/x509authenticationdatabaseuser/resource_x509_authentication_database_user.go index e3a6c119c1..0c2575212c 100644 --- a/internal/service/x509authenticationdatabaseuser/resource_x509_authentication_database_user.go +++ b/internal/service/x509authenticationdatabaseuser/resource_x509_authentication_database_user.go @@ -11,7 +11,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/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/testutil/acc/advanced_cluster.go b/internal/testutil/acc/advanced_cluster.go index 750574527c..4b57826417 100644 --- a/internal/testutil/acc/advanced_cluster.go +++ b/internal/testutil/acc/advanced_cluster.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) var ( diff --git a/internal/testutil/acc/atlas.go b/internal/testutil/acc/atlas.go index f9036d68e2..e60837c0cf 100644 --- a/internal/testutil/acc/atlas.go +++ b/internal/testutil/acc/atlas.go @@ -10,7 +10,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/constant" "github.com/mongodb/terraform-provider-mongodbatlas/internal/service/advancedcluster" "github.com/stretchr/testify/require" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func createProject(tb testing.TB, name string) string { diff --git a/internal/testutil/acc/cluster.go b/internal/testutil/acc/cluster.go index 4ec77cd977..827e08049d 100644 --- a/internal/testutil/acc/cluster.go +++ b/internal/testutil/acc/cluster.go @@ -7,7 +7,7 @@ import ( "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/constant" "github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) // ClusterRequest contains configuration for a cluster where all fields are optional and AddDefaults is used for required fields. diff --git a/internal/testutil/acc/config_cluster.go b/internal/testutil/acc/config_cluster.go index 32f546730b..a63ff645d0 100644 --- a/internal/testutil/acc/config_cluster.go +++ b/internal/testutil/acc/config_cluster.go @@ -7,7 +7,7 @@ import ( "github.com/hashicorp/hcl/v2/hclwrite" "github.com/zclconf/go-cty/cty" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func ClusterDatasourceHcl(req *ClusterRequest) (configStr, clusterName, resourceName string, err error) { diff --git a/internal/testutil/acc/database_user.go b/internal/testutil/acc/database_user.go index 1f6dff9689..c7dc7644cb 100644 --- a/internal/testutil/acc/database_user.go +++ b/internal/testutil/acc/database_user.go @@ -3,7 +3,7 @@ package acc import ( "fmt" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func ConfigDatabaseUserBasic(projectID, username, roleName, keyLabel, valueLabel string) string { diff --git a/internal/testutil/acc/encryption_at_rest.go b/internal/testutil/acc/encryption_at_rest.go index 70502ad03a..99795d3153 100644 --- a/internal/testutil/acc/encryption_at_rest.go +++ b/internal/testutil/acc/encryption_at_rest.go @@ -5,7 +5,7 @@ import ( "fmt" "strconv" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/internal/testutil/acc/factory.go b/internal/testutil/acc/factory.go index 7a657ec470..6298e0ca8b 100644 --- a/internal/testutil/acc/factory.go +++ b/internal/testutil/acc/factory.go @@ -9,7 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-go/tfprotov6" "github.com/mongodb/terraform-provider-mongodbatlas/internal/config" "github.com/mongodb/terraform-provider-mongodbatlas/internal/provider" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) const ( diff --git a/internal/testutil/acc/project.go b/internal/testutil/acc/project.go index 059836cf64..7d461fbbfd 100644 --- a/internal/testutil/acc/project.go +++ b/internal/testutil/acc/project.go @@ -6,7 +6,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func CheckDestroyProject(s *terraform.State) error { diff --git a/internal/testutil/acc/serverless.go b/internal/testutil/acc/serverless.go index 9bb9260205..0821fa6f87 100644 --- a/internal/testutil/acc/serverless.go +++ b/internal/testutil/acc/serverless.go @@ -3,7 +3,7 @@ package acc import ( "fmt" - "go.mongodb.org/atlas-sdk/v20240805005/admin" + "go.mongodb.org/atlas-sdk/v20241023001/admin" ) func ConfigServerlessInstance(projectID, name string, ignoreConnectionStrings bool, autoIndexing *bool, tags []admin.ResourceTag) string { From 0c55bac73eec4abd2c6024e1d48aa49260b99981 Mon Sep 17 00:00:00 2001 From: svc-apix-Bot <142542575+svc-apix-Bot@users.noreply.github.com> Date: Wed, 30 Oct 2024 17:23:17 +0000 Subject: [PATCH 35/35] build(deps): bump go.mongodb.org/atlas-sdk (#2763) Co-authored-by: lantoli <430982+lantoli@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 270280b285..06ddbdf1ff 100644 --- a/go.mod +++ b/go.mod @@ -28,7 +28,7 @@ require ( go.mongodb.org/atlas v0.37.0 go.mongodb.org/atlas-sdk/v20240530005 v20240530005.0.0 go.mongodb.org/atlas-sdk/v20240805005 v20240805005.0.0 - go.mongodb.org/atlas-sdk/v20241023001 v20241023001.0.0 + go.mongodb.org/atlas-sdk/v20241023001 v20241023001.1.0 go.mongodb.org/realm v0.1.0 gopkg.in/yaml.v3 v3.0.1 ) diff --git a/go.sum b/go.sum index e0616c5f6e..88989d234c 100644 --- a/go.sum +++ b/go.sum @@ -806,8 +806,8 @@ go.mongodb.org/atlas-sdk/v20240530005 v20240530005.0.0 h1:d/gbYJ+obR0EM/3DZf7+ZM go.mongodb.org/atlas-sdk/v20240530005 v20240530005.0.0/go.mod h1:O47ZrMMfcWb31wznNIq2PQkkdoFoK0ea2GlmRqGJC2s= go.mongodb.org/atlas-sdk/v20240805005 v20240805005.0.0 h1:EGTT54tKbDbkhhK+jH5AqINFQbHdvaOSpI0oeI5Tl1s= go.mongodb.org/atlas-sdk/v20240805005 v20240805005.0.0/go.mod h1:UTNpAyiKm/7utu+Nl0FafgjgvS+ONNGEoxBT5g/40WM= -go.mongodb.org/atlas-sdk/v20241023001 v20241023001.0.0 h1:dkol8aWch89Jsx9aFKiRkP5LsV1ujPNt8IMK22y4fI0= -go.mongodb.org/atlas-sdk/v20241023001 v20241023001.0.0/go.mod h1:fIIKE86gLwxoK6QoMuJyEuPwbPmf0NbVmNNf70avUAE= +go.mongodb.org/atlas-sdk/v20241023001 v20241023001.1.0 h1:N/aqZ2+D7bAOZ5wTsA4yhToYq5Gj/Ys/H6YfGnF35ps= +go.mongodb.org/atlas-sdk/v20241023001 v20241023001.1.0/go.mod h1:fIIKE86gLwxoK6QoMuJyEuPwbPmf0NbVmNNf70avUAE= go.mongodb.org/realm v0.1.0 h1:zJiXyLaZrznQ+Pz947ziSrDKUep39DO4SfA0Fzx8M4M= go.mongodb.org/realm v0.1.0/go.mod h1:4Vj6iy+Puo1TDERcoh4XZ+pjtwbOzPpzqy3Cwe8ZmDM= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=