From e979c5782b4d8d0b1123e6e0cb7be8813e63dca5 Mon Sep 17 00:00:00 2001 From: neil-yechenwei Date: Thu, 18 Jan 2024 13:40:25 +0800 Subject: [PATCH 1/9] Upgrade CosmosDB Account API version from 2021-10-15 to 2023-04-15 --- internal/services/cosmos/common/cors_rule.go | 15 +- internal/services/cosmos/common/ip_rules.go | 18 +- .../services/cosmos/common/ip_rules_test.go | 16 +- .../cosmos/cosmosdb_account_data_source.go | 226 +-- .../cosmosdb_account_data_source_test.go | 14 +- .../cosmos/cosmosdb_account_resource.go | 1362 ++++++++--------- .../cosmos/cosmosdb_account_resource_test.go | 494 +++--- ...smosdb_cassandra_keyspace_resource_test.go | 10 +- ...cosmosdb_mongo_collection_resource_test.go | 8 +- .../cosmosdb_mongo_database_resource_test.go | 10 +- .../cosmosdb_sql_database_resource_test.go | 10 +- .../cosmos/cosmosdb_table_resource_test.go | 10 +- 12 files changed, 1069 insertions(+), 1124 deletions(-) diff --git a/internal/services/cosmos/common/cors_rule.go b/internal/services/cosmos/common/cors_rule.go index 4990434622be..30fb385bd3d2 100644 --- a/internal/services/cosmos/common/cors_rule.go +++ b/internal/services/cosmos/common/cors_rule.go @@ -6,7 +6,8 @@ package common import ( "strings" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/utils" @@ -80,11 +81,11 @@ func SchemaCorsRule() *pluginsdk.Schema { } } -func ExpandCosmosCorsRule(input []interface{}) *[]documentdb.CorsPolicy { +func ExpandCosmosCorsRule(input []interface{}) *[]cosmosdb.CorsPolicy { if len(input) == 0 || input[0] == nil { return nil } - corsRules := make([]documentdb.CorsPolicy, 0) + corsRules := make([]cosmosdb.CorsPolicy, 0) if len(input) == 0 { return &corsRules @@ -92,8 +93,8 @@ func ExpandCosmosCorsRule(input []interface{}) *[]documentdb.CorsPolicy { for _, attr := range input { corsRuleAttr := attr.(map[string]interface{}) - corsRule := documentdb.CorsPolicy{} - corsRule.AllowedOrigins = utils.String(strings.Join(*utils.ExpandStringSlice(corsRuleAttr["allowed_origins"].([]interface{})), ",")) + corsRule := cosmosdb.CorsPolicy{} + corsRule.AllowedOrigins = strings.Join(*utils.ExpandStringSlice(corsRuleAttr["allowed_origins"].([]interface{})), ",") corsRule.ExposedHeaders = utils.String(strings.Join(*utils.ExpandStringSlice(corsRuleAttr["exposed_headers"].([]interface{})), ",")) corsRule.AllowedHeaders = utils.String(strings.Join(*utils.ExpandStringSlice(corsRuleAttr["allowed_headers"].([]interface{})), ",")) corsRule.AllowedMethods = utils.String(strings.Join(*utils.ExpandStringSlice(corsRuleAttr["allowed_methods"].([]interface{})), ",")) @@ -108,7 +109,7 @@ func ExpandCosmosCorsRule(input []interface{}) *[]documentdb.CorsPolicy { return &corsRules } -func FlattenCosmosCorsRule(input *[]documentdb.CorsPolicy) []interface{} { +func FlattenCosmosCorsRule(input *[]cosmosdb.CorsPolicy) []interface{} { corsRules := make([]interface{}, 0) if input == nil || len(*input) == 0 { @@ -124,7 +125,7 @@ func FlattenCosmosCorsRule(input *[]documentdb.CorsPolicy) []interface{} { corsRules = append(corsRules, map[string]interface{}{ "allowed_headers": flattenCorsProperty(corsRule.AllowedHeaders), - "allowed_origins": flattenCorsProperty(corsRule.AllowedOrigins), + "allowed_origins": flattenCorsProperty(pointer.To(corsRule.AllowedOrigins)), "allowed_methods": flattenCorsProperty(corsRule.AllowedMethods), "exposed_headers": flattenCorsProperty(corsRule.ExposedHeaders), "max_age_in_seconds": maxAgeInSeconds, diff --git a/internal/services/cosmos/common/ip_rules.go b/internal/services/cosmos/common/ip_rules.go index 1d91f0566c32..6e65f87fb7ad 100644 --- a/internal/services/cosmos/common/ip_rules.go +++ b/internal/services/cosmos/common/ip_rules.go @@ -6,12 +6,12 @@ package common import ( "strings" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" "github.com/hashicorp/terraform-provider-azurerm/utils" ) // CosmosDBIpRulesToIpRangeFilterThreePointOh todo Remove for 4.0 -func CosmosDBIpRulesToIpRangeFilterThreePointOh(ipRules *[]documentdb.IPAddressOrRange) string { +func CosmosDBIpRulesToIpRangeFilterThreePointOh(ipRules *[]cosmosdb.IPAddressOrRange) string { ipRangeFilter := make([]string, 0) if ipRules != nil { for _, ipRule := range *ipRules { @@ -22,7 +22,7 @@ func CosmosDBIpRulesToIpRangeFilterThreePointOh(ipRules *[]documentdb.IPAddressO return strings.Join(ipRangeFilter, ",") } -func CosmosDBIpRulesToIpRangeFilter(ipRules *[]documentdb.IPAddressOrRange) []string { +func CosmosDBIpRulesToIpRangeFilter(ipRules *[]cosmosdb.IPAddressOrRange) []string { ipRangeFilter := make([]string, 0) if ipRules != nil { for _, ipRule := range *ipRules { @@ -33,10 +33,10 @@ func CosmosDBIpRulesToIpRangeFilter(ipRules *[]documentdb.IPAddressOrRange) []st return ipRangeFilter } -func CosmosDBIpRangeFilterToIpRules(ipRangeFilter []string) *[]documentdb.IPAddressOrRange { - ipRules := make([]documentdb.IPAddressOrRange, 0) +func CosmosDBIpRangeFilterToIpRules(ipRangeFilter []string) *[]cosmosdb.IPAddressOrRange { + ipRules := make([]cosmosdb.IPAddressOrRange, 0) for _, ipRange := range ipRangeFilter { - ipRules = append(ipRules, documentdb.IPAddressOrRange{ + ipRules = append(ipRules, cosmosdb.IPAddressOrRange{ IPAddressOrRange: utils.String(ipRange), }) } @@ -45,11 +45,11 @@ func CosmosDBIpRangeFilterToIpRules(ipRangeFilter []string) *[]documentdb.IPAddr } // CosmosDBIpRangeFilterToIpRulesThreePointOh todo Remove for 4.0 -func CosmosDBIpRangeFilterToIpRulesThreePointOh(ipRangeFilter string) *[]documentdb.IPAddressOrRange { - ipRules := make([]documentdb.IPAddressOrRange, 0) +func CosmosDBIpRangeFilterToIpRulesThreePointOh(ipRangeFilter string) *[]cosmosdb.IPAddressOrRange { + ipRules := make([]cosmosdb.IPAddressOrRange, 0) if len(ipRangeFilter) > 0 { for _, ipRange := range strings.Split(ipRangeFilter, ",") { - ipRules = append(ipRules, documentdb.IPAddressOrRange{ + ipRules = append(ipRules, cosmosdb.IPAddressOrRange{ IPAddressOrRange: utils.String(ipRange), }) } diff --git a/internal/services/cosmos/common/ip_rules_test.go b/internal/services/cosmos/common/ip_rules_test.go index 87e861c06e01..77834eacbd38 100644 --- a/internal/services/cosmos/common/ip_rules_test.go +++ b/internal/services/cosmos/common/ip_rules_test.go @@ -7,7 +7,7 @@ import ( "reflect" "testing" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" ) var ( @@ -18,7 +18,7 @@ var ( func TestCosmosDBIpRulesToIpRangeFilter(t *testing.T) { testData := []struct { Name string - Input *[]documentdb.IPAddressOrRange + Input *[]cosmosdb.IPAddressOrRange Expected []string }{ { @@ -28,14 +28,14 @@ func TestCosmosDBIpRulesToIpRangeFilter(t *testing.T) { }, { Name: "One element", - Input: &[]documentdb.IPAddressOrRange{ + Input: &[]cosmosdb.IPAddressOrRange{ {IPAddressOrRange: &ipAddressOne}, }, Expected: []string{"127.0.0.1/32"}, }, { Name: "Multiple elements", - Input: &[]documentdb.IPAddressOrRange{ + Input: &[]cosmosdb.IPAddressOrRange{ {IPAddressOrRange: &ipAddressOne}, {IPAddressOrRange: &ipAddressTwo}, }, @@ -58,24 +58,24 @@ func TestCosmosDBIpRangeFilterToIpRules(t *testing.T) { testData := []struct { Name string Input []string - Expected *[]documentdb.IPAddressOrRange + Expected *[]cosmosdb.IPAddressOrRange }{ { Name: "Empty", Input: []string{}, - Expected: &[]documentdb.IPAddressOrRange{}, + Expected: &[]cosmosdb.IPAddressOrRange{}, }, { Name: "One element", Input: []string{ipAddressOne}, - Expected: &[]documentdb.IPAddressOrRange{ + Expected: &[]cosmosdb.IPAddressOrRange{ {IPAddressOrRange: &ipAddressOne}, }, }, { Name: "Multiple elements", Input: []string{ipAddressOne, ipAddressTwo}, - Expected: &[]documentdb.IPAddressOrRange{ + Expected: &[]cosmosdb.IPAddressOrRange{ {IPAddressOrRange: &ipAddressOne}, {IPAddressOrRange: &ipAddressTwo}, }, diff --git a/internal/services/cosmos/cosmosdb_account_data_source.go b/internal/services/cosmos/cosmosdb_account_data_source.go index 6f944dd751fb..52dca60e7ad6 100644 --- a/internal/services/cosmos/cosmosdb_account_data_source.go +++ b/internal/services/cosmos/cosmosdb_account_data_source.go @@ -9,16 +9,16 @@ import ( "sort" "time" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/cosmos/common" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/cosmos/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceCosmosDbAccount() *pluginsdk.Resource { @@ -39,7 +39,7 @@ func dataSourceCosmosDbAccount() *pluginsdk.Resource { "location": commonschema.LocationComputed(), - "tags": tags.SchemaDataSource(), + "tags": commonschema.TagsDataSource(), "offer_type": { Type: pluginsdk.TypeString, @@ -263,16 +263,16 @@ func dataSourceCosmosDbAccount() *pluginsdk.Resource { } func dataSourceCosmosDbAccountRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Cosmos.DatabaseClient + client := meta.(*clients.Client).Cosmos.CosmosDBClient subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewDatabaseAccountID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + id := cosmosdb.NewDatabaseAccountID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) - resp, err := client.Get(ctx, id.ResourceGroup, id.Name) + resp, err := client.DatabaseAccountsGet(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } @@ -280,136 +280,150 @@ func dataSourceCosmosDbAccountRead(d *pluginsdk.ResourceData, meta interface{}) } d.SetId(id.ID()) - d.Set("name", resp.Name) - d.Set("resource_group_name", id.ResourceGroup) - - d.Set("location", location.NormalizeNilable(resp.Location)) - d.Set("kind", string(resp.Kind)) - - if props := resp.DatabaseAccountGetProperties; props != nil { - d.Set("offer_type", string(props.DatabaseAccountOfferType)) - d.Set("ip_range_filter", common.CosmosDBIpRulesToIpRangeFilterThreePointOh(props.IPRules)) - d.Set("endpoint", props.DocumentEndpoint) - d.Set("is_virtual_network_filter_enabled", resp.IsVirtualNetworkFilterEnabled) - d.Set("enable_free_tier", resp.EnableFreeTier) - d.Set("enable_automatic_failover", resp.EnableAutomaticFailover) - - if v := props.KeyVaultKeyURI; v != nil { - d.Set("key_vault_key_id", resp.KeyVaultKeyURI) - } - if err = d.Set("consistency_policy", flattenAzureRmCosmosDBAccountConsistencyPolicy(resp.ConsistencyPolicy)); err != nil { - return fmt.Errorf("setting `consistency_policy`: %+v", err) - } + if model := resp.Model; model != nil { + d.Set("name", model.Name) + d.Set("resource_group_name", id.ResourceGroupName) - locations := make([]map[string]interface{}, len(*props.FailoverPolicies)) - - // the original procedure leads to a sorted locations slice by using failover priority as index - // sort `geo_locations` by failover priority if we found priorities were not within limitation. - if anyUnexpectedFailoverPriority(*props.FailoverPolicies) { - policies := *props.FailoverPolicies - sort.Slice(policies, func(i, j int) bool { - return *policies[i].FailoverPriority < *policies[j].FailoverPriority - }) - for i, l := range policies { - locations[i] = map[string]interface{}{ - "id": *l.ID, - "location": location.NormalizeNilable(l.LocationName), - "failover_priority": int(*l.FailoverPriority), - } + d.Set("location", location.NormalizeNilable(model.Location)) + d.Set("kind", string(pointer.From(model.Kind))) + + if props := model.Properties; props != nil { + d.Set("offer_type", string(pointer.From(props.DatabaseAccountOfferType))) + d.Set("ip_range_filter", common.CosmosDBIpRulesToIpRangeFilterThreePointOh(props.IPRules)) + d.Set("endpoint", props.DocumentEndpoint) + d.Set("is_virtual_network_filter_enabled", props.IsVirtualNetworkFilterEnabled) + d.Set("enable_free_tier", props.EnableFreeTier) + d.Set("enable_automatic_failover", props.EnableAutomaticFailover) + + if v := props.KeyVaultKeyUri; v != nil { + d.Set("key_vault_key_id", v) } - } else { - for _, l := range *props.FailoverPolicies { - locations[*l.FailoverPriority] = map[string]interface{}{ - "id": *l.ID, - "location": location.NormalizeNilable(l.LocationName), - "failover_priority": int(*l.FailoverPriority), + + if err = d.Set("consistency_policy", flattenAzureRmCosmosDBAccountConsistencyPolicy(props.ConsistencyPolicy)); err != nil { + return fmt.Errorf("setting `consistency_policy`: %+v", err) + } + + locations := make([]map[string]interface{}, len(*props.FailoverPolicies)) + + // the original procedure leads to a sorted locations slice by using failover priority as index + // sort `geo_locations` by failover priority if we found priorities were not within limitation. + if anyUnexpectedFailoverPriority(*props.FailoverPolicies) { + policies := *props.FailoverPolicies + sort.Slice(policies, func(i, j int) bool { + return *policies[i].FailoverPriority < *policies[j].FailoverPriority + }) + for i, l := range policies { + locations[i] = map[string]interface{}{ + "id": *l.Id, + "location": location.NormalizeNilable(l.LocationName), + "failover_priority": int(*l.FailoverPriority), + } + } + } else { + for _, l := range *props.FailoverPolicies { + locations[*l.FailoverPriority] = map[string]interface{}{ + "id": *l.Id, + "location": location.NormalizeNilable(l.LocationName), + "failover_priority": int(*l.FailoverPriority), + } } } - } - if err = d.Set("geo_location", locations); err != nil { - return fmt.Errorf("setting `geo_location`: %+v", err) - } + if err = d.Set("geo_location", locations); err != nil { + return fmt.Errorf("setting `geo_location`: %+v", err) + } - if err = d.Set("capabilities", flattenAzureRmCosmosDBAccountCapabilitiesAsList(resp.Capabilities)); err != nil { - return fmt.Errorf("setting `capabilities`: %+v", err) - } + if err = d.Set("capabilities", flattenAzureRmCosmosDBAccountCapabilitiesAsList(props.Capabilities)); err != nil { + return fmt.Errorf("setting `capabilities`: %+v", err) + } - if err = d.Set("virtual_network_rule", flattenAzureRmCosmosDBAccountVirtualNetworkRulesAsList(props.VirtualNetworkRules)); err != nil { - return fmt.Errorf("setting `virtual_network_rule`: %+v", err) - } + if err = d.Set("virtual_network_rule", flattenAzureRmCosmosDBAccountVirtualNetworkRulesAsList(props.VirtualNetworkRules)); err != nil { + return fmt.Errorf("setting `virtual_network_rule`: %+v", err) + } - readEndpoints := make([]string, 0) - if locations := props.ReadLocations; locations != nil { - for _, l := range *locations { - if l.DocumentEndpoint == nil { - continue - } + readEndpoints := make([]string, 0) + if locations := props.ReadLocations; locations != nil { + for _, l := range *locations { + if l.DocumentEndpoint == nil { + continue + } - readEndpoints = append(readEndpoints, *l.DocumentEndpoint) + readEndpoints = append(readEndpoints, *l.DocumentEndpoint) + } + } + if err := d.Set("read_endpoints", readEndpoints); err != nil { + return fmt.Errorf("setting `read_endpoints`: %s", err) } - } - if err := d.Set("read_endpoints", readEndpoints); err != nil { - return fmt.Errorf("setting `read_endpoints`: %s", err) - } - writeEndpoints := make([]string, 0) - if locations := props.WriteLocations; locations != nil { - for _, l := range *locations { - if l.DocumentEndpoint == nil { - continue - } + writeEndpoints := make([]string, 0) + if locations := props.WriteLocations; locations != nil { + for _, l := range *locations { + if l.DocumentEndpoint == nil { + continue + } - writeEndpoints = append(writeEndpoints, *l.DocumentEndpoint) + writeEndpoints = append(writeEndpoints, *l.DocumentEndpoint) + } } - } - if err := d.Set("write_endpoints", writeEndpoints); err != nil { - return fmt.Errorf("setting `write_endpoints`: %s", err) + if err := d.Set("write_endpoints", writeEndpoints); err != nil { + return fmt.Errorf("setting `write_endpoints`: %s", err) + } + + d.Set("enable_multiple_write_locations", props.EnableMultipleWriteLocations) } - d.Set("enable_multiple_write_locations", resp.EnableMultipleWriteLocations) + if err := tags.FlattenAndSet(d, model.Tags); err != nil { + return err + } } - keys, err := client.ListKeys(ctx, id.ResourceGroup, id.Name) + keys, err := client.DatabaseAccountsListKeys(ctx, id) if err != nil { log.Printf("[ERROR] Unable to List Write keys for %s: %s", id, err) } else { - d.Set("primary_key", keys.PrimaryMasterKey) - d.Set("secondary_key", keys.SecondaryMasterKey) + if model := keys.Model; model != nil { + d.Set("primary_key", model.PrimaryMasterKey) + d.Set("secondary_key", model.SecondaryMasterKey) + } } - readonlyKeys, err := client.ListReadOnlyKeys(ctx, id.ResourceGroup, id.Name) + readonlyKeys, err := client.DatabaseAccountsListReadOnlyKeys(ctx, id) if err != nil { log.Printf("[ERROR] Unable to List read-only keys for %s: %s", id, err) } else { - d.Set("primary_readonly_key", readonlyKeys.PrimaryReadonlyMasterKey) - d.Set("secondary_readonly_key", readonlyKeys.SecondaryReadonlyMasterKey) + if model := readonlyKeys.Model; model != nil { + d.Set("primary_readonly_key", model.PrimaryReadonlyMasterKey) + d.Set("secondary_readonly_key", model.SecondaryReadonlyMasterKey) + } } - connStringResp, err := client.ListConnectionStrings(ctx, id.ResourceGroup, id.Name) + + connStringResp, err := client.DatabaseAccountsListConnectionStrings(ctx, id) if err != nil { - if utils.ResponseWasNotFound(keys.Response) { - log.Printf("[DEBUG] Connection Strings were not found for CosmosDB Account %q (Resource Group %q) - removing from state!", id.Name, id.ResourceGroup) + if response.WasNotFound(keys.HttpResponse) { + log.Printf("[DEBUG] Connection Strings were not found for CosmosDB Account %q (Resource Group %q) - removing from state!", id.DatabaseAccountName, id.ResourceGroupName) } else { - log.Printf("[ERROR] Unable to List connection strings for CosmosDB Account %s: %s", id.Name, err) + log.Printf("[ERROR] Unable to List connection strings for CosmosDB Account %s: %s", id.DatabaseAccountName, err) } } else { - var connStrings []string - if connStringResp.ConnectionStrings != nil { - connStrings = make([]string, len(*connStringResp.ConnectionStrings)) - for i, v := range *connStringResp.ConnectionStrings { - connStrings[i] = *v.ConnectionString - if propertyName, propertyExists := connStringPropertyMap[*v.Description]; propertyExists { - d.Set(propertyName, v.ConnectionString) // lintignore:R001 + if model := connStringResp.Model; model != nil { + var connStrings []string + if model.ConnectionStrings != nil { + connStrings = make([]string, len(*model.ConnectionStrings)) + for i, v := range *model.ConnectionStrings { + connStrings[i] = *v.ConnectionString + if propertyName, propertyExists := connStringPropertyMap[*v.Description]; propertyExists { + d.Set(propertyName, v.ConnectionString) // lintignore:R001 + } } } - } - d.Set("connection_strings", connStrings) + d.Set("connection_strings", connStrings) + } } - return tags.FlattenAndSet(d, resp.Tags) + return nil } -func anyUnexpectedFailoverPriority(failoverPolicies []documentdb.FailoverPolicy) bool { +func anyUnexpectedFailoverPriority(failoverPolicies []cosmosdb.FailoverPolicy) bool { size := len(failoverPolicies) for _, policy := range failoverPolicies { if int(*policy.FailoverPriority) > size-1 { @@ -419,7 +433,7 @@ func anyUnexpectedFailoverPriority(failoverPolicies []documentdb.FailoverPolicy) return false } -func flattenAzureRmCosmosDBAccountCapabilitiesAsList(capabilities *[]documentdb.Capability) *[]map[string]interface{} { +func flattenAzureRmCosmosDBAccountCapabilitiesAsList(capabilities *[]cosmosdb.Capability) *[]map[string]interface{} { slice := make([]map[string]interface{}, 0) for _, c := range *capabilities { @@ -434,7 +448,7 @@ func flattenAzureRmCosmosDBAccountCapabilitiesAsList(capabilities *[]documentdb. return &slice } -func flattenAzureRmCosmosDBAccountVirtualNetworkRulesAsList(rules *[]documentdb.VirtualNetworkRule) []map[string]interface{} { +func flattenAzureRmCosmosDBAccountVirtualNetworkRulesAsList(rules *[]cosmosdb.VirtualNetworkRule) []map[string]interface{} { if rules == nil { return []map[string]interface{}{} } @@ -442,7 +456,7 @@ func flattenAzureRmCosmosDBAccountVirtualNetworkRulesAsList(rules *[]documentdb. virtualNetworkRules := make([]map[string]interface{}, len(*rules)) for i, r := range *rules { virtualNetworkRules[i] = map[string]interface{}{ - "id": *r.ID, + "id": *r.Id, } } return virtualNetworkRules diff --git a/internal/services/cosmos/cosmosdb_account_data_source_test.go b/internal/services/cosmos/cosmosdb_account_data_source_test.go index 652f25a997f6..81bc09c3a173 100644 --- a/internal/services/cosmos/cosmosdb_account_data_source_test.go +++ b/internal/services/cosmos/cosmosdb_account_data_source_test.go @@ -7,7 +7,7 @@ import ( "fmt" "testing" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" ) @@ -22,7 +22,7 @@ func TestAccDataSourceCosmosDBAccount_basic(t *testing.T) { { Config: r.basic(data), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelBoundedStaleness, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 1), ), }, }) @@ -36,7 +36,7 @@ func TestAccDataSourceCosmosDBAccount_complete(t *testing.T) { { Config: r.complete(data), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelBoundedStaleness, 3), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 3), check.That(data.ResourceName).Key("geo_location.0.location").HasValue(data.Locations.Primary), check.That(data.ResourceName).Key("geo_location.1.location").HasValue(data.Locations.Secondary), check.That(data.ResourceName).Key("geo_location.2.location").HasValue(data.Locations.Ternary), @@ -80,19 +80,19 @@ func TestAccDataSourceCosmosDBAccount_mongoDBConnectionString(t *testing.T) { } func (c CosmosDBAccountDataSourceResource) basic(data acceptance.TestData) string { - return c.dataConfig(CosmosDBAccountResource{}.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelBoundedStaleness)) + return c.dataConfig(CosmosDBAccountResource{}.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelBoundedStaleness)) } func (c CosmosDBAccountDataSourceResource) complete(data acceptance.TestData) string { - return c.dataConfig(CosmosDBAccountResource{}.complete(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelBoundedStaleness)) + return c.dataConfig(CosmosDBAccountResource{}.complete(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelBoundedStaleness)) } func (c CosmosDBAccountDataSourceResource) globalDocumentDB(data acceptance.TestData) string { - return c.dataConfig(CosmosDBAccountResource{}.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelBoundedStaleness)) + return c.dataConfig(CosmosDBAccountResource{}.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelBoundedStaleness)) } func (c CosmosDBAccountDataSourceResource) mongoDB(data acceptance.TestData) string { - return c.dataConfig(CosmosDBAccountResource{}.basicMongoDB(data, documentdb.DefaultConsistencyLevelStrong)) + return c.dataConfig(CosmosDBAccountResource{}.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelStrong)) } func (c CosmosDBAccountDataSourceResource) dataConfig(baseConfig string) string { diff --git a/internal/services/cosmos/cosmosdb_account_resource.go b/internal/services/cosmos/cosmosdb_account_resource.go index 3ce97ad15e07..33e3c07adfbc 100644 --- a/internal/services/cosmos/cosmosdb_account_resource.go +++ b/internal/services/cosmos/cosmosdb_account_resource.go @@ -14,11 +14,13 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck - "github.com/Azure/go-autorest/autorest/date" "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" @@ -30,7 +32,6 @@ import ( keyVaultParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse" keyVaultSuppress "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/suppress" keyVaultValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -91,22 +92,22 @@ EnableTtlOnCustomPath: MongoDB EnablePartialUniqueIndex: MongoDB */ var capabilitiesToKindMap = map[string]interface{}{ - strings.ToLower(string(databaseAccountCapabilitiesEnableMongo)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB))}, - strings.ToLower(string(databaseAccountCapabilitiesEnableMongo16MBDocumentSupport)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB))}, - strings.ToLower(string(databaseAccountCapabilitiesEnableMongoRoleBasedAccessControl)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB))}, - strings.ToLower(string(databaseAccountCapabilitiesEnableMongoRetryableWrites)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB))}, - strings.ToLower(string(databaseAccountCapabilitiesEnableUniqueCompoundNestedDocs)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB))}, - strings.ToLower(string(databaseAccountCapabilitiesEnableTtlOnCustomPath)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB))}, - strings.ToLower(string(databaseAccountCapabilitiesEnablePartialUniqueIndex)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB))}, - strings.ToLower(string(databaseAccountCapabilitiesEnableCassandra)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(documentdb.DatabaseAccountKindParse))}, - strings.ToLower(string(databaseAccountCapabilitiesEnableGremlin)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(documentdb.DatabaseAccountKindParse))}, - strings.ToLower(string(databaseAccountCapabilitiesEnableTable)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(documentdb.DatabaseAccountKindParse))}, - strings.ToLower(string(databaseAccountCapabilitiesEnableServerless)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(documentdb.DatabaseAccountKindParse))}, - strings.ToLower(string(databaseAccountCapabilitiesEnableAggregationPipeline)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(documentdb.DatabaseAccountKindParse))}, - strings.ToLower(string(databaseAccountCapabilitiesMongoDBv34)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(documentdb.DatabaseAccountKindParse))}, - strings.ToLower(string(databaseAccountCapabilitiesMongoEnableDocLevelTTL)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(documentdb.DatabaseAccountKindParse))}, - strings.ToLower(string(databaseAccountCapabilitiesDisableRateLimitingResponses)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(documentdb.DatabaseAccountKindParse))}, - strings.ToLower(string(databaseAccountCapabilitiesAllowSelfServeUpgradeToMongo36)): []string{strings.ToLower(string(documentdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(documentdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(documentdb.DatabaseAccountKindParse))}, + strings.ToLower(string(databaseAccountCapabilitiesEnableMongo)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB))}, + strings.ToLower(string(databaseAccountCapabilitiesEnableMongo16MBDocumentSupport)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB))}, + strings.ToLower(string(databaseAccountCapabilitiesEnableMongoRoleBasedAccessControl)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB))}, + strings.ToLower(string(databaseAccountCapabilitiesEnableMongoRetryableWrites)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB))}, + strings.ToLower(string(databaseAccountCapabilitiesEnableUniqueCompoundNestedDocs)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB))}, + strings.ToLower(string(databaseAccountCapabilitiesEnableTtlOnCustomPath)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB))}, + strings.ToLower(string(databaseAccountCapabilitiesEnablePartialUniqueIndex)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB))}, + strings.ToLower(string(databaseAccountCapabilitiesEnableCassandra)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindParse))}, + strings.ToLower(string(databaseAccountCapabilitiesEnableGremlin)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindParse))}, + strings.ToLower(string(databaseAccountCapabilitiesEnableTable)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindParse))}, + strings.ToLower(string(databaseAccountCapabilitiesEnableServerless)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindParse))}, + strings.ToLower(string(databaseAccountCapabilitiesEnableAggregationPipeline)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindParse))}, + strings.ToLower(string(databaseAccountCapabilitiesMongoDBv34)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindParse))}, + strings.ToLower(string(databaseAccountCapabilitiesMongoEnableDocLevelTTL)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindParse))}, + strings.ToLower(string(databaseAccountCapabilitiesDisableRateLimitingResponses)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindParse))}, + strings.ToLower(string(databaseAccountCapabilitiesAllowSelfServeUpgradeToMongo36)): []string{strings.ToLower(string(cosmosdb.DatabaseAccountKindGlobalDocumentDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindMongoDB)), strings.ToLower(string(cosmosdb.DatabaseAccountKindParse))}, } // If the consistency policy of the Cosmos DB Database Account is not bounded staleness, @@ -119,7 +120,7 @@ func suppressConsistencyPolicyStalenessConfiguration(_, _, _ string, d *pluginsd consistencyPolicy := consistencyPolicyList[0].(map[string]interface{}) - return consistencyPolicy["consistency_level"].(string) != string(documentdb.DefaultConsistencyLevelBoundedStaleness) + return consistencyPolicy["consistency_level"].(string) != string(cosmosdb.DefaultConsistencyLevelBoundedStaleness) } func resourceCosmosDbAccount() *pluginsdk.Resource { @@ -131,7 +132,7 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { CustomizeDiff: pluginsdk.CustomDiffWithAll( pluginsdk.ForceNewIfChange("backup.0.type", func(ctx context.Context, old, new, _ interface{}) bool { // backup type can only change from Periodic to Continuous - return old.(string) == string(documentdb.TypeContinuous) && new.(string) == string(documentdb.TypePeriodic) + return old.(string) == string(cosmosdb.BackupPolicyTypeContinuous) && new.(string) == string(cosmosdb.BackupPolicyTypePeriodic) }), pluginsdk.ForceNewIfChange("analytical_storage_enabled", func(ctx context.Context, old, new, _ interface{}) bool { @@ -150,7 +151,7 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { caps := diff.Get("capabilities") mongo34found := false enableMongo := false - isMongo := strings.EqualFold(diff.Get("kind").(string), string(documentdb.DatabaseAccountKindMongoDB)) + isMongo := strings.EqualFold(diff.Get("kind").(string), string(cosmosdb.DatabaseAccountKindMongoDB)) for _, cap := range caps.(*pluginsdk.Set).List() { m := cap.(map[string]interface{}) @@ -202,7 +203,7 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(documentdb.DatabaseAccountOfferTypeStandard), + string(cosmosdb.DatabaseAccountOfferTypeStandard), }, false), }, @@ -217,8 +218,8 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(documentdb.AnalyticalStorageSchemaTypeWellDefined), - string(documentdb.AnalyticalStorageSchemaTypeFullFidelity), + string(cosmosdb.AnalyticalStorageSchemaTypeWellDefined), + string(cosmosdb.AnalyticalStorageSchemaTypeFullFidelity), }, false), }, }, @@ -247,8 +248,8 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { Computed: true, ForceNew: true, ValidateFunc: validation.StringInSlice([]string{ - string(documentdb.CreateModeDefault), - string(documentdb.CreateModeRestore), + string(cosmosdb.CreateModeDefault), + string(cosmosdb.CreateModeRestore), }, false), }, @@ -271,11 +272,11 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { Type: pluginsdk.TypeString, Optional: true, ForceNew: true, - Default: string(documentdb.DatabaseAccountKindGlobalDocumentDB), + Default: string(cosmosdb.DatabaseAccountKindGlobalDocumentDB), ValidateFunc: validation.StringInSlice([]string{ - string(documentdb.DatabaseAccountKindGlobalDocumentDB), - string(documentdb.DatabaseAccountKindMongoDB), - string(documentdb.DatabaseAccountKindParse), + string(cosmosdb.DatabaseAccountKindGlobalDocumentDB), + string(cosmosdb.DatabaseAccountKindMongoDB), + string(cosmosdb.DatabaseAccountKindParse), }, false), }, @@ -345,11 +346,11 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(documentdb.DefaultConsistencyLevelBoundedStaleness), - string(documentdb.DefaultConsistencyLevelConsistentPrefix), - string(documentdb.DefaultConsistencyLevelEventual), - string(documentdb.DefaultConsistencyLevelSession), - string(documentdb.DefaultConsistencyLevelStrong), + string(cosmosdb.DefaultConsistencyLevelBoundedStaleness), + string(cosmosdb.DefaultConsistencyLevelConsistentPrefix), + string(cosmosdb.DefaultConsistencyLevelEventual), + string(cosmosdb.DefaultConsistencyLevelSession), + string(cosmosdb.DefaultConsistencyLevelStrong), }, false), }, @@ -483,10 +484,10 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { Optional: true, Computed: true, ValidateFunc: validation.StringInSlice([]string{ - string(documentdb.ServerVersionThreeFullStopTwo), - string(documentdb.ServerVersionThreeFullStopSix), - string(documentdb.ServerVersionFourFullStopZero), - string(documentdb.ServerVersionFourFullStopTwo), + string(cosmosdb.ServerVersionThreePointTwo), + string(cosmosdb.ServerVersionThreePointSix), + string(cosmosdb.ServerVersionFourPointZero), + string(cosmosdb.ServerVersionFourPointTwo), }, false), }, @@ -515,8 +516,8 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(documentdb.TypeContinuous), - string(documentdb.TypePeriodic), + string(cosmosdb.BackupPolicyTypeContinuous), + string(cosmosdb.BackupPolicyTypePeriodic), }, false), }, @@ -539,9 +540,9 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { Optional: true, Computed: true, ValidateFunc: validation.StringInSlice([]string{ - string(documentdb.BackupStorageRedundancyGeo), - string(documentdb.BackupStorageRedundancyLocal), - string(documentdb.BackupStorageRedundancyZone), + string(cosmosdb.BackupStorageRedundancyGeo), + string(cosmosdb.BackupStorageRedundancyLocal), + string(cosmosdb.BackupStorageRedundancyZone), }, false), }, }, @@ -705,29 +706,29 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { Sensitive: true, }, - "tags": tags.Schema(), + "tags": commonschema.Tags(), }, } } func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Cosmos.DatabaseClient + client := meta.(*clients.Client).Cosmos.CosmosDBClient subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() log.Printf("[INFO] Preparing arguments for AzureRM Cosmos DB Account creation") - id := parse.NewDatabaseAccountID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + id := cosmosdb.NewDatabaseAccountID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.Get(ctx, id.ResourceGroup, id.Name) + existing, err := client.DatabaseAccountsGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %s", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return tf.ImportAsExistsError("azurerm_cosmosdb_account", id.ID()) } } @@ -737,7 +738,7 @@ func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) kind := d.Get("kind").(string) offerType := d.Get("offer_type").(string) - var ipRangeFilter *[]documentdb.IPAddressOrRange + var ipRangeFilter *[]cosmosdb.IPAddressOrRange if features.FourPointOhBeta() { ipRangeFilter = common.CosmosDBIpRangeFilterToIpRules(*utils.ExpandStringSlice(d.Get("ip_range_filter").(*pluginsdk.Set).List())) } else { @@ -751,15 +752,15 @@ func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) enableAnalyticalStorage := d.Get("analytical_storage_enabled").(bool) disableLocalAuthentication := d.Get("local_authentication_disabled").(bool) - r, err := client.CheckNameExists(ctx, id.Name) + r, err := client.DatabaseAccountsCheckNameExists(ctx, cosmosdb.NewDatabaseAccountNameID(id.DatabaseAccountName)) if err != nil { // TODO: remove when https://github.com/Azure/azure-sdk-for-go/issues/9891 is fixed - if !utils.ResponseWasStatusCode(r, http.StatusInternalServerError) { + if r.HttpResponse == nil || r.HttpResponse.StatusCode != http.StatusInternalServerError { return fmt.Errorf("checking if CosmosDB Account %s: %+v", id, err) } } else { - if !utils.ResponseWasNotFound(r) { - return fmt.Errorf("CosmosDB Account %s already exists, please import the resource via terraform import", id.Name) + if r.HttpResponse == nil || r.HttpResponse.StatusCode != http.StatusNotFound { + return fmt.Errorf("CosmosDB Account %s already exists, please import the resource via terraform import", id.DatabaseAccountName) } } geoLocations, err := expandAzureRmCosmosDBAccountGeoLocations(d) @@ -767,44 +768,44 @@ func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) return fmt.Errorf("expanding %s geo locations: %+v", id, err) } - publicNetworkAccess := documentdb.PublicNetworkAccessEnabled + publicNetworkAccess := cosmosdb.PublicNetworkAccessEnabled if enabled := d.Get("public_network_access_enabled").(bool); !enabled { - publicNetworkAccess = documentdb.PublicNetworkAccessDisabled + publicNetworkAccess = cosmosdb.PublicNetworkAccessDisabled } - networkByPass := documentdb.NetworkACLBypassNone + networkByPass := cosmosdb.NetworkAclBypassNone if d.Get("network_acl_bypass_for_azure_services").(bool) { - networkByPass = documentdb.NetworkACLBypassAzureServices + networkByPass = cosmosdb.NetworkAclBypassAzureServices } - expandedIdentity, err := expandAccountIdentity(d.Get("identity").([]interface{})) + expandedIdentity, err := identity.ExpandLegacySystemAndUserAssignedMap(d.Get("identity").([]interface{})) if err != nil { return fmt.Errorf("expanding `identity`: %+v", err) } capabilities := expandAzureRmCosmosDBAccountCapabilities(d) - account := documentdb.DatabaseAccountCreateUpdateParameters{ + account := cosmosdb.DatabaseAccountCreateUpdateParameters{ Location: pointer.To(location), - Kind: documentdb.DatabaseAccountKind(kind), + Kind: pointer.To(cosmosdb.DatabaseAccountKind(kind)), Identity: expandedIdentity, - DatabaseAccountCreateUpdateProperties: &documentdb.DatabaseAccountCreateUpdateProperties{ - DatabaseAccountOfferType: pointer.To(offerType), + Properties: cosmosdb.DatabaseAccountCreateUpdateProperties{ + DatabaseAccountOfferType: cosmosdb.DatabaseAccountOfferType(offerType), IPRules: ipRangeFilter, IsVirtualNetworkFilterEnabled: utils.Bool(isVirtualNetworkFilterEnabled), EnableFreeTier: utils.Bool(enableFreeTier), EnableAutomaticFailover: utils.Bool(enableAutomaticFailover), ConsistencyPolicy: expandAzureRmCosmosDBAccountConsistencyPolicy(d), - Locations: &geoLocations, + Locations: geoLocations, Capabilities: capabilities, VirtualNetworkRules: expandAzureRmCosmosDBAccountVirtualNetworkRules(d), EnableMultipleWriteLocations: utils.Bool(enableMultipleWriteLocations), - PublicNetworkAccess: publicNetworkAccess, + PublicNetworkAccess: pointer.To(publicNetworkAccess), EnableAnalyticalStorage: utils.Bool(enableAnalyticalStorage), Cors: common.ExpandCosmosCorsRule(d.Get("cors_rule").([]interface{})), DisableKeyBasedMetadataWriteAccess: utils.Bool(!d.Get("access_key_metadata_writes_enabled").(bool)), - NetworkACLBypass: networkByPass, - NetworkACLBypassResourceIds: utils.ExpandStringSlice(d.Get("network_acl_bypass_ids").([]interface{})), + NetworkAclBypass: pointer.To(networkByPass), + NetworkAclBypassResourceIds: utils.ExpandStringSlice(d.Get("network_acl_bypass_ids").([]interface{})), DisableLocalAuth: utils.Bool(disableLocalAuthentication), }, Tags: tags.Expand(t), @@ -812,30 +813,30 @@ func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) // These values may not have changed but they need to be in the update params... if v, ok := d.GetOk("default_identity_type"); ok { - account.DatabaseAccountCreateUpdateProperties.DefaultIdentity = pointer.To(v.(string)) + account.Properties.DefaultIdentity = pointer.To(v.(string)) } if v, ok := d.GetOk("analytical_storage"); ok { - account.DatabaseAccountCreateUpdateProperties.AnalyticalStorageConfiguration = expandCosmosDBAccountAnalyticalStorageConfiguration(v.([]interface{})) + account.Properties.AnalyticalStorageConfiguration = expandCosmosDBAccountAnalyticalStorageConfiguration(v.([]interface{})) } if v, ok := d.GetOk("capacity"); ok { - account.DatabaseAccountCreateUpdateProperties.Capacity = expandCosmosDBAccountCapacity(v.([]interface{})) + account.Properties.Capacity = expandCosmosDBAccountCapacity(v.([]interface{})) } var createMode string if v, ok := d.GetOk("create_mode"); ok { createMode = v.(string) - account.DatabaseAccountCreateUpdateProperties.CreateMode = documentdb.CreateMode(createMode) + account.Properties.CreateMode = pointer.To(cosmosdb.CreateMode(createMode)) } if v, ok := d.GetOk("restore"); ok { - account.DatabaseAccountCreateUpdateProperties.RestoreParameters = expandCosmosdbAccountRestoreParameters(v.([]interface{})) + account.Properties.RestoreParameters = expandCosmosdbAccountRestoreParameters(v.([]interface{})) } if v, ok := d.GetOk("mongo_server_version"); ok { - account.DatabaseAccountCreateUpdateProperties.APIProperties = &documentdb.APIProperties{ - ServerVersion: documentdb.ServerVersion(v.(string)), + account.Properties.ApiProperties = &cosmosdb.ApiProperties{ + ServerVersion: pointer.To(cosmosdb.ServerVersion(v.(string))), } } @@ -844,7 +845,7 @@ func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) if err != nil { return fmt.Errorf("expanding `backup`: %+v", err) } - account.DatabaseAccountCreateUpdateProperties.BackupPolicy = policy + account.Properties.BackupPolicy = policy } else if createMode != "" { return fmt.Errorf("`create_mode` only works when `backup.type` is `Continuous`") } @@ -854,12 +855,12 @@ func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) if err != nil { return fmt.Errorf("could not parse Key Vault Key ID: %+v", err) } - account.DatabaseAccountCreateUpdateProperties.KeyVaultKeyURI = pointer.To(keyVaultKey.ID()) + account.Properties.KeyVaultKeyUri = pointer.To(keyVaultKey.ID()) } // additional validation on MaxStalenessPrefix as it varies depending on if the DB is multi region or not - consistencyPolicy := account.DatabaseAccountCreateUpdateProperties.ConsistencyPolicy - if len(geoLocations) > 1 && consistencyPolicy != nil && consistencyPolicy.DefaultConsistencyLevel == documentdb.DefaultConsistencyLevelBoundedStaleness { + consistencyPolicy := account.Properties.ConsistencyPolicy + if len(geoLocations) > 1 && consistencyPolicy != nil && consistencyPolicy.DefaultConsistencyLevel == cosmosdb.DefaultConsistencyLevelBoundedStaleness { if msp := consistencyPolicy.MaxStalenessPrefix; msp != nil && pointer.From(msp) < 100000 { return fmt.Errorf("max_staleness_prefix (%d) must be greater then 100000 when more then one geo_location is used", *msp) } @@ -868,7 +869,7 @@ func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) } } - err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, id.ResourceGroup, id.Name, account, d) + err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, id, account, d) if err != nil { return fmt.Errorf("creating %s: %+v", id, err) } @@ -879,408 +880,397 @@ func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) } func resourceCosmosDbAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Cosmos.DatabaseClient + client := meta.(*clients.Client).Cosmos.CosmosDBClient // subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() log.Printf("[INFO] Preparing arguments for AzureRM Cosmos DB Account update") - id, err := parse.DatabaseAccountID(d.Id()) + id, err := cosmosdb.ParseDatabaseAccountID(d.Id()) if err != nil { return err } // get existing locations (if exists) - existing, err := client.Get(ctx, id.ResourceGroup, id.Name) + existing, err := client.DatabaseAccountsGet(ctx, *id) if err != nil { return fmt.Errorf("making Read request on %s: %s", id, err) } - if existing.DatabaseAccountGetProperties == nil { - return fmt.Errorf("retrieving %s: properties were nil", id) - } - - configLocations, err := expandAzureRmCosmosDBAccountGeoLocations(d) - if err != nil { - return fmt.Errorf("expanding %s geo locations: %+v", id, err) - } - - // Normalize Locations... - cosmosLocations := make([]documentdb.Location, 0) - cosmosLocationsMap := map[string]documentdb.Location{} - - if existing.DatabaseAccountGetProperties.Locations != nil { - for _, l := range *existing.DatabaseAccountGetProperties.Locations { - location := documentdb.Location{ - ID: l.ID, - LocationName: l.LocationName, - FailoverPriority: l.FailoverPriority, - IsZoneRedundant: l.IsZoneRedundant, - } - - cosmosLocations = append(cosmosLocations, location) - cosmosLocationsMap[azure.NormalizeLocation(*location.LocationName)] = location + if model := existing.Model; model != nil { + configLocations, err := expandAzureRmCosmosDBAccountGeoLocations(d) + if err != nil { + return fmt.Errorf("expanding %s geo locations: %+v", id, err) } - } - var capabilities *[]documentdb.Capability - if existing.DatabaseAccountGetProperties.Capabilities != nil { - capabilities = existing.DatabaseAccountGetProperties.Capabilities - } + // Normalize Locations... + cosmosLocations := make([]cosmosdb.Location, 0) + cosmosLocationsMap := map[string]cosmosdb.Location{} - // backup must be updated independently - var backup documentdb.BasicBackupPolicy - if existing.DatabaseAccountGetProperties.BackupPolicy != nil { - backup = existing.DatabaseAccountGetProperties.BackupPolicy - if d.HasChange("backup") { - if v, ok := d.GetOk("backup"); ok { - newBackup, err := expandCosmosdbAccountBackup(v.([]interface{}), d.HasChange("backup.0.type"), string(existing.DatabaseAccountGetProperties.CreateMode)) - if err != nil { - return fmt.Errorf("expanding `backup`: %+v", err) - } - updateParameters := documentdb.DatabaseAccountUpdateParameters{ - DatabaseAccountUpdateProperties: &documentdb.DatabaseAccountUpdateProperties{ - BackupPolicy: newBackup, - }, + if model.Properties.Locations != nil { + for _, l := range *model.Properties.Locations { + location := cosmosdb.Location{ + Id: l.Id, + LocationName: l.LocationName, + FailoverPriority: l.FailoverPriority, + IsZoneRedundant: l.IsZoneRedundant, } - // Update Database 'backup'... - future, err := client.Update(ctx, id.ResourceGroup, id.Name, updateParameters) - if err != nil { - return fmt.Errorf("updating CosmosDB Account %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the CosmosDB Account %q (Resource Group %q) to finish updating: %+v", id.Name, id.ResourceGroup, err) - } - backup = newBackup - } else if string(existing.CreateMode) != "" { - return fmt.Errorf("`create_mode` only works when `backup.type` is `Continuous`") + cosmosLocations = append(cosmosLocations, location) + cosmosLocationsMap[azure.NormalizeLocation(*location.LocationName)] = location } } - } - - updateRequired := false - if props := existing.DatabaseAccountGetProperties; props != nil { - location := azure.NormalizeLocation(pointer.From(existing.Location)) - offerType := d.Get("offer_type").(string) - t := tags.Expand(d.Get("tags").(map[string]interface{})) - kind := documentdb.DatabaseAccountKind(d.Get("kind").(string)) - isVirtualNetworkFilterEnabled := pointer.To(d.Get("is_virtual_network_filter_enabled").(bool)) - enableFreeTier := pointer.To(d.Get("enable_free_tier").(bool)) - enableAutomaticFailover := pointer.To(d.Get("enable_automatic_failover").(bool)) - enableAnalyticalStorage := pointer.To(d.Get("analytical_storage_enabled").(bool)) - disableLocalAuthentication := pointer.To(d.Get("local_authentication_disabled").(bool)) - - networkByPass := documentdb.NetworkACLBypassNone - if d.Get("network_acl_bypass_for_azure_services").(bool) { - networkByPass = documentdb.NetworkACLBypassAzureServices - } - var ipRangeFilter *[]documentdb.IPAddressOrRange - if features.FourPointOhBeta() { - ipRangeFilter = common.CosmosDBIpRangeFilterToIpRules(*utils.ExpandStringSlice(d.Get("ip_range_filter").(*pluginsdk.Set).List())) - } else { - ipRangeFilter = common.CosmosDBIpRangeFilterToIpRulesThreePointOh(d.Get("ip_range_filter").(string)) + var capabilities *[]cosmosdb.Capability + if model.Properties.Capabilities != nil { + capabilities = model.Properties.Capabilities } - publicNetworkAccess := documentdb.PublicNetworkAccessEnabled - if enabled := d.Get("public_network_access_enabled").(bool); !enabled { - publicNetworkAccess = documentdb.PublicNetworkAccessDisabled - } + // backup must be updated independently + var backup cosmosdb.BackupPolicy + if model.Properties.BackupPolicy != nil { + backup = model.Properties.BackupPolicy + if d.HasChange("backup") { + if v, ok := d.GetOk("backup"); ok { + newBackup, err := expandCosmosdbAccountBackup(v.([]interface{}), d.HasChange("backup.0.type"), string(pointer.From(model.Properties.CreateMode))) + if err != nil { + return fmt.Errorf("expanding `backup`: %+v", err) + } + updateParameters := cosmosdb.DatabaseAccountUpdateParameters{ + Properties: &cosmosdb.DatabaseAccountUpdateProperties{ + BackupPolicy: newBackup, + }, + } - // NOTE: these fields are expanded directly into the - // 'DatabaseAccountCreateUpdateParameters' below or - // are included in the 'DatabaseAccountCreateUpdateParameters' - // later, however we need to know if they changed or not... - if d.HasChanges("consistency_policy", "virtual_network_rule", "cors_rule", "access_key_metadata_writes_enabled", - "network_acl_bypass_for_azure_services", "network_acl_bypass_ids", "analytical_storage", - "capacity", "create_mode", "restore", "key_vault_key_id", "mongo_server_version", - "public_network_access_enabled", "ip_range_filter", "offer_type", "is_virtual_network_filter_enabled", - "kind", "tags", "enable_free_tier", "enable_automatic_failover", "analytical_storage_enabled", - "local_authentication_disabled") { - updateRequired = true - } + // Update Database 'backup'... + if err := client.DatabaseAccountsUpdateThenPoll(ctx, *id, updateParameters); err != nil { + return fmt.Errorf("updating %q: %+v", id, err) + } - // Incident : #383341730 - // Azure Bug: #2209567 'Updating identities and default identity at the same time fails silently' - // - // The 'Identity' field should only ever be sent once to the endpoint, except for updates and removal. If the - // 'Identity' field is included in the update call with the 'DefaultIdentity' it will silently fail - // per the bug noted above (e.g. Azure Bug #2209567). - // - // In the update scenario where the end-user would like to update their 'Identity' and their 'DefaultIdentity' - // fields at the same time both of these operations need to happen atomically in separate PUT/PATCH calls - // to the service else you will hit the bug mentioned above. You need to update the 'Identity' field - // first then update the 'DefaultIdentity' in totally different PUT/PATCH calls where you have to drop - // the 'Identity' field on the floor when updating the 'DefaultIdentity' field. - // - // NOTE : If the 'Identity' field has not changed in the resource, do not send it in the payload. - // this workaround can be removed once the service team fixes the above mentioned bug. - // - // ADDITIONAL: You cannot update properties and add/remove replication locations or update the enabling of - // multiple write locations at the same time. So you must update any changed properties - // first, then address the replication locations and/or updating/enabling of - // multiple write locations. - - account := documentdb.DatabaseAccountCreateUpdateParameters{ - Location: pointer.To(location), - Kind: kind, - DatabaseAccountCreateUpdateProperties: &documentdb.DatabaseAccountCreateUpdateProperties{ - DatabaseAccountOfferType: pointer.To(offerType), - IPRules: ipRangeFilter, - IsVirtualNetworkFilterEnabled: isVirtualNetworkFilterEnabled, - EnableFreeTier: enableFreeTier, - EnableAutomaticFailover: enableAutomaticFailover, - Capabilities: capabilities, - ConsistencyPolicy: expandAzureRmCosmosDBAccountConsistencyPolicy(d), - Locations: pointer.To(cosmosLocations), - VirtualNetworkRules: expandAzureRmCosmosDBAccountVirtualNetworkRules(d), - EnableMultipleWriteLocations: props.EnableMultipleWriteLocations, - PublicNetworkAccess: publicNetworkAccess, - EnableAnalyticalStorage: enableAnalyticalStorage, - Cors: common.ExpandCosmosCorsRule(d.Get("cors_rule").([]interface{})), - DisableKeyBasedMetadataWriteAccess: pointer.To(!d.Get("access_key_metadata_writes_enabled").(bool)), - NetworkACLBypass: networkByPass, - NetworkACLBypassResourceIds: utils.ExpandStringSlice(d.Get("network_acl_bypass_ids").([]interface{})), - DisableLocalAuth: disableLocalAuthentication, - BackupPolicy: backup, - }, - Tags: t, + backup = newBackup + } else if string(pointer.From(model.Properties.CreateMode)) != "" { + return fmt.Errorf("`create_mode` only works when `backup.type` is `Continuous`") + } + } } - accountProps := account.DatabaseAccountCreateUpdateProperties + updateRequired := false + if props := model.Properties; props != nil { + location := azure.NormalizeLocation(pointer.From(model.Location)) + offerType := d.Get("offer_type").(string) + t := tags.Expand(d.Get("tags").(map[string]interface{})) + kind := cosmosdb.DatabaseAccountKind(d.Get("kind").(string)) + isVirtualNetworkFilterEnabled := pointer.To(d.Get("is_virtual_network_filter_enabled").(bool)) + enableFreeTier := pointer.To(d.Get("enable_free_tier").(bool)) + enableAutomaticFailover := pointer.To(d.Get("enable_automatic_failover").(bool)) + enableAnalyticalStorage := pointer.To(d.Get("analytical_storage_enabled").(bool)) + disableLocalAuthentication := pointer.To(d.Get("local_authentication_disabled").(bool)) + + networkByPass := cosmosdb.NetworkAclBypassNone + if d.Get("network_acl_bypass_for_azure_services").(bool) { + networkByPass = cosmosdb.NetworkAclBypassAzureServices + } - if keyVaultKeyIDRaw, ok := d.GetOk("key_vault_key_id"); ok { - keyVaultKey, err := keyVaultParse.ParseOptionallyVersionedNestedItemID(keyVaultKeyIDRaw.(string)) - if err != nil { - return fmt.Errorf("could not parse Key Vault Key ID: %+v", err) + var ipRangeFilter *[]cosmosdb.IPAddressOrRange + if features.FourPointOhBeta() { + ipRangeFilter = common.CosmosDBIpRangeFilterToIpRules(*utils.ExpandStringSlice(d.Get("ip_range_filter").(*pluginsdk.Set).List())) + } else { + ipRangeFilter = common.CosmosDBIpRangeFilterToIpRulesThreePointOh(d.Get("ip_range_filter").(string)) } - accountProps.KeyVaultKeyURI = pointer.To(keyVaultKey.ID()) - } - // 'default_identity_type' will always have a value since it now has a default value of "FirstPartyIdentity" per the API documentation. - // I do not include 'DefaultIdentity' and 'Identity' in the 'accountProps' intentionally, these operations need to be - // performed mutually exclusive from each other in an atomic fashion, else you will hit the service teams bug... - updateDefaultIdentity := false - if d.HasChange("default_identity_type") { - updateDefaultIdentity = true - } + publicNetworkAccess := cosmosdb.PublicNetworkAccessEnabled + if enabled := d.Get("public_network_access_enabled").(bool); !enabled { + publicNetworkAccess = cosmosdb.PublicNetworkAccessDisabled + } - // adding 'DefaultIdentity' to avoid causing it to fallback - // to "FirstPartyIdentity" on update(s), issue #22466 - if v, ok := d.GetOk("default_identity_type"); ok { - accountProps.DefaultIdentity = pointer.To(v.(string)) - } + // NOTE: these fields are expanded directly into the + // 'DatabaseAccountCreateUpdateParameters' below or + // are included in the 'DatabaseAccountCreateUpdateParameters' + // later, however we need to know if they changed or not... + if d.HasChanges("consistency_policy", "virtual_network_rule", "cors_rule", "access_key_metadata_writes_enabled", + "network_acl_bypass_for_azure_services", "network_acl_bypass_ids", "analytical_storage", + "capacity", "create_mode", "restore", "key_vault_key_id", "mongo_server_version", + "public_network_access_enabled", "ip_range_filter", "offer_type", "is_virtual_network_filter_enabled", + "kind", "tags", "enable_free_tier", "enable_automatic_failover", "analytical_storage_enabled", + "local_authentication_disabled") { + updateRequired = true + } - // we need the following in the accountProps even if they have not changed... - if v, ok := d.GetOk("analytical_storage"); ok { - accountProps.AnalyticalStorageConfiguration = expandCosmosDBAccountAnalyticalStorageConfiguration(v.([]interface{})) - } + // Incident : #383341730 + // Azure Bug: #2209567 'Updating identities and default identity at the same time fails silently' + // + // The 'Identity' field should only ever be sent once to the endpoint, except for updates and removal. If the + // 'Identity' field is included in the update call with the 'DefaultIdentity' it will silently fail + // per the bug noted above (e.g. Azure Bug #2209567). + // + // In the update scenario where the end-user would like to update their 'Identity' and their 'DefaultIdentity' + // fields at the same time both of these operations need to happen atomically in separate PUT/PATCH calls + // to the service else you will hit the bug mentioned above. You need to update the 'Identity' field + // first then update the 'DefaultIdentity' in totally different PUT/PATCH calls where you have to drop + // the 'Identity' field on the floor when updating the 'DefaultIdentity' field. + // + // NOTE : If the 'Identity' field has not changed in the resource, do not send it in the payload. + // this workaround can be removed once the service team fixes the above mentioned bug. + // + // ADDITIONAL: You cannot update properties and add/remove replication locations or update the enabling of + // multiple write locations at the same time. So you must update any changed properties + // first, then address the replication locations and/or updating/enabling of + // multiple write locations. + + account := cosmosdb.DatabaseAccountCreateUpdateParameters{ + Location: pointer.To(location), + Kind: pointer.To(kind), + Properties: cosmosdb.DatabaseAccountCreateUpdateProperties{ + DatabaseAccountOfferType: cosmosdb.DatabaseAccountOfferType(offerType), + IPRules: ipRangeFilter, + IsVirtualNetworkFilterEnabled: isVirtualNetworkFilterEnabled, + EnableFreeTier: enableFreeTier, + EnableAutomaticFailover: enableAutomaticFailover, + Capabilities: capabilities, + ConsistencyPolicy: expandAzureRmCosmosDBAccountConsistencyPolicy(d), + Locations: cosmosLocations, + VirtualNetworkRules: expandAzureRmCosmosDBAccountVirtualNetworkRules(d), + EnableMultipleWriteLocations: props.EnableMultipleWriteLocations, + PublicNetworkAccess: pointer.To(publicNetworkAccess), + EnableAnalyticalStorage: enableAnalyticalStorage, + Cors: common.ExpandCosmosCorsRule(d.Get("cors_rule").([]interface{})), + DisableKeyBasedMetadataWriteAccess: pointer.To(!d.Get("access_key_metadata_writes_enabled").(bool)), + NetworkAclBypass: pointer.To(networkByPass), + NetworkAclBypassResourceIds: utils.ExpandStringSlice(d.Get("network_acl_bypass_ids").([]interface{})), + DisableLocalAuth: disableLocalAuthentication, + BackupPolicy: backup, + }, + Tags: t, + } - if v, ok := d.GetOk("capacity"); ok { - accountProps.Capacity = expandCosmosDBAccountCapacity(v.([]interface{})) - } + accountProps := account.Properties - var createMode string - if v, ok := d.GetOk("create_mode"); ok { - createMode = v.(string) - accountProps.CreateMode = documentdb.CreateMode(createMode) - } + if keyVaultKeyIDRaw, ok := d.GetOk("key_vault_key_id"); ok { + keyVaultKey, err := keyVaultParse.ParseOptionallyVersionedNestedItemID(keyVaultKeyIDRaw.(string)) + if err != nil { + return fmt.Errorf("could not parse Key Vault Key ID: %+v", err) + } + accountProps.KeyVaultKeyUri = pointer.To(keyVaultKey.ID()) + } - if v, ok := d.GetOk("restore"); ok { - accountProps.RestoreParameters = expandCosmosdbAccountRestoreParameters(v.([]interface{})) - } + // 'default_identity_type' will always have a value since it now has a default value of "FirstPartyIdentity" per the API documentation. + // I do not include 'DefaultIdentity' and 'Identity' in the 'accountProps' intentionally, these operations need to be + // performed mutually exclusive from each other in an atomic fashion, else you will hit the service teams bug... + updateDefaultIdentity := false + if d.HasChange("default_identity_type") { + updateDefaultIdentity = true + } - if v, ok := d.GetOk("mongo_server_version"); ok { - accountProps.APIProperties = &documentdb.APIProperties{ - ServerVersion: documentdb.ServerVersion(v.(string)), + // adding 'DefaultIdentity' to avoid causing it to fallback + // to "FirstPartyIdentity" on update(s), issue #22466 + if v, ok := d.GetOk("default_identity_type"); ok { + accountProps.DefaultIdentity = pointer.To(v.(string)) } - } - // Only do this update if a value has changed above... - if updateRequired { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DatabaseAccountCreateUpdateParameters'") + // we need the following in the accountProps even if they have not changed... + if v, ok := d.GetOk("analytical_storage"); ok { + accountProps.AnalyticalStorageConfiguration = expandCosmosDBAccountAnalyticalStorageConfiguration(v.([]interface{})) + } - // Update the database... - if err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, id.ResourceGroup, id.Name, account, d); err != nil { - return fmt.Errorf("updating %s: %+v", id, err) + if v, ok := d.GetOk("capacity"); ok { + accountProps.Capacity = expandCosmosDBAccountCapacity(v.([]interface{})) } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Update 'DatabaseAccountCreateUpdateParameters' [NO CHANGE]") - } - // Update the following properties independently after the initial CreateOrUpdate... - if d.HasChange("enable_multiple_write_locations") { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'EnableMultipleWriteLocations'") + var createMode string + if v, ok := d.GetOk("create_mode"); ok { + createMode = v.(string) + accountProps.CreateMode = pointer.To(cosmosdb.CreateMode(createMode)) + } - enableMultipleWriteLocations := pointer.To(d.Get("enable_multiple_write_locations").(bool)) - if props.EnableMultipleWriteLocations != enableMultipleWriteLocations { - accountProps.EnableMultipleWriteLocations = enableMultipleWriteLocations + if v, ok := d.GetOk("restore"); ok { + accountProps.RestoreParameters = expandCosmosdbAccountRestoreParameters(v.([]interface{})) + } - // Update the database... - if err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, id.ResourceGroup, id.Name, account, d); err != nil { - return fmt.Errorf("updating %q EnableMultipleWriteLocations: %+v", id, err) + if v, ok := d.GetOk("mongo_server_version"); ok { + accountProps.ApiProperties = &cosmosdb.ApiProperties{ + ServerVersion: pointer.To(cosmosdb.ServerVersion(v.(string))), } } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'EnableMultipleWriteLocations' [NO CHANGE]") - } - // determine if any locations have been renamed/priority reordered and remove them - updateLocations := false - for _, configLoc := range configLocations { - if cosmosLoc, ok := cosmosLocationsMap[pointer.From(configLoc.LocationName)]; ok { - // is the location in the config also in the database with the same 'FailoverPriority'? - if pointer.From(configLoc.FailoverPriority) != pointer.From(cosmosLoc.FailoverPriority) { - // The Failover Priority has been changed in the config... - if pointer.From(configLoc.FailoverPriority) == 0 { - return fmt.Errorf("cannot change the failover priority of %q location %q to %d", id, pointer.From(configLoc.LocationName), pointer.From(configLoc.FailoverPriority)) - } + // Only do this update if a value has changed above... + if updateRequired { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DatabaseAccountCreateUpdateParameters'") - // since the Locations FailoverPriority changed remove it from the map because - // we have to update the Location in the database. The Locations - // left in the map after this loop are the Locations that are - // the same in the database and in the config file... - delete(cosmosLocationsMap, pointer.From(configLoc.LocationName)) - updateLocations = true + // Update the database... + if err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, *id, account, d); err != nil { + return fmt.Errorf("updating %s: %+v", id, err) } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Update 'DatabaseAccountCreateUpdateParameters' [NO CHANGE]") } - } - if updateLocations { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Removing renamed 'Locations'") - locationsUnchanged := make([]documentdb.Location, 0, len(cosmosLocationsMap)) - for _, value := range cosmosLocationsMap { - locationsUnchanged = append(locationsUnchanged, value) - } + // Update the following properties independently after the initial CreateOrUpdate... + if d.HasChange("enable_multiple_write_locations") { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'EnableMultipleWriteLocations'") - accountProps.Locations = pointer.To(locationsUnchanged) + enableMultipleWriteLocations := pointer.To(d.Get("enable_multiple_write_locations").(bool)) + if props.EnableMultipleWriteLocations != enableMultipleWriteLocations { + accountProps.EnableMultipleWriteLocations = enableMultipleWriteLocations - // Update the database... - if err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, id.ResourceGroup, id.Name, account, d); err != nil { - return fmt.Errorf("removing %q renamed `locations`: %+v", id, err) + // Update the database... + if err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, *id, account, d); err != nil { + return fmt.Errorf("updating %q EnableMultipleWriteLocations: %+v", id, err) + } + } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'EnableMultipleWriteLocations' [NO CHANGE]") } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Removing renamed 'Locations' [NO CHANGE]") - } - if d.HasChanges("geo_location") { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Locations'") - // add any new/renamed locations - accountProps.Locations = pointer.To(configLocations) + // determine if any locations have been renamed/priority reordered and remove them + updateLocations := false + for _, configLoc := range configLocations { + if cosmosLoc, ok := cosmosLocationsMap[pointer.From(configLoc.LocationName)]; ok { + // is the location in the config also in the database with the same 'FailoverPriority'? + if pointer.From(configLoc.FailoverPriority) != pointer.From(cosmosLoc.FailoverPriority) { + // The Failover Priority has been changed in the config... + if pointer.From(configLoc.FailoverPriority) == 0 { + return fmt.Errorf("cannot change the failover priority of %q location %q to %d", id, pointer.From(configLoc.LocationName), pointer.From(configLoc.FailoverPriority)) + } - // Update the database locations... - err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, id.ResourceGroup, id.Name, account, d) - if err != nil { - return fmt.Errorf("updating %q `locations`: %+v", id, err) + // since the Locations FailoverPriority changed remove it from the map because + // we have to update the Location in the database. The Locations + // left in the map after this loop are the Locations that are + // the same in the database and in the config file... + delete(cosmosLocationsMap, pointer.From(configLoc.LocationName)) + updateLocations = true + } + } } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Locations' [NO CHANGE]") - } - // Update Identity and Default Identity... - identityChanged := false - expandedIdentity, err := expandAccountIdentity(d.Get("identity").([]interface{})) - if err != nil { - return fmt.Errorf("expanding `identity`: %+v", err) - } + if updateLocations { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Removing renamed 'Locations'") + locationsUnchanged := make([]cosmosdb.Location, 0, len(cosmosLocationsMap)) + for _, value := range cosmosLocationsMap { + locationsUnchanged = append(locationsUnchanged, value) + } - if d.HasChange("identity") { - identityChanged = true + accountProps.Locations = locationsUnchanged + + // Update the database... + if err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, *id, account, d); err != nil { + return fmt.Errorf("removing %q renamed `locations`: %+v", id, err) + } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Removing renamed 'Locations' [NO CHANGE]") + } - // Looks like you have to always remove all the identities first before you can - // reassign/modify them, else it will append any new/changed identities - // resulting in a diff... - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Setting 'Identity' to 'None'") + if d.HasChanges("geo_location") { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Locations'") + // add any new/renamed locations + accountProps.Locations = configLocations - // can't set this back to account, because that will hit the bug... - identity := documentdb.DatabaseAccountUpdateParameters{ - Identity: pointer.To(documentdb.ManagedServiceIdentity{ - Type: documentdb.ResourceIdentityTypeNone, - }), + // Update the database locations... + err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, *id, account, d) + if err != nil { + return fmt.Errorf("updating %q `locations`: %+v", id, err) + } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Locations' [NO CHANGE]") } - // Update the database 'Identity' to 'None'... - err = resourceCosmosDbAccountApiUpdate(client, ctx, id.ResourceGroup, id.Name, identity, d) + // Update Identity and Default Identity... + identityChanged := false + expandedIdentity, err := identity.ExpandLegacySystemAndUserAssignedMap(d.Get("identity").([]interface{})) if err != nil { - return fmt.Errorf("updating 'identity' %q: %+v", id, err) + return fmt.Errorf("expanding `identity`: %+v", err) } - // If the Identity was removed from the configuration file it will be set as type None - // so we can skip setting the Identity if it is going to be set to None... - if expandedIdentity.Type != documentdb.ResourceIdentityTypeNone { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Identity' to %q", expandedIdentity.Type) + if d.HasChange("identity") { + identityChanged = true + + // Looks like you have to always remove all the identities first before you can + // reassign/modify them, else it will append any new/changed identities + // resulting in a diff... + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Setting 'Identity' to 'None'") - identity := documentdb.DatabaseAccountUpdateParameters{ - Identity: expandedIdentity, + // can't set this back to account, because that will hit the bug... + identityVal := cosmosdb.DatabaseAccountUpdateParameters{ + Identity: pointer.To(identity.LegacySystemAndUserAssignedMap{ + Type: identity.TypeNone, + }), } - // Update the database... - err = resourceCosmosDbAccountApiUpdate(client, ctx, id.ResourceGroup, id.Name, identity, d) + // Update the database 'Identity' to 'None'... + err = resourceCosmosDbAccountApiUpdate(client, ctx, *id, identityVal, d) if err != nil { return fmt.Errorf("updating 'identity' %q: %+v", id, err) } - } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Identity' [NO CHANGE]") - } - // NOTE: updateDefaultIdentity now has a default value of 'FirstPartyIdentity'... This value now gets - // triggered if the default value does not match the value in Azure... - // - // NOTE: When you change the 'Identity', the 'DefaultIdentity' will be set to 'undefined', so if you change - // the identity you must also update the 'DefaultIdentity' as well... - if updateDefaultIdentity || identityChanged { - // This will now return the default of 'FirstPartyIdentity' if it - // is not set in the config, which is correct. - configDefaultIdentity := d.Get("default_identity_type").(string) - if identityChanged { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DefaultIdentity' to %q because the 'Identity' was changed to %q", configDefaultIdentity, expandedIdentity.Type) - } else { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DefaultIdentity' to %q because 'default_identity_type' was changed", configDefaultIdentity) - } + // If the Identity was removed from the configuration file it will be set as type None + // so we can skip setting the Identity if it is going to be set to None... + if expandedIdentity.Type != identity.TypeNone { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Identity' to %q", expandedIdentity.Type) - // PATCH instead of PUT... - defaultIdentity := documentdb.DatabaseAccountUpdateParameters{ - DatabaseAccountUpdateProperties: &documentdb.DatabaseAccountUpdateProperties{ - DefaultIdentity: pointer.To(configDefaultIdentity), - }, - } + identityVal := cosmosdb.DatabaseAccountUpdateParameters{ + Identity: expandedIdentity, + } - // Update the database... - err = resourceCosmosDbAccountApiUpdate(client, ctx, id.ResourceGroup, id.Name, defaultIdentity, d) - if err != nil { - return fmt.Errorf("updating 'default_identity_type' %q: %+v", id, err) + // Update the database... + err = resourceCosmosDbAccountApiUpdate(client, ctx, *id, identityVal, d) + if err != nil { + return fmt.Errorf("updating 'identity' %q: %+v", id, err) + } + } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Identity' [NO CHANGE]") } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'DefaultIdentity' [NO CHANGE]") - } - } - if existing.DatabaseAccountGetProperties.Capabilities != nil { - if d.HasChange("capabilities") { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Capabilities'") + // NOTE: updateDefaultIdentity now has a default value of 'FirstPartyIdentity'... This value now gets + // triggered if the default value does not match the value in Azure... + // + // NOTE: When you change the 'Identity', the 'DefaultIdentity' will be set to 'undefined', so if you change + // the identity you must also update the 'DefaultIdentity' as well... + if updateDefaultIdentity || identityChanged { + // This will now return the default of 'FirstPartyIdentity' if it + // is not set in the config, which is correct. + configDefaultIdentity := d.Get("default_identity_type").(string) + if identityChanged { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DefaultIdentity' to %q because the 'Identity' was changed to %q", configDefaultIdentity, expandedIdentity.Type) + } else { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DefaultIdentity' to %q because 'default_identity_type' was changed", configDefaultIdentity) + } - newCapabilities := expandAzureRmCosmosDBAccountCapabilities(d) - updateParameters := documentdb.DatabaseAccountUpdateParameters{ - DatabaseAccountUpdateProperties: &documentdb.DatabaseAccountUpdateProperties{ - Capabilities: newCapabilities, - }, - } + // PATCH instead of PUT... + defaultIdentity := cosmosdb.DatabaseAccountUpdateParameters{ + Properties: &cosmosdb.DatabaseAccountUpdateProperties{ + DefaultIdentity: pointer.To(configDefaultIdentity), + }, + } - // Update Database 'capabilities'... - future, err := client.Update(ctx, id.ResourceGroup, id.Name, updateParameters) - if err != nil { - return fmt.Errorf("updating CosmosDB Account %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + // Update the database... + err = resourceCosmosDbAccountApiUpdate(client, ctx, *id, defaultIdentity, d) + if err != nil { + return fmt.Errorf("updating 'default_identity_type' %q: %+v", id, err) + } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'DefaultIdentity' [NO CHANGE]") } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the CosmosDB Account %q (Resource Group %q) to finish updating: %+v", id.Name, id.ResourceGroup, err) + if props.Capabilities != nil { + if d.HasChange("capabilities") { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Capabilities'") + + newCapabilities := expandAzureRmCosmosDBAccountCapabilities(d) + updateParameters := cosmosdb.DatabaseAccountUpdateParameters{ + Properties: &cosmosdb.DatabaseAccountUpdateProperties{ + Capabilities: newCapabilities, + }, + } + + // Update Database 'capabilities'... + if err := client.DatabaseAccountsUpdateThenPoll(ctx, *id, updateParameters); err != nil { + return fmt.Errorf("updating %q: %+v", id, err) + } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Capabilities' [NO CHANGE]") + } } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Capabilities' [NO CHANGE]") } } @@ -1288,222 +1278,232 @@ func resourceCosmosDbAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) } func resourceCosmosDbAccountRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Cosmos.DatabaseClient + client := meta.(*clients.Client).Cosmos.CosmosDBClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.DatabaseAccountID(d.Id()) + id, err := cosmosdb.ParseDatabaseAccountID(d.Id()) if err != nil { return err } - existing, err := client.Get(ctx, id.ResourceGroup, id.Name) + existing, err := client.DatabaseAccountsGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { + if response.WasNotFound(existing.HttpResponse) { d.SetId("") return nil } - return fmt.Errorf("retrieving CosmosDB Account %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("retrieving CosmosDB Account %q (Resource Group %q): %+v", id.DatabaseAccountName, id.DatabaseAccountName, err) } - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - d.Set("location", location.NormalizeNilable(existing.Location)) - d.Set("kind", string(existing.Kind)) - - identity, err := flattenAccountIdentity(existing.Identity) - if err != nil { - return fmt.Errorf("flattening `identity`: %+v", err) - } + d.Set("name", id.DatabaseAccountName) + d.Set("resource_group_name", id.ResourceGroupName) - if err := d.Set("identity", identity); err != nil { - return fmt.Errorf("setting `identity`: %+v", err) - } + if model := existing.Model; model != nil { + d.Set("location", location.NormalizeNilable(model.Location)) + d.Set("kind", pointer.From(model.Kind)) - if props := existing.DatabaseAccountGetProperties; props != nil { - d.Set("offer_type", string(props.DatabaseAccountOfferType)) + identity, err := identity.FlattenLegacySystemAndUserAssignedMap(model.Identity) + if err != nil { + return fmt.Errorf("flattening `identity`: %+v", err) + } - if features.FourPointOhBeta() { - d.Set("ip_range_filter", common.CosmosDBIpRulesToIpRangeFilter(props.IPRules)) - } else { - d.Set("ip_range_filter", common.CosmosDBIpRulesToIpRangeFilterThreePointOh(props.IPRules)) + if err := d.Set("identity", identity); err != nil { + return fmt.Errorf("setting `identity`: %+v", err) } - d.Set("endpoint", props.DocumentEndpoint) - d.Set("enable_free_tier", props.EnableFreeTier) - d.Set("analytical_storage_enabled", props.EnableAnalyticalStorage) - d.Set("public_network_access_enabled", props.PublicNetworkAccess == documentdb.PublicNetworkAccessEnabled) - d.Set("default_identity_type", props.DefaultIdentity) - d.Set("create_mode", props.CreateMode) + if props := model.Properties; props != nil { + d.Set("offer_type", pointer.From(props.DatabaseAccountOfferType)) - if v := existing.IsVirtualNetworkFilterEnabled; v != nil { - d.Set("is_virtual_network_filter_enabled", props.IsVirtualNetworkFilterEnabled) - } + if features.FourPointOhBeta() { + d.Set("ip_range_filter", common.CosmosDBIpRulesToIpRangeFilter(props.IPRules)) + } else { + d.Set("ip_range_filter", common.CosmosDBIpRulesToIpRangeFilterThreePointOh(props.IPRules)) + } - if v := existing.EnableAutomaticFailover; v != nil { - d.Set("enable_automatic_failover", props.EnableAutomaticFailover) - } + d.Set("endpoint", props.DocumentEndpoint) + d.Set("enable_free_tier", props.EnableFreeTier) + d.Set("analytical_storage_enabled", props.EnableAnalyticalStorage) + d.Set("public_network_access_enabled", pointer.From(props.PublicNetworkAccess) == cosmosdb.PublicNetworkAccessEnabled) + d.Set("default_identity_type", props.DefaultIdentity) + d.Set("create_mode", props.CreateMode) - if v := existing.KeyVaultKeyURI; v != nil { - d.Set("key_vault_key_id", props.KeyVaultKeyURI) - } + if v := props.IsVirtualNetworkFilterEnabled; v != nil { + d.Set("is_virtual_network_filter_enabled", props.IsVirtualNetworkFilterEnabled) + } - if v := existing.EnableMultipleWriteLocations; v != nil { - d.Set("enable_multiple_write_locations", props.EnableMultipleWriteLocations) - } + if v := props.EnableAutomaticFailover; v != nil { + d.Set("enable_automatic_failover", props.EnableAutomaticFailover) + } - if err := d.Set("analytical_storage", flattenCosmosDBAccountAnalyticalStorageConfiguration(props.AnalyticalStorageConfiguration)); err != nil { - return fmt.Errorf("setting `analytical_storage`: %+v", err) - } + if v := props.KeyVaultKeyUri; v != nil { + d.Set("key_vault_key_id", props.KeyVaultKeyUri) + } - if err := d.Set("capacity", flattenCosmosDBAccountCapacity(props.Capacity)); err != nil { - return fmt.Errorf("setting `capacity`: %+v", err) - } + if v := props.EnableMultipleWriteLocations; v != nil { + d.Set("enable_multiple_write_locations", props.EnableMultipleWriteLocations) + } - if err := d.Set("restore", flattenCosmosdbAccountRestoreParameters(props.RestoreParameters)); err != nil { - return fmt.Errorf("setting `restore`: %+v", err) - } + if err := d.Set("analytical_storage", flattenCosmosDBAccountAnalyticalStorageConfiguration(props.AnalyticalStorageConfiguration)); err != nil { + return fmt.Errorf("setting `analytical_storage`: %+v", err) + } - if err = d.Set("consistency_policy", flattenAzureRmCosmosDBAccountConsistencyPolicy(props.ConsistencyPolicy)); err != nil { - return fmt.Errorf("setting CosmosDB Account %q `consistency_policy` (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) - } + if err := d.Set("capacity", flattenCosmosDBAccountCapacity(props.Capacity)); err != nil { + return fmt.Errorf("setting `capacity`: %+v", err) + } - if err = d.Set("geo_location", flattenAzureRmCosmosDBAccountGeoLocations(props)); err != nil { - return fmt.Errorf("setting `geo_location`: %+v", err) - } + if err := d.Set("restore", flattenCosmosdbAccountRestoreParameters(props.RestoreParameters)); err != nil { + return fmt.Errorf("setting `restore`: %+v", err) + } - if err = d.Set("capabilities", flattenAzureRmCosmosDBAccountCapabilities(props.Capabilities)); err != nil { - return fmt.Errorf("setting `capabilities`: %+v", err) - } + if err = d.Set("consistency_policy", flattenAzureRmCosmosDBAccountConsistencyPolicy(props.ConsistencyPolicy)); err != nil { + return fmt.Errorf("setting CosmosDB Account %q `consistency_policy` (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err) + } - if err = d.Set("virtual_network_rule", flattenAzureRmCosmosDBAccountVirtualNetworkRules(props.VirtualNetworkRules)); err != nil { - return fmt.Errorf("setting `virtual_network_rule`: %+v", err) - } + if err = d.Set("geo_location", flattenAzureRmCosmosDBAccountGeoLocations(props)); err != nil { + return fmt.Errorf("setting `geo_location`: %+v", err) + } - d.Set("access_key_metadata_writes_enabled", !*props.DisableKeyBasedMetadataWriteAccess) - if apiProps := props.APIProperties; apiProps != nil { - d.Set("mongo_server_version", apiProps.ServerVersion) - } - d.Set("network_acl_bypass_for_azure_services", props.NetworkACLBypass == documentdb.NetworkACLBypassAzureServices) - d.Set("network_acl_bypass_ids", utils.FlattenStringSlice(props.NetworkACLBypassResourceIds)) + if err = d.Set("capabilities", flattenAzureRmCosmosDBAccountCapabilities(props.Capabilities)); err != nil { + return fmt.Errorf("setting `capabilities`: %+v", err) + } - if v := existing.DisableLocalAuth; v != nil { - d.Set("local_authentication_disabled", props.DisableLocalAuth) - } + if err = d.Set("virtual_network_rule", flattenAzureRmCosmosDBAccountVirtualNetworkRules(props.VirtualNetworkRules)); err != nil { + return fmt.Errorf("setting `virtual_network_rule`: %+v", err) + } - policy, err := flattenCosmosdbAccountBackup(props.BackupPolicy) - if err != nil { - return err - } + d.Set("access_key_metadata_writes_enabled", !*props.DisableKeyBasedMetadataWriteAccess) + if apiProps := props.ApiProperties; apiProps != nil { + d.Set("mongo_server_version", apiProps.ServerVersion) + } + d.Set("network_acl_bypass_for_azure_services", pointer.From(props.NetworkAclBypass) == cosmosdb.NetworkAclBypassAzureServices) + d.Set("network_acl_bypass_ids", utils.FlattenStringSlice(props.NetworkAclBypassResourceIds)) - if err = d.Set("backup", policy); err != nil { - return fmt.Errorf("setting `backup`: %+v", err) - } + if v := props.DisableLocalAuth; v != nil { + d.Set("local_authentication_disabled", props.DisableLocalAuth) + } - d.Set("cors_rule", common.FlattenCosmosCorsRule(props.Cors)) - } + policy, err := flattenCosmosdbAccountBackup(props.BackupPolicy) + if err != nil { + return err + } - readEndpoints := make([]string, 0) - if p := existing.ReadLocations; p != nil { - for _, l := range *p { - if l.DocumentEndpoint == nil { - continue + if err = d.Set("backup", policy); err != nil { + return fmt.Errorf("setting `backup`: %+v", err) } - readEndpoints = append(readEndpoints, *l.DocumentEndpoint) - } - } - if err := d.Set("read_endpoints", readEndpoints); err != nil { - return fmt.Errorf("setting `read_endpoints`: %s", err) - } + d.Set("cors_rule", common.FlattenCosmosCorsRule(props.Cors)) - writeEndpoints := make([]string, 0) - if p := existing.WriteLocations; p != nil { - for _, l := range *p { - if l.DocumentEndpoint == nil { - continue + readEndpoints := make([]string, 0) + if p := props.ReadLocations; p != nil { + for _, l := range *p { + if l.DocumentEndpoint == nil { + continue + } + + readEndpoints = append(readEndpoints, *l.DocumentEndpoint) + } + } + if err := d.Set("read_endpoints", readEndpoints); err != nil { + return fmt.Errorf("setting `read_endpoints`: %s", err) + } + + writeEndpoints := make([]string, 0) + if p := props.WriteLocations; p != nil { + for _, l := range *p { + if l.DocumentEndpoint == nil { + continue + } + + writeEndpoints = append(writeEndpoints, *l.DocumentEndpoint) + } } + if err := d.Set("write_endpoints", writeEndpoints); err != nil { + return fmt.Errorf("setting `write_endpoints`: %s", err) + } + } - writeEndpoints = append(writeEndpoints, *l.DocumentEndpoint) + if err := tags.FlattenAndSet(d, model.Tags); err != nil { + return err } } - if err := d.Set("write_endpoints", writeEndpoints); err != nil { - return fmt.Errorf("setting `write_endpoints`: %s", err) - } // ListKeys returns a data structure containing a DatabaseAccountListReadOnlyKeysResult pointer // implying that it also returns the read only keys, however this appears to not be the case - keys, err := client.ListKeys(ctx, id.ResourceGroup, id.Name) + keys, err := client.DatabaseAccountsListKeys(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(keys.Response) { - log.Printf("[DEBUG] Keys were not found for CosmosDB Account %q (Resource Group %q) - removing from state!", id.Name, id.ResourceGroup) + if response.WasNotFound(keys.HttpResponse) { + log.Printf("[DEBUG] Keys were not found for CosmosDB Account %q (Resource Group %q) - removing from state!", id.DatabaseAccountName, id.ResourceGroupName) d.SetId("") return nil } - return fmt.Errorf("[ERROR] Unable to List Write keys for CosmosDB Account %s: %s", id.Name, err) + return fmt.Errorf("[ERROR] Unable to List Write keys for CosmosDB Account %s: %s", id.DatabaseAccountName, err) } - d.Set("primary_key", keys.PrimaryMasterKey) - d.Set("secondary_key", keys.SecondaryMasterKey) - readonlyKeys, err := client.ListReadOnlyKeys(ctx, id.ResourceGroup, id.Name) + if model := keys.Model; model != nil { + d.Set("primary_key", model.PrimaryMasterKey) + d.Set("secondary_key", model.SecondaryMasterKey) + } + + readonlyKeys, err := client.DatabaseAccountsListReadOnlyKeys(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(keys.Response) { - log.Printf("[DEBUG] Read Only Keys were not found for CosmosDB Account %q (Resource Group %q) - removing from state!", id.Name, id.ResourceGroup) + if response.WasNotFound(keys.HttpResponse) { + log.Printf("[DEBUG] Read Only Keys were not found for CosmosDB Account %q (Resource Group %q) - removing from state!", id.DatabaseAccountName, id.ResourceGroupName) d.SetId("") return nil } - return fmt.Errorf("[ERROR] Unable to List read-only keys for CosmosDB Account %s: %s", id.Name, err) + return fmt.Errorf("[ERROR] Unable to List read-only keys for CosmosDB Account %s: %s", id.DatabaseAccountName, err) + } + + if model := readonlyKeys.Model; model != nil { + d.Set("primary_readonly_key", model.PrimaryReadonlyMasterKey) + d.Set("secondary_readonly_key", model.SecondaryReadonlyMasterKey) } - d.Set("primary_readonly_key", readonlyKeys.PrimaryReadonlyMasterKey) - d.Set("secondary_readonly_key", readonlyKeys.SecondaryReadonlyMasterKey) - connStringResp, err := client.ListConnectionStrings(ctx, id.ResourceGroup, id.Name) + connStringResp, err := client.DatabaseAccountsListConnectionStrings(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(keys.Response) { - log.Printf("[DEBUG] Connection Strings were not found for CosmosDB Account %q (Resource Group %q) - removing from state!", id.Name, id.ResourceGroup) + if response.WasNotFound(keys.HttpResponse) { + log.Printf("[DEBUG] Connection Strings were not found for CosmosDB Account %q (Resource Group %q) - removing from state!", id.DatabaseAccountName, id.ResourceGroupName) d.SetId("") return nil } - return fmt.Errorf("[ERROR] Unable to List connection strings for CosmosDB Account %s: %s", id.Name, err) + return fmt.Errorf("[ERROR] Unable to List connection strings for CosmosDB Account %s: %s", id.DatabaseAccountName, err) } - var connStrings []string - if connStringResp.ConnectionStrings != nil { - connStrings = make([]string, len(*connStringResp.ConnectionStrings)) - for i, v := range *connStringResp.ConnectionStrings { - connStrings[i] = *v.ConnectionString - if propertyName, propertyExists := connStringPropertyMap[*v.Description]; propertyExists { - d.Set(propertyName, v.ConnectionString) // lintignore:R001 + if model := connStringResp.Model; model != nil { + var connStrings []string + if model.ConnectionStrings != nil { + connStrings = make([]string, len(*model.ConnectionStrings)) + for i, v := range *model.ConnectionStrings { + connStrings[i] = *v.ConnectionString + if propertyName, propertyExists := connStringPropertyMap[*v.Description]; propertyExists { + d.Set(propertyName, v.ConnectionString) // lintignore:R001 + } } } - } - d.Set("connection_strings", connStrings) + d.Set("connection_strings", connStrings) + } - return tags.FlattenAndSet(d, existing.Tags) + return nil } func resourceCosmosDbAccountDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Cosmos.DatabaseClient + client := meta.(*clients.Client).Cosmos.CosmosDBClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.DatabaseAccountID(d.Id()) + id, err := cosmosdb.ParseDatabaseAccountID(d.Id()) if err != nil { return err } - future, err := client.Delete(ctx, id.ResourceGroup, id.Name) - if err != nil { - return fmt.Errorf("deleting CosmosDB Account %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) - } - - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for deletion of %q: %+v", id, err) + if err := client.DatabaseAccountsDeleteThenPoll(ctx, *id); err != nil { + return fmt.Errorf("deleting %q: %+v", id, err) } // the SDK now will return a `WasNotFound` response even when still deleting @@ -1513,9 +1513,9 @@ func resourceCosmosDbAccountDelete(d *pluginsdk.ResourceData, meta interface{}) MinTimeout: 30 * time.Second, Timeout: d.Timeout(pluginsdk.TimeoutDelete), Refresh: func() (interface{}, string, error) { - resp, err2 := client.Get(ctx, id.ResourceGroup, id.Name) + resp, err2 := client.DatabaseAccountsGet(ctx, *id) if err2 != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return resp, "NotFound", nil } return nil, "", err2 @@ -1526,20 +1526,16 @@ func resourceCosmosDbAccountDelete(d *pluginsdk.ResourceData, meta interface{}) } if _, err = stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for CosmosDB Account %q (Resource Group %q) to be deleted: %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("waiting for CosmosDB Account %q (Resource Group %q) to be deleted: %+v", id.DatabaseAccountName, id.ResourceGroupName, err) } return nil } -func resourceCosmosDbAccountApiUpdate(client *documentdb.DatabaseAccountsClient, ctx context.Context, resourceGroup string, name string, account documentdb.DatabaseAccountUpdateParameters, d *pluginsdk.ResourceData) error { - future, err := client.Update(ctx, resourceGroup, name, account) +func resourceCosmosDbAccountApiUpdate(client *cosmosdb.CosmosDBClient, ctx context.Context, id cosmosdb.DatabaseAccountId, account cosmosdb.DatabaseAccountUpdateParameters, d *pluginsdk.ResourceData) error { + err := client.DatabaseAccountsUpdateThenPoll(ctx, id, account) if err != nil { - return fmt.Errorf("updating CosmosDB Account %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the CosmosDB Account %q (Resource Group %q) to finish creating/updating: %+v", name, resourceGroup, err) + return fmt.Errorf("updating %q: %+v", id, err) } stateConf := &pluginsdk.StateChangeConf{ @@ -1548,9 +1544,9 @@ func resourceCosmosDbAccountApiUpdate(client *documentdb.DatabaseAccountsClient, MinTimeout: 15 * time.Second, ContinuousTargetOccurence: 2, Refresh: func() (interface{}, string, error) { - resp, err2 := client.Get(ctx, resourceGroup, name) - if err2 != nil || resp.StatusCode == http.StatusNotFound { - return nil, "", fmt.Errorf("reading CosmosDB Account %q after update (Resource Group %q): %+v", name, resourceGroup, err2) + resp, err2 := client.DatabaseAccountsGet(ctx, id) + if err2 != nil || resp.HttpResponse == nil || resp.HttpResponse.StatusCode == http.StatusNotFound { + return nil, "", fmt.Errorf("reading CosmosDB Account %q after update (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err2) } status := "Succeeded" @@ -1562,20 +1558,15 @@ func resourceCosmosDbAccountApiUpdate(client *documentdb.DatabaseAccountsClient, _, err = stateConf.WaitForStateContext(ctx) if err != nil { - return fmt.Errorf("waiting for the CosmosDB Account %q (Resource Group %q) to update: %+v", name, resourceGroup, err) + return fmt.Errorf("waiting for the CosmosDB Account %q (Resource Group %q) to update: %+v", id.DatabaseAccountName, id.ResourceGroupName, err) } return nil } -func resourceCosmosDbAccountApiCreateOrUpdate(client *documentdb.DatabaseAccountsClient, ctx context.Context, resourceGroup string, name string, account documentdb.DatabaseAccountCreateUpdateParameters, d *pluginsdk.ResourceData) error { - future, err := client.CreateOrUpdate(ctx, resourceGroup, name, account) - if err != nil { - return fmt.Errorf("creating/updating CosmosDB Account %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the CosmosDB Account %q (Resource Group %q) to finish creating/updating: %+v", name, resourceGroup, err) +func resourceCosmosDbAccountApiCreateOrUpdate(client *cosmosdb.CosmosDBClient, ctx context.Context, id cosmosdb.DatabaseAccountId, account cosmosdb.DatabaseAccountCreateUpdateParameters, d *pluginsdk.ResourceData) error { + if err := client.DatabaseAccountsCreateOrUpdateThenPoll(ctx, id, account); err != nil { + return fmt.Errorf("creating/updating %q: %+v", id, err) } // if a replication location is added or removed it can take some time to provision @@ -1585,35 +1576,38 @@ func resourceCosmosDbAccountApiCreateOrUpdate(client *documentdb.DatabaseAccount MinTimeout: 15 * time.Second, Delay: 30 * time.Second, // required because it takes some time before the 'creating' location shows up Refresh: func() (interface{}, string, error) { - resp, err2 := client.Get(ctx, resourceGroup, name) - if err2 != nil || resp.StatusCode == http.StatusNotFound { - return nil, "", fmt.Errorf("reading CosmosDB Account %q after create/update (Resource Group %q): %+v", name, resourceGroup, err2) + resp, err2 := client.DatabaseAccountsGet(ctx, id) + if err2 != nil || resp.HttpResponse == nil || resp.HttpResponse.StatusCode == http.StatusNotFound { + return nil, "", fmt.Errorf("reading CosmosDB Account %q after create/update (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err2) } status := "Succeeded" - if props := resp.DatabaseAccountGetProperties; props != nil { - var locations []documentdb.Location - if props.ReadLocations != nil { - locations = append(locations, *props.ReadLocations...) - } - if props.WriteLocations != nil { - locations = append(locations, *props.WriteLocations...) - } + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + var locations []cosmosdb.Location - for _, l := range locations { - if status = *l.ProvisioningState; status == "Creating" || status == "Updating" || status == "Deleting" { - break // return the first non successful status. + if props.ReadLocations != nil { + locations = append(locations, *props.ReadLocations...) + } + if props.WriteLocations != nil { + locations = append(locations, *props.WriteLocations...) } - } - for _, desiredLocation := range *account.Locations { - for index, l := range locations { - if azure.NormalizeLocation(*desiredLocation.LocationName) == azure.NormalizeLocation(*l.LocationName) { - break + for _, l := range locations { + if status = *l.ProvisioningState; status == "Creating" || status == "Updating" || status == "Deleting" { + break // return the first non successful status. } + } + + for _, desiredLocation := range *props.Locations { + for index, l := range locations { + if azure.NormalizeLocation(*desiredLocation.LocationName) == azure.NormalizeLocation(*l.LocationName) { + break + } - if (index + 1) == len(locations) { - return resp, "Updating", nil + if (index + 1) == len(locations) { + return resp, "Updating", nil + } } } } @@ -1629,15 +1623,15 @@ func resourceCosmosDbAccountApiCreateOrUpdate(client *documentdb.DatabaseAccount stateConf.Timeout = d.Timeout(pluginsdk.TimeoutUpdate) } - _, err = stateConf.WaitForStateContext(ctx) + _, err := stateConf.WaitForStateContext(ctx) if err != nil { - return fmt.Errorf("waiting for the CosmosDB Account %q (Resource Group %q) to provision: %+v", name, resourceGroup, err) + return fmt.Errorf("waiting for the CosmosDB Account %q (Resource Group %q) to provision: %+v", id.DatabaseAccountName, id.ResourceGroupName, err) } return nil } -func expandAzureRmCosmosDBAccountConsistencyPolicy(d *pluginsdk.ResourceData) *documentdb.ConsistencyPolicy { +func expandAzureRmCosmosDBAccountConsistencyPolicy(d *pluginsdk.ResourceData) *cosmosdb.ConsistencyPolicy { i := d.Get("consistency_policy").([]interface{}) if len(i) == 0 || i[0] == nil { return nil @@ -1645,8 +1639,8 @@ func expandAzureRmCosmosDBAccountConsistencyPolicy(d *pluginsdk.ResourceData) *d input := i[0].(map[string]interface{}) consistencyLevel := input["consistency_level"].(string) - policy := documentdb.ConsistencyPolicy{ - DefaultConsistencyLevel: documentdb.DefaultConsistencyLevel(consistencyLevel), + policy := cosmosdb.ConsistencyPolicy{ + DefaultConsistencyLevel: cosmosdb.DefaultConsistencyLevel(consistencyLevel), } if stalenessPrefix, ok := input["max_staleness_prefix"].(int); ok { @@ -1659,20 +1653,20 @@ func expandAzureRmCosmosDBAccountConsistencyPolicy(d *pluginsdk.ResourceData) *d if maxInterval == 0 { maxInterval = 5 } - policy.MaxIntervalInSeconds = utils.Int32(int32(maxInterval)) + policy.MaxIntervalInSeconds = utils.Int64(int64(maxInterval)) } return &policy } -func expandAzureRmCosmosDBAccountGeoLocations(d *pluginsdk.ResourceData) ([]documentdb.Location, error) { - locations := make([]documentdb.Location, 0) +func expandAzureRmCosmosDBAccountGeoLocations(d *pluginsdk.ResourceData) ([]cosmosdb.Location, error) { + locations := make([]cosmosdb.Location, 0) for _, l := range d.Get("geo_location").(*pluginsdk.Set).List() { data := l.(map[string]interface{}) - location := documentdb.Location{ + location := cosmosdb.Location{ LocationName: pointer.To(azure.NormalizeLocation(data["location"].(string))), - FailoverPriority: utils.Int32(int32(data["failover_priority"].(int))), + FailoverPriority: utils.Int64(int64(data["failover_priority"].(int))), IsZoneRedundant: pointer.FromBool(data["zone_redundant"].(bool)), } @@ -1712,26 +1706,26 @@ func expandAzureRmCosmosDBAccountGeoLocations(d *pluginsdk.ResourceData) ([]docu return locations, nil } -func expandAzureRmCosmosDBAccountCapabilities(d *pluginsdk.ResourceData) *[]documentdb.Capability { +func expandAzureRmCosmosDBAccountCapabilities(d *pluginsdk.ResourceData) *[]cosmosdb.Capability { capabilities := d.Get("capabilities").(*pluginsdk.Set).List() - s := make([]documentdb.Capability, 0) + s := make([]cosmosdb.Capability, 0) for _, c := range capabilities { m := c.(map[string]interface{}) - s = append(s, documentdb.Capability{Name: pointer.To(m["name"].(string))}) + s = append(s, cosmosdb.Capability{Name: pointer.To(m["name"].(string))}) } return &s } -func expandAzureRmCosmosDBAccountVirtualNetworkRules(d *pluginsdk.ResourceData) *[]documentdb.VirtualNetworkRule { +func expandAzureRmCosmosDBAccountVirtualNetworkRules(d *pluginsdk.ResourceData) *[]cosmosdb.VirtualNetworkRule { virtualNetworkRules := d.Get("virtual_network_rule").(*pluginsdk.Set).List() - s := make([]documentdb.VirtualNetworkRule, len(virtualNetworkRules)) + s := make([]cosmosdb.VirtualNetworkRule, len(virtualNetworkRules)) for i, r := range virtualNetworkRules { m := r.(map[string]interface{}) - s[i] = documentdb.VirtualNetworkRule{ - ID: pointer.To(m["id"].(string)), + s[i] = cosmosdb.VirtualNetworkRule{ + Id: pointer.To(m["id"].(string)), IgnoreMissingVNetServiceEndpoint: pointer.FromBool(m["ignore_missing_vnet_service_endpoint"].(bool)), } } @@ -1739,7 +1733,7 @@ func expandAzureRmCosmosDBAccountVirtualNetworkRules(d *pluginsdk.ResourceData) return &s } -func flattenAzureRmCosmosDBAccountConsistencyPolicy(policy *documentdb.ConsistencyPolicy) []interface{} { +func flattenAzureRmCosmosDBAccountConsistencyPolicy(policy *cosmosdb.ConsistencyPolicy) []interface{} { result := map[string]interface{}{} result["consistency_level"] = string(policy.DefaultConsistencyLevel) if policy.MaxIntervalInSeconds != nil { @@ -1752,7 +1746,7 @@ func flattenAzureRmCosmosDBAccountConsistencyPolicy(policy *documentdb.Consisten return []interface{}{result} } -func flattenAzureRmCosmosDBAccountGeoLocations(account *documentdb.DatabaseAccountGetProperties) *pluginsdk.Set { +func flattenAzureRmCosmosDBAccountGeoLocations(account *cosmosdb.DatabaseAccountGetProperties) *pluginsdk.Set { locationSet := pluginsdk.Set{ F: resourceAzureRMCosmosDBAccountGeoLocationHash, } @@ -1761,11 +1755,11 @@ func flattenAzureRmCosmosDBAccountGeoLocations(account *documentdb.DatabaseAccou } for _, l := range *account.FailoverPolicies { - if l.ID == nil { + if l.Id == nil { continue } - id := *l.ID + id := *l.Id lb := map[string]interface{}{ "id": id, "location": location.NormalizeNilable(l.LocationName), @@ -1780,13 +1774,13 @@ func flattenAzureRmCosmosDBAccountGeoLocations(account *documentdb.DatabaseAccou return &locationSet } -func findZoneRedundant(locations *[]documentdb.Location, id string) bool { +func findZoneRedundant(locations *[]cosmosdb.Location, id string) bool { if locations == nil { return false } for _, location := range *locations { - if location.ID != nil && *location.ID == id { + if location.Id != nil && *location.Id == id { if location.IsZoneRedundant != nil { return *location.IsZoneRedundant } @@ -1808,7 +1802,7 @@ func isServerlessCapacityMode(accResp documentdb.DatabaseAccountGetResults) bool return false } -func flattenAzureRmCosmosDBAccountCapabilities(capabilities *[]documentdb.Capability) *pluginsdk.Set { +func flattenAzureRmCosmosDBAccountCapabilities(capabilities *[]cosmosdb.Capability) *pluginsdk.Set { s := pluginsdk.Set{ F: resourceAzureRMCosmosDBAccountCapabilitiesHash, } @@ -1825,7 +1819,7 @@ func flattenAzureRmCosmosDBAccountCapabilities(capabilities *[]documentdb.Capabi return &s } -func flattenAzureRmCosmosDBAccountVirtualNetworkRules(rules *[]documentdb.VirtualNetworkRule) *pluginsdk.Set { +func flattenAzureRmCosmosDBAccountVirtualNetworkRules(rules *[]cosmosdb.VirtualNetworkRule) *pluginsdk.Set { results := pluginsdk.Set{ F: resourceAzureRMCosmosDBAccountVirtualNetworkRuleHash, } @@ -1833,7 +1827,7 @@ func flattenAzureRmCosmosDBAccountVirtualNetworkRules(rules *[]documentdb.Virtua if rules != nil { for _, r := range *rules { rule := map[string]interface{}{ - "id": *r.ID, + "id": *r.Id, "ignore_missing_vnet_service_endpoint": *r.IgnoreMissingVNetServiceEndpoint, } results.Add(rule) @@ -1876,14 +1870,14 @@ func resourceAzureRMCosmosDBAccountVirtualNetworkRuleHash(v interface{}) int { return pluginsdk.HashString(buf.String()) } -func expandCosmosdbAccountBackup(input []interface{}, backupHasChange bool, createMode string) (documentdb.BasicBackupPolicy, error) { +func expandCosmosdbAccountBackup(input []interface{}, backupHasChange bool, createMode string) (cosmosdb.BackupPolicy, error) { if len(input) == 0 || input[0] == nil { return nil, nil } attr := input[0].(map[string]interface{}) switch attr["type"].(string) { - case string(documentdb.TypeContinuous): + case string(cosmosdb.BackupPolicyTypeContinuous): if v := attr["interval_in_minutes"].(int); v != 0 && !backupHasChange { return nil, fmt.Errorf("`interval_in_minutes` can not be set when `type` in `backup` is `Continuous`") } @@ -1893,21 +1887,18 @@ func expandCosmosdbAccountBackup(input []interface{}, backupHasChange bool, crea if v := attr["storage_redundancy"].(string); v != "" && !backupHasChange { return nil, fmt.Errorf("`storage_redundancy` can not be set when `type` in `backup` is `Continuous`") } - return documentdb.ContinuousModeBackupPolicy{ - Type: documentdb.TypeContinuous, - }, nil + return cosmosdb.ContinuousModeBackupPolicy{}, nil - case string(documentdb.TypePeriodic): + case string(cosmosdb.BackupPolicyTypePeriodic): if createMode != "" { return nil, fmt.Errorf("`create_mode` only works when `backup.type` is `Continuous`") } - return documentdb.PeriodicModeBackupPolicy{ - Type: documentdb.TypePeriodic, - PeriodicModeProperties: &documentdb.PeriodicModeProperties{ - BackupIntervalInMinutes: utils.Int32(int32(attr["interval_in_minutes"].(int))), - BackupRetentionIntervalInHours: utils.Int32(int32(attr["retention_in_hours"].(int))), - BackupStorageRedundancy: documentdb.BackupStorageRedundancy(attr["storage_redundancy"].(string)), + return cosmosdb.PeriodicModeBackupPolicy{ + PeriodicModeProperties: &cosmosdb.PeriodicModeProperties{ + BackupIntervalInMinutes: utils.Int64(int64(attr["interval_in_minutes"].(int))), + BackupRetentionIntervalInHours: utils.Int64(int64(attr["retention_in_hours"].(int))), + BackupStorageRedundancy: pointer.To(cosmosdb.BackupStorageRedundancy(attr["storage_redundancy"].(string))), }, }, nil @@ -1916,21 +1907,21 @@ func expandCosmosdbAccountBackup(input []interface{}, backupHasChange bool, crea } } -func flattenCosmosdbAccountBackup(input documentdb.BasicBackupPolicy) ([]interface{}, error) { +func flattenCosmosdbAccountBackup(input cosmosdb.BackupPolicy) ([]interface{}, error) { if input == nil { return []interface{}{}, nil } switch input.(type) { - case documentdb.ContinuousModeBackupPolicy: + case cosmosdb.ContinuousModeBackupPolicy: return []interface{}{ map[string]interface{}{ - "type": string(documentdb.TypeContinuous), + "type": string(cosmosdb.BackupPolicyTypeContinuous), }, }, nil - case documentdb.PeriodicModeBackupPolicy: - policy, ok := input.AsPeriodicModeBackupPolicy() + case cosmosdb.PeriodicModeBackupPolicy: + policy, ok := input.(cosmosdb.PeriodicModeBackupPolicy) if !ok { return nil, fmt.Errorf("can not transit %+v into `backup` of `type` `Periodic`", input) } @@ -1941,13 +1932,13 @@ func flattenCosmosdbAccountBackup(input documentdb.BasicBackupPolicy) ([]interfa if v := policy.PeriodicModeProperties.BackupRetentionIntervalInHours; v != nil { retention = int(*v) } - var storageRedundancy documentdb.BackupStorageRedundancy - if policy.PeriodicModeProperties.BackupStorageRedundancy != "" { - storageRedundancy = policy.PeriodicModeProperties.BackupStorageRedundancy + var storageRedundancy cosmosdb.BackupStorageRedundancy + if policy.PeriodicModeProperties.BackupStorageRedundancy != nil { + storageRedundancy = pointer.From(policy.PeriodicModeProperties.BackupStorageRedundancy) } return []interface{}{ map[string]interface{}{ - "type": string(documentdb.TypePeriodic), + "type": string(cosmosdb.BackupPolicyTypePeriodic), "interval_in_minutes": interval, "retention_in_hours": retention, "storage_redundancy": storageRedundancy, @@ -1959,101 +1950,38 @@ func flattenCosmosdbAccountBackup(input documentdb.BasicBackupPolicy) ([]interfa } } -func expandAccountIdentity(input []interface{}) (*documentdb.ManagedServiceIdentity, error) { - expanded, err := identity.ExpandSystemAndUserAssignedMap(input) - if err != nil { - return nil, err - } - - out := documentdb.ManagedServiceIdentity{ - Type: documentdb.ResourceIdentityType(string(expanded.Type)), - } - - if expanded.Type == identity.TypeUserAssigned || expanded.Type == identity.TypeSystemAssignedUserAssigned { - out.UserAssignedIdentities = make(map[string]*documentdb.ManagedServiceIdentityUserAssignedIdentitiesValue) - for k := range expanded.IdentityIds { - out.UserAssignedIdentities[k] = &documentdb.ManagedServiceIdentityUserAssignedIdentitiesValue{} - } - } - - return &out, nil -} - -func flattenAccountIdentity(input *documentdb.ManagedServiceIdentity) (*[]interface{}, error) { - var transform *identity.SystemAndUserAssignedMap - - if input != nil { - transform = pointer.To(identity.SystemAndUserAssignedMap{ - Type: identity.Type(string(input.Type)), - IdentityIds: make(map[string]identity.UserAssignedIdentityDetails), - }) - - if input.PrincipalID != nil { - transform.PrincipalId = pointer.From(input.PrincipalID) - } - - if input.TenantID != nil { - transform.TenantId = pointer.From(input.TenantID) - } - - if input.UserAssignedIdentities != nil { - log.Printf("[DEBUG] input.UserAssignedIdentities ***NOT NULL***") - - for k, v := range input.UserAssignedIdentities { - log.Printf("[DEBUG] *** Parsing input.UserAssignedIdentities") - details := identity.UserAssignedIdentityDetails{} - - if v.ClientID != nil { - details.ClientId = v.ClientID - } - - if v.PrincipalID != nil { - details.PrincipalId = v.PrincipalID - } - - transform.IdentityIds[k] = details - - log.Printf("[DEBUG] *** Details: {ClientId: %q, PrincipalId: %q}", pointer.From(details.ClientId), pointer.From(details.PrincipalId)) - log.Printf("[DEBUG] *** Current 'transform': %+v", transform) - } - } - } - - return identity.FlattenSystemAndUserAssignedMap(transform) -} - -func expandCosmosDBAccountAnalyticalStorageConfiguration(input []interface{}) *documentdb.AnalyticalStorageConfiguration { +func expandCosmosDBAccountAnalyticalStorageConfiguration(input []interface{}) *cosmosdb.AnalyticalStorageConfiguration { if len(input) == 0 { return nil } v := input[0].(map[string]interface{}) - return &documentdb.AnalyticalStorageConfiguration{ - SchemaType: documentdb.AnalyticalStorageSchemaType(v["schema_type"].(string)), + return &cosmosdb.AnalyticalStorageConfiguration{ + SchemaType: pointer.To(cosmosdb.AnalyticalStorageSchemaType(v["schema_type"].(string))), } } -func expandCosmosDBAccountCapacity(input []interface{}) *documentdb.Capacity { +func expandCosmosDBAccountCapacity(input []interface{}) *cosmosdb.Capacity { if len(input) == 0 { return nil } v := input[0].(map[string]interface{}) - return &documentdb.Capacity{ - TotalThroughputLimit: utils.Int32(int32(v["total_throughput_limit"].(int))), + return &cosmosdb.Capacity{ + TotalThroughputLimit: utils.Int64(int64(v["total_throughput_limit"].(int))), } } -func flattenCosmosDBAccountAnalyticalStorageConfiguration(input *documentdb.AnalyticalStorageConfiguration) []interface{} { +func flattenCosmosDBAccountAnalyticalStorageConfiguration(input *cosmosdb.AnalyticalStorageConfiguration) []interface{} { if input == nil { return make([]interface{}, 0) } - var schemaType documentdb.AnalyticalStorageSchemaType - if input.SchemaType != "" { - schemaType = input.SchemaType + var schemaType cosmosdb.AnalyticalStorageSchemaType + if input.SchemaType != nil { + schemaType = pointer.From(input.SchemaType) } return []interface{}{ @@ -2063,12 +1991,12 @@ func flattenCosmosDBAccountAnalyticalStorageConfiguration(input *documentdb.Anal } } -func flattenCosmosDBAccountCapacity(input *documentdb.Capacity) []interface{} { +func flattenCosmosDBAccountCapacity(input *cosmosdb.Capacity) []interface{} { if input == nil { return make([]interface{}, 0) } - var totalThroughputLimit int32 + var totalThroughputLimit int64 if input.TotalThroughputLimit != nil { totalThroughputLimit = *input.TotalThroughputLimit } @@ -2080,29 +2008,31 @@ func flattenCosmosDBAccountCapacity(input *documentdb.Capacity) []interface{} { } } -func expandCosmosdbAccountRestoreParameters(input []interface{}) *documentdb.RestoreParameters { +func expandCosmosdbAccountRestoreParameters(input []interface{}) *cosmosdb.RestoreParameters { if len(input) == 0 { return nil } v := input[0].(map[string]interface{}) + restoreParameters := cosmosdb.RestoreParameters{ + RestoreMode: pointer.To(cosmosdb.RestoreModePointInTime), + RestoreSource: pointer.To(v["source_cosmosdb_account_id"].(string)), + DatabasesToRestore: expandCosmosdbAccountDatabasesToRestore(v["database"].(*pluginsdk.Set).List()), + } + restoreTimestampInUtc, _ := time.Parse(time.RFC3339, v["restore_timestamp_in_utc"].(string)) + restoreParameters.SetRestoreTimestampInUtcAsTime(restoreTimestampInUtc) - return &documentdb.RestoreParameters{ - RestoreMode: documentdb.RestoreModePointInTime, - RestoreSource: pointer.To(v["source_cosmosdb_account_id"].(string)), - RestoreTimestampInUtc: &date.Time{Time: restoreTimestampInUtc}, - DatabasesToRestore: expandCosmosdbAccountDatabasesToRestore(v["database"].(*pluginsdk.Set).List()), - } + return &restoreParameters } -func expandCosmosdbAccountDatabasesToRestore(input []interface{}) *[]documentdb.DatabaseRestoreResource { - results := make([]documentdb.DatabaseRestoreResource, 0) +func expandCosmosdbAccountDatabasesToRestore(input []interface{}) *[]cosmosdb.DatabaseRestoreResource { + results := make([]cosmosdb.DatabaseRestoreResource, 0) for _, item := range input { v := item.(map[string]interface{}) - results = append(results, documentdb.DatabaseRestoreResource{ + results = append(results, cosmosdb.DatabaseRestoreResource{ DatabaseName: pointer.To(v["name"].(string)), CollectionNames: utils.ExpandStringSlice(v["collection_names"].(*pluginsdk.Set).List()), }) @@ -2111,7 +2041,7 @@ func expandCosmosdbAccountDatabasesToRestore(input []interface{}) *[]documentdb. return &results } -func flattenCosmosdbAccountRestoreParameters(input *documentdb.RestoreParameters) []interface{} { +func flattenCosmosdbAccountRestoreParameters(input *cosmosdb.RestoreParameters) []interface{} { if input == nil { return make([]interface{}, 0) } @@ -2123,7 +2053,7 @@ func flattenCosmosdbAccountRestoreParameters(input *documentdb.RestoreParameters var restoreTimestampInUtc string if input.RestoreTimestampInUtc != nil { - restoreTimestampInUtc = input.RestoreTimestampInUtc.Format(time.RFC3339) + restoreTimestampInUtc = pointer.From(input.RestoreTimestampInUtc) } return []interface{}{ @@ -2135,7 +2065,7 @@ func flattenCosmosdbAccountRestoreParameters(input *documentdb.RestoreParameters } } -func flattenCosmosdbAccountDatabasesToRestore(input *[]documentdb.DatabaseRestoreResource) []interface{} { +func flattenCosmosdbAccountDatabasesToRestore(input *[]cosmosdb.DatabaseRestoreResource) []interface{} { results := make([]interface{}, 0) if input == nil { return results @@ -2156,7 +2086,7 @@ func flattenCosmosdbAccountDatabasesToRestore(input *[]documentdb.DatabaseRestor return results } -func checkCapabilitiesCanBeUpdated(kind string, oldCapabilities *[]documentdb.Capability, newCapabilities *[]documentdb.Capability) bool { +func checkCapabilitiesCanBeUpdated(kind string, oldCapabilities *[]cosmosdb.Capability, newCapabilities *[]cosmosdb.Capability) bool { // The feedback from service team : capabilities that can be added to an existing account canBeAddedCaps := []string{ strings.ToLower(string(databaseAccountCapabilitiesDisableRateLimitingResponses)), @@ -2231,12 +2161,12 @@ func checkCapabilitiesCanBeUpdated(kind string, oldCapabilities *[]documentdb.Ca return true } -func prepareCapabilities(capabilities interface{}) *[]documentdb.Capability { - output := make([]documentdb.Capability, 0) +func prepareCapabilities(capabilities interface{}) *[]cosmosdb.Capability { + output := make([]cosmosdb.Capability, 0) for _, v := range capabilities.(*pluginsdk.Set).List() { m := v.(map[string]interface{}) if c, ok := m["name"].(string); ok { - cap := documentdb.Capability{ + cap := cosmosdb.Capability{ Name: pointer.To(c), } output = append(output, cap) diff --git a/internal/services/cosmos/cosmosdb_account_resource_test.go b/internal/services/cosmos/cosmosdb_account_resource_test.go index 882956a5e483..26db73918bbd 100644 --- a/internal/services/cosmos/cosmosdb_account_resource_test.go +++ b/internal/services/cosmos/cosmosdb_account_resource_test.go @@ -10,7 +10,7 @@ import ( "strconv" "testing" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" @@ -24,74 +24,74 @@ import ( type CosmosDBAccountResource struct{} func TestAccCosmosDBAccount_basic_global_boundedStaleness(t *testing.T) { - testAccCosmosDBAccount_basicDocumentDbWith(t, documentdb.DefaultConsistencyLevelBoundedStaleness) + testAccCosmosDBAccount_basicDocumentDbWith(t, cosmosdb.DefaultConsistencyLevelBoundedStaleness) } func TestAccCosmosDBAccount_basic_global_consistentPrefix(t *testing.T) { - testAccCosmosDBAccount_basicDocumentDbWith(t, documentdb.DefaultConsistencyLevelConsistentPrefix) + testAccCosmosDBAccount_basicDocumentDbWith(t, cosmosdb.DefaultConsistencyLevelConsistentPrefix) } func TestAccCosmosDBAccount_basic_global_eventual(t *testing.T) { - testAccCosmosDBAccount_basicDocumentDbWith(t, documentdb.DefaultConsistencyLevelEventual) + testAccCosmosDBAccount_basicDocumentDbWith(t, cosmosdb.DefaultConsistencyLevelEventual) } func TestAccCosmosDBAccount_basic_global_session(t *testing.T) { - testAccCosmosDBAccount_basicDocumentDbWith(t, documentdb.DefaultConsistencyLevelSession) + testAccCosmosDBAccount_basicDocumentDbWith(t, cosmosdb.DefaultConsistencyLevelSession) } func TestAccCosmosDBAccount_basic_global_strong(t *testing.T) { - testAccCosmosDBAccount_basicDocumentDbWith(t, documentdb.DefaultConsistencyLevelStrong) + testAccCosmosDBAccount_basicDocumentDbWith(t, cosmosdb.DefaultConsistencyLevelStrong) } func TestAccCosmosDBAccount_basic_mongo_boundedStaleness(t *testing.T) { - testAccCosmosDBAccount_basicMongoDBWith(t, documentdb.DefaultConsistencyLevelBoundedStaleness) + testAccCosmosDBAccount_basicMongoDBWith(t, cosmosdb.DefaultConsistencyLevelBoundedStaleness) } func TestAccCosmosDBAccount_basic_mongo_consistentPrefix(t *testing.T) { - testAccCosmosDBAccount_basicMongoDBWith(t, documentdb.DefaultConsistencyLevelConsistentPrefix) + testAccCosmosDBAccount_basicMongoDBWith(t, cosmosdb.DefaultConsistencyLevelConsistentPrefix) } func TestAccCosmosDBAccount_basic_mongo_eventual(t *testing.T) { - testAccCosmosDBAccount_basicMongoDBWith(t, documentdb.DefaultConsistencyLevelEventual) + testAccCosmosDBAccount_basicMongoDBWith(t, cosmosdb.DefaultConsistencyLevelEventual) } func TestAccCosmosDBAccount_basic_mongo_session(t *testing.T) { - testAccCosmosDBAccount_basicMongoDBWith(t, documentdb.DefaultConsistencyLevelSession) + testAccCosmosDBAccount_basicMongoDBWith(t, cosmosdb.DefaultConsistencyLevelSession) } func TestAccCosmosDBAccount_basic_mongo_strong(t *testing.T) { - testAccCosmosDBAccount_basicMongoDBWith(t, documentdb.DefaultConsistencyLevelStrong) + testAccCosmosDBAccount_basicMongoDBWith(t, cosmosdb.DefaultConsistencyLevelStrong) } func TestAccCosmosDBAccount_basic_mongo_strong_without_capability(t *testing.T) { - testAccCosmosDBAccount_basicMongoDBWith(t, documentdb.DefaultConsistencyLevelStrong) + testAccCosmosDBAccount_basicMongoDBWith(t, cosmosdb.DefaultConsistencyLevelStrong) } func TestAccCosmosDBAccount_basic_parse_boundedStaleness(t *testing.T) { - testAccCosmosDBAccount_basicWith(t, documentdb.DatabaseAccountKindParse, documentdb.DefaultConsistencyLevelBoundedStaleness) + testAccCosmosDBAccount_basicWith(t, cosmosdb.DatabaseAccountKindParse, cosmosdb.DefaultConsistencyLevelBoundedStaleness) } func TestAccCosmosDBAccount_basic_parse_consistentPrefix(t *testing.T) { - testAccCosmosDBAccount_basicWith(t, documentdb.DatabaseAccountKindParse, documentdb.DefaultConsistencyLevelConsistentPrefix) + testAccCosmosDBAccount_basicWith(t, cosmosdb.DatabaseAccountKindParse, cosmosdb.DefaultConsistencyLevelConsistentPrefix) } func TestAccCosmosDBAccount_basic_parse_eventual(t *testing.T) { - testAccCosmosDBAccount_basicWith(t, documentdb.DatabaseAccountKindParse, documentdb.DefaultConsistencyLevelEventual) + testAccCosmosDBAccount_basicWith(t, cosmosdb.DatabaseAccountKindParse, cosmosdb.DefaultConsistencyLevelEventual) } func TestAccCosmosDBAccount_basic_parse_session(t *testing.T) { - testAccCosmosDBAccount_basicWith(t, documentdb.DatabaseAccountKindParse, documentdb.DefaultConsistencyLevelSession) + testAccCosmosDBAccount_basicWith(t, cosmosdb.DatabaseAccountKindParse, cosmosdb.DefaultConsistencyLevelSession) } func TestAccCosmosDBAccount_basic_parse_strong(t *testing.T) { - testAccCosmosDBAccount_basicWith(t, documentdb.DatabaseAccountKindParse, documentdb.DefaultConsistencyLevelStrong) + testAccCosmosDBAccount_basicWith(t, cosmosdb.DatabaseAccountKindParse, cosmosdb.DefaultConsistencyLevelStrong) } func TestAccCosmosDBAccount_public_network_access_enabled(t *testing.T) { - testAccCosmosDBAccount_public_network_access_enabled(t, documentdb.DatabaseAccountKindMongoDB, documentdb.DefaultConsistencyLevelStrong) + testAccCosmosDBAccount_public_network_access_enabled(t, cosmosdb.DatabaseAccountKindMongoDB, cosmosdb.DefaultConsistencyLevelStrong) } -func testAccCosmosDBAccount_public_network_access_enabled(t *testing.T, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) { +func testAccCosmosDBAccount_public_network_access_enabled(t *testing.T, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) { data := acceptance.BuildTestData(t, "azurerm_cosmosdb_account", "test") r := CosmosDBAccountResource{} @@ -112,9 +112,9 @@ func TestAccCosmosDBAccount_keyVaultUri(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.key_vault_uri(data, documentdb.DatabaseAccountKindMongoDB, documentdb.DefaultConsistencyLevelStrong), + Config: r.key_vault_uri(data, cosmosdb.DatabaseAccountKindMongoDB, cosmosdb.DefaultConsistencyLevelStrong), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), @@ -127,30 +127,30 @@ func TestAccCosmosDBAccount_customerManagedKeyWithIdentity(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.keyVaultKeyUriWithSystemAssignedIdentity(data, documentdb.DatabaseAccountKindMongoDB, documentdb.DefaultConsistencyLevelStrong), + Config: r.keyVaultKeyUriWithSystemAssignedIdentity(data, cosmosdb.DatabaseAccountKindMongoDB, cosmosdb.DefaultConsistencyLevelStrong), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), { - Config: r.keyVaultKeyUriWithSystemAssignedAndUserAssignedIdentity(data, documentdb.DatabaseAccountKindMongoDB, documentdb.DefaultConsistencyLevelStrong), + Config: r.keyVaultKeyUriWithSystemAssignedAndUserAssignedIdentity(data, cosmosdb.DatabaseAccountKindMongoDB, cosmosdb.DefaultConsistencyLevelStrong), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), { - Config: r.keyVaultKeyUriWithUserAssignedIdentity(data, documentdb.DatabaseAccountKindMongoDB, documentdb.DefaultConsistencyLevelStrong), + Config: r.keyVaultKeyUriWithUserAssignedIdentity(data, cosmosdb.DatabaseAccountKindMongoDB, cosmosdb.DefaultConsistencyLevelStrong), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), { - Config: r.keyVaultKeyUriWithSystemAssignedIdentity(data, documentdb.DatabaseAccountKindMongoDB, documentdb.DefaultConsistencyLevelStrong), + Config: r.keyVaultKeyUriWithSystemAssignedIdentity(data, cosmosdb.DatabaseAccountKindMongoDB, cosmosdb.DefaultConsistencyLevelStrong), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), @@ -163,14 +163,14 @@ func TestAccCosmosDBAccount_updateMongoDBVersionCapabilities(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicMongoDB(data, documentdb.DefaultConsistencyLevelStrong), + Config: r.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelStrong), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.updateMongoDBVersionCapabilities(data, documentdb.DefaultConsistencyLevelStrong), + Config: r.updateMongoDBVersionCapabilities(data, cosmosdb.DefaultConsistencyLevelStrong), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -185,16 +185,16 @@ func TestAccCosmosDBAccount_keyVaultUriUpdateConsistancy(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.key_vault_uri(data, documentdb.DatabaseAccountKindMongoDB, documentdb.DefaultConsistencyLevelStrong), + Config: r.key_vault_uri(data, cosmosdb.DatabaseAccountKindMongoDB, cosmosdb.DefaultConsistencyLevelStrong), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), { - Config: r.key_vault_uri(data, documentdb.DatabaseAccountKindMongoDB, documentdb.DefaultConsistencyLevelSession), + Config: r.key_vault_uri(data, cosmosdb.DatabaseAccountKindMongoDB, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelSession, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelSession, 1), ), }, data.ImportStep(), @@ -230,44 +230,44 @@ func TestAccCosmosDBAccount_updateDefaultIdentity(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.defaultIdentity(data, documentdb.DatabaseAccountKindGlobalDocumentDB, "FirstPartyIdentity", documentdb.DefaultConsistencyLevelEventual), + Config: r.defaultIdentity(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, "FirstPartyIdentity", cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.updateDefaultIdentity(data, documentdb.DatabaseAccountKindGlobalDocumentDB, `"SystemAssignedIdentity"`, documentdb.DefaultConsistencyLevelEventual), + Config: r.updateDefaultIdentity(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, `"SystemAssignedIdentity"`, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.updateDefaultIdentityUserAssigned(data, documentdb.DatabaseAccountKindGlobalDocumentDB, `join("=", ["UserAssignedIdentity", azurerm_user_assigned_identity.test.id])`, documentdb.DefaultConsistencyLevelEventual, "UserAssigned"), + Config: r.updateDefaultIdentityUserAssigned(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, `join("=", ["UserAssignedIdentity", azurerm_user_assigned_identity.test.id])`, cosmosdb.DefaultConsistencyLevelEventual, "UserAssigned"), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.updateDefaultIdentityUserAssigned(data, documentdb.DatabaseAccountKindGlobalDocumentDB, `join("=", ["UserAssignedIdentity", azurerm_user_assigned_identity.test.id])`, documentdb.DefaultConsistencyLevelEventual, "SystemAssigned, UserAssigned"), + Config: r.updateDefaultIdentityUserAssigned(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, `join("=", ["UserAssignedIdentity", azurerm_user_assigned_identity.test.id])`, cosmosdb.DefaultConsistencyLevelEventual, "SystemAssigned, UserAssigned"), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), @@ -303,7 +303,7 @@ func TestAccCosmosDBAccount_userAssignedIdentityMultiple(t *testing.T) { } //nolint:unparam -func testAccCosmosDBAccount_basicWith(t *testing.T, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) { +func testAccCosmosDBAccount_basicWith(t *testing.T, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) { data := acceptance.BuildTestData(t, "azurerm_cosmosdb_account", "test") r := CosmosDBAccountResource{} @@ -318,13 +318,13 @@ func testAccCosmosDBAccount_basicWith(t *testing.T, kind documentdb.DatabaseAcco }) } -func testAccCosmosDBAccount_basicDocumentDbWith(t *testing.T, consistency documentdb.DefaultConsistencyLevel) { +func testAccCosmosDBAccount_basicDocumentDbWith(t *testing.T, consistency cosmosdb.DefaultConsistencyLevel) { data := acceptance.BuildTestData(t, "azurerm_cosmosdb_account", "test") r := CosmosDBAccountResource{} data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, consistency), + Config: r.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, consistency), Check: acceptance.ComposeAggregateTestCheckFunc( checkAccCosmosDBAccount_basic(data, consistency, 1), checkAccCosmosDBAccount_sql(data), @@ -334,7 +334,7 @@ func testAccCosmosDBAccount_basicDocumentDbWith(t *testing.T, consistency docume }) } -func testAccCosmosDBAccount_basicMongoDBWith(t *testing.T, consistency documentdb.DefaultConsistencyLevel) { +func testAccCosmosDBAccount_basicMongoDBWith(t *testing.T, consistency cosmosdb.DefaultConsistencyLevel) { data := acceptance.BuildTestData(t, "azurerm_cosmosdb_account", "test") r := CosmosDBAccountResource{} @@ -355,20 +355,20 @@ func TestAccCosmosDBAccount_requiresImport(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, "GlobalDocumentDB", documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, "GlobalDocumentDB", cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, { - Config: r.requiresImport(data, documentdb.DefaultConsistencyLevelEventual), + Config: r.requiresImport(data, cosmosdb.DefaultConsistencyLevelEventual), ExpectError: acceptance.RequiresImportError("azurerm_cosmosdb_account"), }, }) } func TestAccCosmosDBAccount_updateConsistency_global(t *testing.T) { - testAccCosmosDBAccount_updateConsistency(t, documentdb.DatabaseAccountKindGlobalDocumentDB) + testAccCosmosDBAccount_updateConsistency(t, cosmosdb.DatabaseAccountKindGlobalDocumentDB) } func TestAccCosmosDBAccount_updateConsistency_mongo(t *testing.T) { @@ -377,71 +377,71 @@ func TestAccCosmosDBAccount_updateConsistency_mongo(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicMongoDB(data, documentdb.DefaultConsistencyLevelStrong), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + Config: r.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelStrong), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), }, data.ImportStep(), { - Config: r.consistencyMongoDB(data, documentdb.DefaultConsistencyLevelStrong, 8, 880), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + Config: r.consistencyMongoDB(data, cosmosdb.DefaultConsistencyLevelStrong, 8, 880), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), }, data.ImportStep(), { - Config: r.basicMongoDB(data, documentdb.DefaultConsistencyLevelBoundedStaleness), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelBoundedStaleness, 1), + Config: r.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelBoundedStaleness), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 1), }, data.ImportStep(), { - Config: r.consistencyMongoDB(data, documentdb.DefaultConsistencyLevelBoundedStaleness, 7, 770), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelBoundedStaleness, 1), + Config: r.consistencyMongoDB(data, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 7, 770), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 1), }, data.ImportStep(), { - Config: r.consistencyMongoDB(data, documentdb.DefaultConsistencyLevelBoundedStaleness, 77, 700), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelBoundedStaleness, 1), + Config: r.consistencyMongoDB(data, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 77, 700), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 1), }, data.ImportStep(), { - Config: r.basicMongoDB(data, documentdb.DefaultConsistencyLevelConsistentPrefix), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelConsistentPrefix, 1), + Config: r.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelConsistentPrefix), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelConsistentPrefix, 1), }, data.ImportStep(), }) } -func testAccCosmosDBAccount_updateConsistency(t *testing.T, kind documentdb.DatabaseAccountKind) { +func testAccCosmosDBAccount_updateConsistency(t *testing.T, kind cosmosdb.DatabaseAccountKind) { data := acceptance.BuildTestData(t, "azurerm_cosmosdb_account", "test") r := CosmosDBAccountResource{} data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, kind, documentdb.DefaultConsistencyLevelStrong), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + Config: r.basic(data, kind, cosmosdb.DefaultConsistencyLevelStrong), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), }, data.ImportStep(), { - Config: r.consistency(data, kind, documentdb.DefaultConsistencyLevelStrong, 8, 880), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + Config: r.consistency(data, kind, cosmosdb.DefaultConsistencyLevelStrong, 8, 880), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), }, data.ImportStep(), { - Config: r.basic(data, kind, documentdb.DefaultConsistencyLevelBoundedStaleness), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelBoundedStaleness, 1), + Config: r.basic(data, kind, cosmosdb.DefaultConsistencyLevelBoundedStaleness), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 1), }, data.ImportStep(), { - Config: r.consistency(data, kind, documentdb.DefaultConsistencyLevelBoundedStaleness, 7, 770), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelBoundedStaleness, 1), + Config: r.consistency(data, kind, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 7, 770), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 1), }, data.ImportStep(), { - Config: r.consistency(data, kind, documentdb.DefaultConsistencyLevelBoundedStaleness, 77, 700), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelBoundedStaleness, 1), + Config: r.consistency(data, kind, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 77, 700), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelBoundedStaleness, 1), }, data.ImportStep(), { - Config: r.basic(data, kind, documentdb.DefaultConsistencyLevelConsistentPrefix), - Check: checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelConsistentPrefix, 1), + Config: r.basic(data, kind, cosmosdb.DefaultConsistencyLevelConsistentPrefix), + Check: checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelConsistentPrefix, 1), }, data.ImportStep(), }) @@ -453,9 +453,9 @@ func TestAccCosmosDBAccount_complete_mongo(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.completeMongoDB(data, documentdb.DefaultConsistencyLevelEventual), + Config: r.completeMongoDB(data, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 3), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 3), ), }, data.ImportStep(), @@ -463,22 +463,22 @@ func TestAccCosmosDBAccount_complete_mongo(t *testing.T) { } func TestAccCosmosDBAccount_complete_global(t *testing.T) { - testAccCosmosDBAccount_completeWith(t, documentdb.DatabaseAccountKindGlobalDocumentDB) + testAccCosmosDBAccount_completeWith(t, cosmosdb.DatabaseAccountKindGlobalDocumentDB) } func TestAccCosmosDBAccount_complete_parse(t *testing.T) { - testAccCosmosDBAccount_completeWith(t, documentdb.DatabaseAccountKindParse) + testAccCosmosDBAccount_completeWith(t, cosmosdb.DatabaseAccountKindParse) } -func testAccCosmosDBAccount_completeWith(t *testing.T, kind documentdb.DatabaseAccountKind) { +func testAccCosmosDBAccount_completeWith(t *testing.T, kind cosmosdb.DatabaseAccountKind) { data := acceptance.BuildTestData(t, "azurerm_cosmosdb_account", "test") r := CosmosDBAccountResource{} data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.complete(data, kind, documentdb.DefaultConsistencyLevelEventual), + Config: r.complete(data, kind, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 3), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 3), ), }, data.ImportStep(), @@ -491,7 +491,7 @@ func TestAccCosmosDBAccount_complete_tags(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.completeTags(data, documentdb.DatabaseAccountKindParse, documentdb.DefaultConsistencyLevelEventual), + Config: r.completeTags(data, cosmosdb.DatabaseAccountKindParse, cosmosdb.DefaultConsistencyLevelEventual), }, data.ImportStep(), }) @@ -516,14 +516,14 @@ func TestAccCosmosDBAccount_completeZoneRedundant_mongo(t *testing.T) { } func TestAccCosmosDBAccount_completeZoneRedundant_global(t *testing.T) { - testAccCosmosDBAccount_zoneRedundantWith(t, documentdb.DatabaseAccountKindGlobalDocumentDB) + testAccCosmosDBAccount_zoneRedundantWith(t, cosmosdb.DatabaseAccountKindGlobalDocumentDB) } func TestAccCosmosDBAccount_completeZoneRedundant_parse(t *testing.T) { - testAccCosmosDBAccount_zoneRedundantWith(t, documentdb.DatabaseAccountKindParse) + testAccCosmosDBAccount_zoneRedundantWith(t, cosmosdb.DatabaseAccountKindParse) } -func testAccCosmosDBAccount_zoneRedundantWith(t *testing.T, kind documentdb.DatabaseAccountKind) { +func testAccCosmosDBAccount_zoneRedundantWith(t *testing.T, kind cosmosdb.DatabaseAccountKind) { data := acceptance.BuildTestData(t, "azurerm_cosmosdb_account", "test") // Limited regional availability data.Locations.Primary = "westeurope" @@ -550,16 +550,16 @@ func TestAccCosmosDBAccount_zoneRedundant_update_mongo(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicMongoDB(data, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.zoneRedundantMongoDBUpdate(data, documentdb.DefaultConsistencyLevelEventual), + Config: r.zoneRedundantMongoDBUpdate(data, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 2), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 2), ), }, data.ImportStep(), @@ -572,37 +572,37 @@ func TestAccCosmosDBAccount_update_mongo(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicMongoDB(data, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.completeMongoDB(data, documentdb.DefaultConsistencyLevelEventual), + Config: r.completeMongoDB(data, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 3), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 3), ), }, data.ImportStep(), { - Config: r.completeUpdatedMongoDB(data, documentdb.DefaultConsistencyLevelEventual), + Config: r.completeUpdatedMongoDB(data, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 3), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 3), ), }, data.ImportStep(), { - Config: r.completeUpdatedMongoDB_RemoveDisableRateLimitingResponsesCapability(data, documentdb.DefaultConsistencyLevelEventual), + Config: r.completeUpdatedMongoDB_RemoveDisableRateLimitingResponsesCapability(data, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 3), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 3), ), }, data.ImportStep(), { - Config: r.basicWithResourcesMongoDB(data, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithResourcesMongoDB(data, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - // checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + // checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), @@ -610,50 +610,50 @@ func TestAccCosmosDBAccount_update_mongo(t *testing.T) { } func TestAccCosmosDBAccount_update_global(t *testing.T) { - testAccCosmosDBAccount_updateWith(t, documentdb.DatabaseAccountKindGlobalDocumentDB) + testAccCosmosDBAccount_updateWith(t, cosmosdb.DatabaseAccountKindGlobalDocumentDB) } func TestAccCosmosDBAccount_update_parse(t *testing.T) { - testAccCosmosDBAccount_updateWith(t, documentdb.DatabaseAccountKindParse) + testAccCosmosDBAccount_updateWith(t, cosmosdb.DatabaseAccountKindParse) } -func testAccCosmosDBAccount_updateWith(t *testing.T, kind documentdb.DatabaseAccountKind) { +func testAccCosmosDBAccount_updateWith(t *testing.T, kind cosmosdb.DatabaseAccountKind) { data := acceptance.BuildTestData(t, "azurerm_cosmosdb_account", "test") r := CosmosDBAccountResource{} data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, kind, documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, kind, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.complete(data, kind, documentdb.DefaultConsistencyLevelEventual), + Config: r.complete(data, kind, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 3), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 3), ), }, data.ImportStep(), { - Config: r.completeUpdated(data, kind, documentdb.DefaultConsistencyLevelEventual), + Config: r.completeUpdated(data, kind, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 3), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 3), ), }, data.ImportStep(), { - Config: r.completeUpdated_RemoveDisableRateLimitingResponsesCapabilities(data, kind, documentdb.DefaultConsistencyLevelEventual), + Config: r.completeUpdated_RemoveDisableRateLimitingResponsesCapabilities(data, kind, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 3), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 3), ), }, data.ImportStep(), { - Config: r.basicWithResources(data, kind, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithResources(data, kind, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - // checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + // checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), @@ -661,31 +661,31 @@ func testAccCosmosDBAccount_updateWith(t *testing.T, kind documentdb.DatabaseAcc } func TestAccCosmosDBAccount_capabilities_EnableAggregationPipeline(t *testing.T) { - testAccCosmosDBAccount_capabilitiesWith(t, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableAggregationPipeline"}) + testAccCosmosDBAccount_capabilitiesWith(t, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableAggregationPipeline"}) } func TestAccCosmosDBAccount_capabilities_EnableCassandra(t *testing.T) { - testAccCosmosDBAccount_capabilitiesWith(t, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}) + testAccCosmosDBAccount_capabilitiesWith(t, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}) } func TestAccCosmosDBAccount_capabilities_EnableGremlin(t *testing.T) { - testAccCosmosDBAccount_capabilitiesWith(t, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableGremlin"}) + testAccCosmosDBAccount_capabilitiesWith(t, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableGremlin"}) } func TestAccCosmosDBAccount_capabilities_EnableTable(t *testing.T) { - testAccCosmosDBAccount_capabilitiesWith(t, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableTable"}) + testAccCosmosDBAccount_capabilitiesWith(t, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableTable"}) } func TestAccCosmosDBAccount_capabilities_EnableServerless(t *testing.T) { - testAccCosmosDBAccount_capabilitiesWith(t, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableServerless"}) + testAccCosmosDBAccount_capabilitiesWith(t, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableServerless"}) } func TestAccCosmosDBAccount_capabilities_EnableMongo(t *testing.T) { - testAccCosmosDBAccount_capabilitiesWith(t, documentdb.DatabaseAccountKindMongoDB, []string{"EnableMongo"}) + testAccCosmosDBAccount_capabilitiesWith(t, cosmosdb.DatabaseAccountKindMongoDB, []string{"EnableMongo"}) } func TestAccCosmosDBAccount_capabilities_MongoDBv34(t *testing.T) { - testAccCosmosDBAccount_capabilitiesWith(t, documentdb.DatabaseAccountKindMongoDB, []string{"EnableMongo", "MongoDBv3.4"}) + testAccCosmosDBAccount_capabilitiesWith(t, cosmosdb.DatabaseAccountKindMongoDB, []string{"EnableMongo", "MongoDBv3.4"}) } func TestAccCosmosDBAccount_capabilities_MongoDBv34_NoEnableMongo(t *testing.T) { @@ -693,25 +693,25 @@ func TestAccCosmosDBAccount_capabilities_MongoDBv34_NoEnableMongo(t *testing.T) r := CosmosDBAccountResource{} data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.capabilities(data, documentdb.DatabaseAccountKindMongoDB, []string{"MongoDBv3.4"}), + Config: r.capabilities(data, cosmosdb.DatabaseAccountKindMongoDB, []string{"MongoDBv3.4"}), ExpectError: regexp.MustCompile("capability EnableMongo must be enabled if MongoDBv3.4 is also enabled"), }, }) } func TestAccCosmosDBAccount_capabilities_mongoEnableDocLevelTTL(t *testing.T) { - testAccCosmosDBAccount_capabilitiesWith(t, documentdb.DatabaseAccountKindMongoDB, []string{"EnableMongo", "mongoEnableDocLevelTTL"}) + testAccCosmosDBAccount_capabilitiesWith(t, cosmosdb.DatabaseAccountKindMongoDB, []string{"EnableMongo", "mongoEnableDocLevelTTL"}) } func TestAccCosmosDBAccount_capabilities_DisableRateLimitingResponses(t *testing.T) { - testAccCosmosDBAccount_capabilitiesWith(t, documentdb.DatabaseAccountKindMongoDB, []string{"EnableMongo", "DisableRateLimitingResponses"}) + testAccCosmosDBAccount_capabilitiesWith(t, cosmosdb.DatabaseAccountKindMongoDB, []string{"EnableMongo", "DisableRateLimitingResponses"}) } func TestAccCosmosDBAccount_capabilities_AllowSelfServeUpgradeToMongo36(t *testing.T) { - testAccCosmosDBAccount_capabilitiesWith(t, documentdb.DatabaseAccountKindMongoDB, []string{"EnableMongo", "AllowSelfServeUpgradeToMongo36"}) + testAccCosmosDBAccount_capabilitiesWith(t, cosmosdb.DatabaseAccountKindMongoDB, []string{"EnableMongo", "AllowSelfServeUpgradeToMongo36"}) } -func testAccCosmosDBAccount_capabilitiesWith(t *testing.T, kind documentdb.DatabaseAccountKind, capabilities []string) { +func testAccCosmosDBAccount_capabilitiesWith(t *testing.T, kind cosmosdb.DatabaseAccountKind, capabilities []string) { data := acceptance.BuildTestData(t, "azurerm_cosmosdb_account", "test") r := CosmosDBAccountResource{} @@ -719,7 +719,7 @@ func testAccCosmosDBAccount_capabilitiesWith(t *testing.T, kind documentdb.Datab { Config: r.capabilities(data, kind, capabilities), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), @@ -732,16 +732,16 @@ func TestAccCosmosDBAccount_capabilitiesAdd(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}), + Config: r.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), { - Config: r.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra", "EnableAggregationPipeline"}), + Config: r.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra", "EnableAggregationPipeline"}), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), @@ -754,23 +754,23 @@ func TestAccCosmosDBAccount_capabilitiesUpdate(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}), + Config: r.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), { - Config: r.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra", "DisableRateLimitingResponses", "AllowSelfServeUpgradeToMongo36", "EnableAggregationPipeline", "MongoDBv3.4", "mongoEnableDocLevelTTL"}), + Config: r.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra", "DisableRateLimitingResponses", "AllowSelfServeUpgradeToMongo36", "EnableAggregationPipeline", "MongoDBv3.4", "mongoEnableDocLevelTTL"}), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), { - Config: r.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra", "AllowSelfServeUpgradeToMongo36", "EnableAggregationPipeline", "MongoDBv3.4", "mongoEnableDocLevelTTL"}), + Config: r.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra", "AllowSelfServeUpgradeToMongo36", "EnableAggregationPipeline", "MongoDBv3.4", "mongoEnableDocLevelTTL"}), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), ), }, data.ImportStep(), @@ -783,23 +783,23 @@ func TestAccCosmosDBAccount_geoLocationsUpdate(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, "GlobalDocumentDB", documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, "GlobalDocumentDB", cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.geoLocationUpdate(data, "GlobalDocumentDB", documentdb.DefaultConsistencyLevelEventual), + Config: r.geoLocationUpdate(data, "GlobalDocumentDB", cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 2), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 2), ), }, data.ImportStep(), { - Config: r.basic(data, "GlobalDocumentDB", documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, "GlobalDocumentDB", cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), @@ -812,9 +812,9 @@ func TestAccCosmosDBAccount_freeTier(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.freeTier(data, "GlobalDocumentDB", documentdb.DefaultConsistencyLevelEventual), + Config: r.freeTier(data, "GlobalDocumentDB", cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), check.That(data.ResourceName).Key("enable_free_tier").HasValue("true"), ), }, @@ -828,17 +828,17 @@ func TestAccCosmosDBAccount_analyticalStorage(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.analyticalStorage(data, "MongoDB", documentdb.DefaultConsistencyLevelStrong, false), + Config: r.analyticalStorage(data, "MongoDB", cosmosdb.DefaultConsistencyLevelStrong, false), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), check.That(data.ResourceName).Key("analytical_storage_enabled").HasValue("false"), ), }, data.ImportStep(), { - Config: r.analyticalStorage(data, "MongoDB", documentdb.DefaultConsistencyLevelStrong, true), + Config: r.analyticalStorage(data, "MongoDB", cosmosdb.DefaultConsistencyLevelStrong, true), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelStrong, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelStrong, 1), check.That(data.ResourceName).Key("analytical_storage_enabled").HasValue("true"), ), }, @@ -852,30 +852,30 @@ func TestAccCosmosDBAccount_updateAnalyticalStorage(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.updateAnalyticalStorage(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.AnalyticalStorageSchemaTypeWellDefined, documentdb.DefaultConsistencyLevelEventual), + Config: r.updateAnalyticalStorage(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.AnalyticalStorageSchemaTypeWellDefined, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.updateAnalyticalStorage(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.AnalyticalStorageSchemaTypeFullFidelity, documentdb.DefaultConsistencyLevelEventual), + Config: r.updateAnalyticalStorage(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.AnalyticalStorageSchemaTypeFullFidelity, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), @@ -888,30 +888,30 @@ func TestAccCosmosDBAccount_updateCapacity(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.updateCapacity(data, documentdb.DatabaseAccountKindGlobalDocumentDB, -1, documentdb.DefaultConsistencyLevelEventual), + Config: r.updateCapacity(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, -1, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.updateCapacity(data, documentdb.DatabaseAccountKindGlobalDocumentDB, 200, documentdb.DefaultConsistencyLevelEventual), + Config: r.updateCapacity(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, 200, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), { - Config: r.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), @@ -965,14 +965,14 @@ func TestAccCosmosDBAccount_identity(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicMongoDB(data, documentdb.DefaultConsistencyLevelSession), + Config: r.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.systemAssignedUserAssignedIdentity(data, documentdb.DefaultConsistencyLevelSession), + Config: r.systemAssignedUserAssignedIdentity(data, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("identity.0.type").HasValue("SystemAssigned, UserAssigned"), @@ -983,7 +983,7 @@ func TestAccCosmosDBAccount_identity(t *testing.T) { }, data.ImportStep(), { - Config: r.basicMongoDB(data, documentdb.DefaultConsistencyLevelSession), + Config: r.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -998,7 +998,7 @@ func TestAccCosmosDBAccount_backup(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("backup.0.type").HasValue("Periodic"), @@ -1009,14 +1009,14 @@ func TestAccCosmosDBAccount_backup(t *testing.T) { }, data.ImportStep(), { - Config: r.basicWithBackupPeriodic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithBackupPeriodic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.basicWithBackupPeriodicUpdate(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithBackupPeriodicUpdate(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("backup.0.type").HasValue("Periodic"), @@ -1032,14 +1032,14 @@ func TestAccCosmosDBAccount_backupPeriodicToContinuous(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicWithBackupPeriodic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithBackupPeriodic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.basicWithBackupContinuous(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithBackupContinuous(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -1054,7 +1054,7 @@ func TestAccCosmosDBAccount_backupContinuous(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicWithBackupContinuous(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithBackupContinuous(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -1069,14 +1069,14 @@ func TestAccCosmosDBAccount_backupPeriodicToContinuousUpdate(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicWithBackupPeriodic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithBackupPeriodic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.basicWithBackupContinuousUpdate(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithBackupContinuousUpdate(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -1091,21 +1091,21 @@ func TestAccCosmosDBAccount_networkBypass(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.basicWithNetworkBypass(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithNetworkBypass(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.basicWithoutNetworkBypass(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithoutNetworkBypass(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -1120,7 +1120,7 @@ func TestAccCosmosDBAccount_mongoVersion32(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicMongoDBVersion32(data, documentdb.DefaultConsistencyLevelSession), + Config: r.basicMongoDBVersion32(data, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -1135,7 +1135,7 @@ func TestAccCosmosDBAccount_mongoVersion36(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicMongoDBVersion36(data, documentdb.DefaultConsistencyLevelSession), + Config: r.basicMongoDBVersion36(data, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -1150,7 +1150,7 @@ func TestAccCosmosDBAccount_mongoVersion40(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicMongoDBVersion40(data, documentdb.DefaultConsistencyLevelSession), + Config: r.basicMongoDBVersion40(data, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -1165,7 +1165,7 @@ func TestAccCosmosDBAccount_mongoVersion42(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicMongoDBVersion42(data, documentdb.DefaultConsistencyLevelSession), + Config: r.basicMongoDBVersion42(data, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -1180,28 +1180,28 @@ func TestAccCosmosDBAccount_mongoVersionUpdate(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basicMongoDBVersion32(data, documentdb.DefaultConsistencyLevelSession), + Config: r.basicMongoDBVersion32(data, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.basicMongoDBVersion36(data, documentdb.DefaultConsistencyLevelSession), + Config: r.basicMongoDBVersion36(data, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.basicMongoDBVersion40(data, documentdb.DefaultConsistencyLevelSession), + Config: r.basicMongoDBVersion40(data, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.basicMongoDBVersion36(data, documentdb.DefaultConsistencyLevelSession), + Config: r.basicMongoDBVersion36(data, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -1216,7 +1216,7 @@ func TestAccCosmosDBAccount_localAuthenticationDisabled(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("local_authentication_disabled").HasValue("false"), @@ -1224,7 +1224,7 @@ func TestAccCosmosDBAccount_localAuthenticationDisabled(t *testing.T) { }, data.ImportStep(), { - Config: r.basicWithLocalAuthenticationDisabled(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.basicWithLocalAuthenticationDisabled(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("local_authentication_disabled").HasValue("true"), @@ -1240,9 +1240,9 @@ func TestAccCosmosDBAccount_defaultCreateMode(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.defaultCreateMode(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelEventual), + Config: r.defaultCreateMode(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelEventual), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelEventual, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelEventual, 1), ), }, data.ImportStep(), @@ -1255,9 +1255,9 @@ func TestAccCosmosDBAccount_restoreCreateMode(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.restoreCreateMode(data, documentdb.DatabaseAccountKindMongoDB, documentdb.DefaultConsistencyLevelSession), + Config: r.restoreCreateMode(data, cosmosdb.DatabaseAccountKindMongoDB, cosmosdb.DefaultConsistencyLevelSession), Check: acceptance.ComposeAggregateTestCheckFunc( - checkAccCosmosDBAccount_basic(data, documentdb.DefaultConsistencyLevelSession, 1), + checkAccCosmosDBAccount_basic(data, cosmosdb.DefaultConsistencyLevelSession, 1), ), }, data.ImportStep(), @@ -1335,7 +1335,7 @@ func TestAccCosmosDBAccount_withoutMaxAgeInSeconds(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.withoutMaxAgeInSeconds(data, documentdb.DatabaseAccountKindParse, documentdb.DefaultConsistencyLevelEventual), + Config: r.withoutMaxAgeInSeconds(data, cosmosdb.DatabaseAccountKindParse, cosmosdb.DefaultConsistencyLevelEventual), }, data.ImportStep(), }) @@ -1355,7 +1355,7 @@ func (t CosmosDBAccountResource) Exists(ctx context.Context, clients *clients.Cl return utils.Bool(resp.ID != nil), nil } -func (CosmosDBAccountResource) basic(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) basic(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -1385,7 +1385,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) basicMongoDB(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) basicMongoDB(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -1419,7 +1419,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(consistency)) } -func (r CosmosDBAccountResource) requiresImport(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) requiresImport(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %s @@ -1441,7 +1441,7 @@ resource "azurerm_cosmosdb_account" "import" { `, r.basic(data, "GlobalDocumentDB", consistency)) } -func (CosmosDBAccountResource) consistency(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel, interval, staleness int) string { +func (CosmosDBAccountResource) consistency(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel, interval, staleness int) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -1473,7 +1473,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), string(consistency), interval, staleness) } -func (CosmosDBAccountResource) consistencyMongoDB(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel, interval, staleness int) string { +func (CosmosDBAccountResource) consistencyMongoDB(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel, interval, staleness int) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -1546,7 +1546,7 @@ resource "azurerm_subnet" "subnet2" { `, data.RandomInteger, data.Locations.Primary) } -func (r CosmosDBAccountResource) complete(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) complete(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %[1]s @@ -1604,7 +1604,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.completePreReqs(data), data.RandomInteger, string(kind), string(consistency), data.Locations.Secondary, data.Locations.Ternary) } -func (r CosmosDBAccountResource) completeTags(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) completeTags(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %[1]s @@ -1665,7 +1665,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.completePreReqs(data), data.RandomInteger, string(kind), string(consistency), data.Locations.Secondary, data.Locations.Ternary) } -func (r CosmosDBAccountResource) completeMongoDB(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) completeMongoDB(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %[1]s @@ -1727,7 +1727,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.completePreReqs(data), data.RandomInteger, string(consistency), data.Locations.Secondary, data.Locations.Ternary) } -func (CosmosDBAccountResource) zoneRedundant(data acceptance.TestData, kind documentdb.DatabaseAccountKind) string { +func (CosmosDBAccountResource) zoneRedundant(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -1811,7 +1811,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.Locations.Secondary) } -func (r CosmosDBAccountResource) completeUpdated(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) completeUpdated(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %[1]s @@ -1880,7 +1880,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.completePreReqs(data), data.RandomInteger, string(kind), string(consistency), data.Locations.Secondary, data.Locations.Ternary) } -func (r CosmosDBAccountResource) completeUpdated_RemoveDisableRateLimitingResponsesCapabilities(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) completeUpdated_RemoveDisableRateLimitingResponsesCapabilities(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %[1]s @@ -1945,7 +1945,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.completePreReqs(data), data.RandomInteger, string(kind), string(consistency), data.Locations.Secondary, data.Locations.Ternary) } -func (r CosmosDBAccountResource) completeUpdatedMongoDB(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) completeUpdatedMongoDB(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %[1]s @@ -2021,7 +2021,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.completePreReqs(data), data.RandomInteger, string(consistency), data.Locations.Secondary, data.Locations.Ternary) } -func (r CosmosDBAccountResource) completeUpdatedMongoDB_RemoveDisableRateLimitingResponsesCapability(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) completeUpdatedMongoDB_RemoveDisableRateLimitingResponsesCapability(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %[1]s @@ -2093,7 +2093,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.completePreReqs(data), data.RandomInteger, string(consistency), data.Locations.Secondary, data.Locations.Ternary) } -func (r CosmosDBAccountResource) basicWithResources(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) basicWithResources(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %[1]s @@ -2128,7 +2128,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.completePreReqs(data), data.RandomInteger, string(kind), string(consistency)) } -func (r CosmosDBAccountResource) basicWithResourcesMongoDB(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) basicWithResourcesMongoDB(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %[1]s @@ -2171,7 +2171,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.completePreReqs(data), data.RandomInteger, string(consistency)) } -func (CosmosDBAccountResource) capabilities(data acceptance.TestData, kind documentdb.DatabaseAccountKind, capabilities []string) string { +func (CosmosDBAccountResource) capabilities(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, capabilities []string) string { capeTf := "" for _, c := range capabilities { capeTf += fmt.Sprintf("capabilities {name = \"%s\"}\n", c) @@ -2208,7 +2208,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), capeTf) } -func (CosmosDBAccountResource) geoLocationUpdate(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) geoLocationUpdate(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -2243,7 +2243,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), string(consistency), data.Locations.Secondary) } -func (CosmosDBAccountResource) zoneRedundantMongoDBUpdate(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) zoneRedundantMongoDBUpdate(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` variable "geo_location" { type = list(object({ @@ -2426,7 +2426,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.vNetFiltersPreReqs(data), data.RandomInteger) } -func (CosmosDBAccountResource) freeTier(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) freeTier(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -2458,7 +2458,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) analyticalStorage(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel, enableAnalyticalStorage bool) string { +func (CosmosDBAccountResource) analyticalStorage(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel, enableAnalyticalStorage bool) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -2490,7 +2490,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), enableAnalyticalStorage, string(consistency)) } -func (CosmosDBAccountResource) mongoAnalyticalStorage(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) mongoAnalyticalStorage(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -2526,13 +2526,13 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(consistency)) } -func checkAccCosmosDBAccount_basic(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel, locationCount int) acceptance.TestCheckFunc { +func checkAccCosmosDBAccount_basic(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel, locationCount int) acceptance.TestCheckFunc { return acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).Key("name").Exists(), check.That(data.ResourceName).Key("resource_group_name").Exists(), check.That(data.ResourceName).Key("location").HasValue(azure.NormalizeLocation(data.Locations.Primary)), check.That(data.ResourceName).Key("tags.%").HasValue("0"), - check.That(data.ResourceName).Key("offer_type").HasValue(string(documentdb.DatabaseAccountOfferTypeStandard)), + check.That(data.ResourceName).Key("offer_type").HasValue(string(cosmosdb.DatabaseAccountOfferTypeStandard)), check.That(data.ResourceName).Key("consistency_policy.0.consistency_level").HasValue(string(consistency)), check.That(data.ResourceName).Key("geo_location.#").HasValue(strconv.Itoa(locationCount)), check.That(data.ResourceName).Key("endpoint").Exists(), @@ -2553,7 +2553,7 @@ func checkAccCosmosDBAccount_sql(data acceptance.TestData) acceptance.TestCheckF ) } -func (CosmosDBAccountResource) network_access_enabled(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) network_access_enabled(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -2588,7 +2588,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) key_vault_uri(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) key_vault_uri(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features { @@ -2706,7 +2706,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomString, data.RandomString, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) keyVaultKeyUriWithSystemAssignedIdentity(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) keyVaultKeyUriWithSystemAssignedIdentity(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features { @@ -2856,7 +2856,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomString, data.RandomString, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) keyVaultKeyUriWithSystemAssignedAndUserAssignedIdentity(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) keyVaultKeyUriWithSystemAssignedAndUserAssignedIdentity(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features { @@ -3009,7 +3009,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomString, data.RandomString, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) keyVaultKeyUriWithUserAssignedIdentity(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) keyVaultKeyUriWithUserAssignedIdentity(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features { @@ -3162,7 +3162,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomString, data.RandomString, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) systemAssignedUserAssignedIdentity(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) systemAssignedUserAssignedIdentity(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3312,7 +3312,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } -func (CosmosDBAccountResource) basicWithBackupPeriodic(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) basicWithBackupPeriodic(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3349,7 +3349,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) basicWithBackupPeriodicUpdate(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) basicWithBackupPeriodicUpdate(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3386,7 +3386,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) basicWithBackupContinuous(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) basicWithBackupContinuous(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3420,7 +3420,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) basicWithBackupContinuousUpdate(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) basicWithBackupContinuousUpdate(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3496,7 +3496,7 @@ resource "azurerm_synapse_workspace" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomString) } -func (r CosmosDBAccountResource) basicWithNetworkBypass(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) basicWithNetworkBypass(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %s @@ -3522,7 +3522,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.basicWithNetworkBypassTemplate(data), data.RandomInteger, string(kind), string(consistency)) } -func (r CosmosDBAccountResource) basicWithoutNetworkBypass(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) basicWithoutNetworkBypass(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %s @@ -3546,7 +3546,7 @@ resource "azurerm_cosmosdb_account" "test" { `, r.basicWithNetworkBypassTemplate(data), data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) basicMongoDBVersion32(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) basicMongoDBVersion32(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3583,7 +3583,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(consistency)) } -func (CosmosDBAccountResource) updateMongoDBVersionCapabilities(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) updateMongoDBVersionCapabilities(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3622,7 +3622,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(consistency)) } -func (CosmosDBAccountResource) basicMongoDBVersion36(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) basicMongoDBVersion36(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3660,7 +3660,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(consistency)) } -func (CosmosDBAccountResource) basicMongoDBVersion40(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) basicMongoDBVersion40(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3725,7 +3725,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(consistency)) } -func (CosmosDBAccountResource) basicMongoDBVersion42(data acceptance.TestData, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) basicMongoDBVersion42(data acceptance.TestData, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3766,7 +3766,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(consistency)) } -func (CosmosDBAccountResource) basicWithLocalAuthenticationDisabled(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) basicWithLocalAuthenticationDisabled(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3798,7 +3798,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) updateAnalyticalStorage(data acceptance.TestData, kind documentdb.DatabaseAccountKind, schemaType documentdb.AnalyticalStorageSchemaType, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) updateAnalyticalStorage(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, schemaType cosmosdb.AnalyticalStorageSchemaType, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3833,7 +3833,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), string(schemaType), string(consistency)) } -func (CosmosDBAccountResource) updateCapacity(data acceptance.TestData, kind documentdb.DatabaseAccountKind, totalThroughputLimit int, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) updateCapacity(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, totalThroughputLimit int, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3868,7 +3868,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), totalThroughputLimit, string(consistency)) } -func (CosmosDBAccountResource) defaultIdentity(data acceptance.TestData, kind documentdb.DatabaseAccountKind, defaultIdentity string, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) defaultIdentity(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, defaultIdentity string, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3899,7 +3899,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), defaultIdentity, string(consistency)) } -func (CosmosDBAccountResource) updateDefaultIdentity(data acceptance.TestData, kind documentdb.DatabaseAccountKind, defaultIdentity string, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) updateDefaultIdentity(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, defaultIdentity string, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3934,7 +3934,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), defaultIdentity, string(consistency)) } -func (CosmosDBAccountResource) updateDefaultIdentityUserAssigned(data acceptance.TestData, kind documentdb.DatabaseAccountKind, defaultIdentity string, consistency documentdb.DefaultConsistencyLevel, identityType string) string { +func (CosmosDBAccountResource) updateDefaultIdentityUserAssigned(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, defaultIdentity string, consistency cosmosdb.DefaultConsistencyLevel, identityType string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -3976,7 +3976,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), defaultIdentity, identityType, string(consistency)) } -func (CosmosDBAccountResource) defaultCreateMode(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) defaultCreateMode(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -4011,7 +4011,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, string(kind), string(consistency)) } -func (CosmosDBAccountResource) restoreCreateMode(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (CosmosDBAccountResource) restoreCreateMode(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -4330,7 +4330,7 @@ resource "azurerm_cosmosdb_account" "test" { `, data.RandomInteger, tag) } -func (r CosmosDBAccountResource) withoutMaxAgeInSeconds(data acceptance.TestData, kind documentdb.DatabaseAccountKind, consistency documentdb.DefaultConsistencyLevel) string { +func (r CosmosDBAccountResource) withoutMaxAgeInSeconds(data acceptance.TestData, kind cosmosdb.DatabaseAccountKind, consistency cosmosdb.DefaultConsistencyLevel) string { return fmt.Sprintf(` %[1]s resource "azurerm_cosmosdb_account" "test" { diff --git a/internal/services/cosmos/cosmosdb_cassandra_keyspace_resource_test.go b/internal/services/cosmos/cosmosdb_cassandra_keyspace_resource_test.go index 9e46ecad144a..f9183d9d4f88 100644 --- a/internal/services/cosmos/cosmosdb_cassandra_keyspace_resource_test.go +++ b/internal/services/cosmos/cosmosdb_cassandra_keyspace_resource_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -144,7 +144,7 @@ resource "azurerm_cosmosdb_cassandra_keyspace" "test" { resource_group_name = azurerm_cosmosdb_account.test.resource_group_name account_name = azurerm_cosmosdb_account.test.name } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}), data.RandomInteger) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}), data.RandomInteger) } func (CosmosDbCassandraKeyspaceResource) throughput(data acceptance.TestData, throughput int) string { @@ -158,7 +158,7 @@ resource "azurerm_cosmosdb_cassandra_keyspace" "test" { throughput = %[3]d } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}), data.RandomInteger, throughput) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}), data.RandomInteger, throughput) } func (CosmosDbCassandraKeyspaceResource) autoscale(data acceptance.TestData, maxThroughput int) string { @@ -173,7 +173,7 @@ resource "azurerm_cosmosdb_cassandra_keyspace" "test" { max_throughput = %[3]d } } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}), data.RandomInteger, maxThroughput) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra"}), data.RandomInteger, maxThroughput) } func (CosmosDbCassandraKeyspaceResource) serverless(data acceptance.TestData) string { @@ -185,5 +185,5 @@ resource "azurerm_cosmosdb_cassandra_keyspace" "test" { resource_group_name = azurerm_cosmosdb_account.test.resource_group_name account_name = azurerm_cosmosdb_account.test.name } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra", "EnableServerless"}), data.RandomInteger) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableCassandra", "EnableServerless"}), data.RandomInteger) } diff --git a/internal/services/cosmos/cosmosdb_mongo_collection_resource_test.go b/internal/services/cosmos/cosmosdb_mongo_collection_resource_test.go index 37380ea1b3f5..554f1aa5eb95 100644 --- a/internal/services/cosmos/cosmosdb_mongo_collection_resource_test.go +++ b/internal/services/cosmos/cosmosdb_mongo_collection_resource_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -410,7 +410,7 @@ resource "azurerm_cosmosdb_mongo_collection" "test" { unique = true } } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindMongoDB, []string{"EnableMongo"}), data.RandomInteger) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindMongoDB, []string{"EnableMongo"}), data.RandomInteger) } func (CosmosMongoCollectionResource) serverless(data acceptance.TestData) string { @@ -434,7 +434,7 @@ resource "azurerm_cosmosdb_mongo_collection" "test" { unique = true } } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindMongoDB, []string{"EnableMongo", "EnableServerless"}), data.RandomInteger) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindMongoDB, []string{"EnableMongo", "EnableServerless"}), data.RandomInteger) } func (CosmosMongoCollectionResource) analyticalStorageTTL(data acceptance.TestData) string { @@ -460,7 +460,7 @@ resource "azurerm_cosmosdb_mongo_collection" "test" { analytical_storage_ttl = 600 } -`, CosmosDBAccountResource{}.mongoAnalyticalStorage(data, documentdb.DefaultConsistencyLevelEventual), data.RandomInteger, data.RandomInteger) +`, CosmosDBAccountResource{}.mongoAnalyticalStorage(data, cosmosdb.DefaultConsistencyLevelEventual), data.RandomInteger, data.RandomInteger) } func (CosmosMongoCollectionResource) autoscaleWithoutShareKey(data acceptance.TestData) string { diff --git a/internal/services/cosmos/cosmosdb_mongo_database_resource_test.go b/internal/services/cosmos/cosmosdb_mongo_database_resource_test.go index 50b3d7a1055a..0efc348dac3e 100644 --- a/internal/services/cosmos/cosmosdb_mongo_database_resource_test.go +++ b/internal/services/cosmos/cosmosdb_mongo_database_resource_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -122,7 +122,7 @@ resource "azurerm_cosmosdb_mongo_database" "test" { resource_group_name = azurerm_cosmosdb_account.test.resource_group_name account_name = azurerm_cosmosdb_account.test.name } -`, CosmosDBAccountResource{}.basicMongoDB(data, documentdb.DefaultConsistencyLevelStrong), data.RandomInteger) +`, CosmosDBAccountResource{}.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelStrong), data.RandomInteger) } func (CosmosMongoDatabaseResource) complete(data acceptance.TestData) string { @@ -135,7 +135,7 @@ resource "azurerm_cosmosdb_mongo_database" "test" { account_name = azurerm_cosmosdb_account.test.name throughput = 700 } -`, CosmosDBAccountResource{}.basicMongoDB(data, documentdb.DefaultConsistencyLevelStrong), data.RandomInteger) +`, CosmosDBAccountResource{}.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelStrong), data.RandomInteger) } func (CosmosMongoDatabaseResource) autoscale(data acceptance.TestData, maxThroughput int) string { @@ -150,7 +150,7 @@ resource "azurerm_cosmosdb_mongo_database" "test" { max_throughput = %[3]d } } -`, CosmosDBAccountResource{}.basicMongoDB(data, documentdb.DefaultConsistencyLevelStrong), data.RandomInteger, maxThroughput) +`, CosmosDBAccountResource{}.basicMongoDB(data, cosmosdb.DefaultConsistencyLevelStrong), data.RandomInteger, maxThroughput) } func (CosmosMongoDatabaseResource) serverless(data acceptance.TestData) string { @@ -162,7 +162,7 @@ resource "azurerm_cosmosdb_mongo_database" "test" { resource_group_name = azurerm_cosmosdb_account.test.resource_group_name account_name = azurerm_cosmosdb_account.test.name } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindMongoDB, []string{"EnableServerless", "mongoEnableDocLevelTTL", "EnableMongo"}), data.RandomInteger) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindMongoDB, []string{"EnableServerless", "mongoEnableDocLevelTTL", "EnableMongo"}), data.RandomInteger) } func checkAccCosmosDBAccount_mongodb(resourceName string) acceptance.TestCheckFunc { diff --git a/internal/services/cosmos/cosmosdb_sql_database_resource_test.go b/internal/services/cosmos/cosmosdb_sql_database_resource_test.go index 48497f8dba66..f27cdac5521a 100644 --- a/internal/services/cosmos/cosmosdb_sql_database_resource_test.go +++ b/internal/services/cosmos/cosmosdb_sql_database_resource_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -128,7 +128,7 @@ resource "azurerm_cosmosdb_sql_database" "test" { resource_group_name = azurerm_cosmosdb_account.test.resource_group_name account_name = azurerm_cosmosdb_account.test.name } -`, CosmosDBAccountResource{}.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelStrong), data.RandomInteger) +`, CosmosDBAccountResource{}.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelStrong), data.RandomInteger) } func (CosmosSqlDatabaseResource) throughput(data acceptance.TestData, throughput int) string { @@ -141,7 +141,7 @@ resource "azurerm_cosmosdb_sql_database" "test" { account_name = azurerm_cosmosdb_account.test.name throughput = %[3]d } -`, CosmosDBAccountResource{}.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelStrong), data.RandomInteger, throughput) +`, CosmosDBAccountResource{}.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelStrong), data.RandomInteger, throughput) } func (CosmosSqlDatabaseResource) autoscale(data acceptance.TestData, maxThroughput int) string { @@ -156,7 +156,7 @@ resource "azurerm_cosmosdb_sql_database" "test" { max_throughput = %[3]d } } -`, CosmosDBAccountResource{}.basic(data, documentdb.DatabaseAccountKindGlobalDocumentDB, documentdb.DefaultConsistencyLevelStrong), data.RandomInteger, maxThroughput) +`, CosmosDBAccountResource{}.basic(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, cosmosdb.DefaultConsistencyLevelStrong), data.RandomInteger, maxThroughput) } func (CosmosSqlDatabaseResource) serverless(data acceptance.TestData) string { @@ -167,5 +167,5 @@ resource "azurerm_cosmosdb_sql_database" "test" { resource_group_name = azurerm_cosmosdb_account.test.resource_group_name account_name = azurerm_cosmosdb_account.test.name } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableServerless"}), data.RandomInteger) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableServerless"}), data.RandomInteger) } diff --git a/internal/services/cosmos/cosmosdb_table_resource_test.go b/internal/services/cosmos/cosmosdb_table_resource_test.go index f7f5a457d75d..ee43638588fd 100644 --- a/internal/services/cosmos/cosmosdb_table_resource_test.go +++ b/internal/services/cosmos/cosmosdb_table_resource_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" // nolint: staticcheck + "github.com/hashicorp/go-azure-sdk/resource-manager/cosmosdb/2023-04-15/cosmosdb" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -128,7 +128,7 @@ resource "azurerm_cosmosdb_table" "test" { resource_group_name = azurerm_cosmosdb_account.test.resource_group_name account_name = azurerm_cosmosdb_account.test.name } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableTable"}), data.RandomInteger) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableTable"}), data.RandomInteger) } func (CosmosTableResource) throughput(data acceptance.TestData, throughput int) string { @@ -141,7 +141,7 @@ resource "azurerm_cosmosdb_table" "test" { account_name = azurerm_cosmosdb_account.test.name throughput = %[3]d } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableTable"}), data.RandomInteger, throughput) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableTable"}), data.RandomInteger, throughput) } func (CosmosTableResource) autoscale(data acceptance.TestData, maxThroughput int) string { @@ -156,7 +156,7 @@ resource "azurerm_cosmosdb_table" "test" { max_throughput = %[3]d } } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableTable"}), data.RandomInteger, maxThroughput) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableTable"}), data.RandomInteger, maxThroughput) } func (CosmosTableResource) serverless(data acceptance.TestData) string { @@ -168,5 +168,5 @@ resource "azurerm_cosmosdb_table" "test" { resource_group_name = azurerm_cosmosdb_account.test.resource_group_name account_name = azurerm_cosmosdb_account.test.name } -`, CosmosDBAccountResource{}.capabilities(data, documentdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableServerless", "EnableTable"}), data.RandomInteger) +`, CosmosDBAccountResource{}.capabilities(data, cosmosdb.DatabaseAccountKindGlobalDocumentDB, []string{"EnableServerless", "EnableTable"}), data.RandomInteger) } From ecab3fa21fef77182469c01f1bbf00ec1218c86e Mon Sep 17 00:00:00 2001 From: neil-yechenwei Date: Thu, 18 Jan 2024 14:11:54 +0800 Subject: [PATCH 2/9] update code --- .../2023-03-01/virtualmachineruncommands/method_list.go | 6 ++++-- .../method_listbyvirtualmachine.go | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2023-03-01/virtualmachineruncommands/method_list.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2023-03-01/virtualmachineruncommands/method_list.go index 4be6ff8e234b..ad9508c86fab 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2023-03-01/virtualmachineruncommands/method_list.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2023-03-01/virtualmachineruncommands/method_list.go @@ -19,7 +19,8 @@ type ListOperationResponse struct { } type ListCompleteResult struct { - Items []RunCommandDocumentBase + LatestHttpResponse *http.Response + Items []RunCommandDocumentBase } // List ... @@ -83,7 +84,8 @@ func (c VirtualMachineRunCommandsClient) ListCompleteMatchingPredicate(ctx conte } result = ListCompleteResult{ - Items: items, + LatestHttpResponse: resp.HttpResponse, + Items: items, } return } diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2023-03-01/virtualmachineruncommands/method_listbyvirtualmachine.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2023-03-01/virtualmachineruncommands/method_listbyvirtualmachine.go index a465a85c558b..d59a8c256bbb 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2023-03-01/virtualmachineruncommands/method_listbyvirtualmachine.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2023-03-01/virtualmachineruncommands/method_listbyvirtualmachine.go @@ -19,7 +19,8 @@ type ListByVirtualMachineOperationResponse struct { } type ListByVirtualMachineCompleteResult struct { - Items []VirtualMachineRunCommand + LatestHttpResponse *http.Response + Items []VirtualMachineRunCommand } type ListByVirtualMachineOperationOptions struct { @@ -111,7 +112,8 @@ func (c VirtualMachineRunCommandsClient) ListByVirtualMachineCompleteMatchingPre } result = ListByVirtualMachineCompleteResult{ - Items: items, + LatestHttpResponse: resp.HttpResponse, + Items: items, } return } From 2b902843862cd3586d6a28b622ce18ed06b83838 Mon Sep 17 00:00:00 2001 From: neil-yechenwei Date: Thu, 18 Jan 2024 14:19:08 +0800 Subject: [PATCH 3/9] update code --- internal/services/cosmos/cosmosdb_account_resource.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/services/cosmos/cosmosdb_account_resource.go b/internal/services/cosmos/cosmosdb_account_resource.go index 33e3c07adfbc..f702cf6b3e8f 100644 --- a/internal/services/cosmos/cosmosdb_account_resource.go +++ b/internal/services/cosmos/cosmosdb_account_resource.go @@ -1327,7 +1327,7 @@ func resourceCosmosDbAccountRead(d *pluginsdk.ResourceData, meta interface{}) er d.Set("analytical_storage_enabled", props.EnableAnalyticalStorage) d.Set("public_network_access_enabled", pointer.From(props.PublicNetworkAccess) == cosmosdb.PublicNetworkAccessEnabled) d.Set("default_identity_type", props.DefaultIdentity) - d.Set("create_mode", props.CreateMode) + d.Set("create_mode", string(pointer.From(props.CreateMode))) if v := props.IsVirtualNetworkFilterEnabled; v != nil { d.Set("is_virtual_network_filter_enabled", props.IsVirtualNetworkFilterEnabled) @@ -1375,7 +1375,7 @@ func resourceCosmosDbAccountRead(d *pluginsdk.ResourceData, meta interface{}) er d.Set("access_key_metadata_writes_enabled", !*props.DisableKeyBasedMetadataWriteAccess) if apiProps := props.ApiProperties; apiProps != nil { - d.Set("mongo_server_version", apiProps.ServerVersion) + d.Set("mongo_server_version", string(pointer.From(apiProps.ServerVersion))) } d.Set("network_acl_bypass_for_azure_services", pointer.From(props.NetworkAclBypass) == cosmosdb.NetworkAclBypassAzureServices) d.Set("network_acl_bypass_ids", utils.FlattenStringSlice(props.NetworkAclBypassResourceIds)) From fa882fdaaa29cde2518ed501c139ea5f01895050 Mon Sep 17 00:00:00 2001 From: neil-yechenwei Date: Thu, 18 Jan 2024 14:42:05 +0800 Subject: [PATCH 4/9] update code --- .../services/cosmos/cosmosdb_account_resource.go | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/internal/services/cosmos/cosmosdb_account_resource.go b/internal/services/cosmos/cosmosdb_account_resource.go index f702cf6b3e8f..2c91ef41e7a1 100644 --- a/internal/services/cosmos/cosmosdb_account_resource.go +++ b/internal/services/cosmos/cosmosdb_account_resource.go @@ -1912,29 +1912,24 @@ func flattenCosmosdbAccountBackup(input cosmosdb.BackupPolicy) ([]interface{}, e return []interface{}{}, nil } - switch input.(type) { + switch backupPolicy := input.(type) { case cosmosdb.ContinuousModeBackupPolicy: return []interface{}{ map[string]interface{}{ "type": string(cosmosdb.BackupPolicyTypeContinuous), }, }, nil - case cosmosdb.PeriodicModeBackupPolicy: - policy, ok := input.(cosmosdb.PeriodicModeBackupPolicy) - if !ok { - return nil, fmt.Errorf("can not transit %+v into `backup` of `type` `Periodic`", input) - } var interval, retention int - if v := policy.PeriodicModeProperties.BackupIntervalInMinutes; v != nil { + if v := backupPolicy.PeriodicModeProperties.BackupIntervalInMinutes; v != nil { interval = int(*v) } - if v := policy.PeriodicModeProperties.BackupRetentionIntervalInHours; v != nil { + if v := backupPolicy.PeriodicModeProperties.BackupRetentionIntervalInHours; v != nil { retention = int(*v) } var storageRedundancy cosmosdb.BackupStorageRedundancy - if policy.PeriodicModeProperties.BackupStorageRedundancy != nil { - storageRedundancy = pointer.From(policy.PeriodicModeProperties.BackupStorageRedundancy) + if backupPolicy.PeriodicModeProperties.BackupStorageRedundancy != nil { + storageRedundancy = pointer.From(backupPolicy.PeriodicModeProperties.BackupStorageRedundancy) } return []interface{}{ map[string]interface{}{ @@ -1944,7 +1939,6 @@ func flattenCosmosdbAccountBackup(input cosmosdb.BackupPolicy) ([]interface{}, e "storage_redundancy": storageRedundancy, }, }, nil - default: return nil, fmt.Errorf("unknown `type` in `backup`: %+v", input) } From c6f9864241cd6d29c2c65b2f9f59da200ed407dc Mon Sep 17 00:00:00 2001 From: neil-yechenwei Date: Thu, 18 Jan 2024 15:26:12 +0800 Subject: [PATCH 5/9] update code --- internal/services/cosmos/cosmosdb_account_resource.go | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/internal/services/cosmos/cosmosdb_account_resource.go b/internal/services/cosmos/cosmosdb_account_resource.go index 2c91ef41e7a1..7d4528562217 100644 --- a/internal/services/cosmos/cosmosdb_account_resource.go +++ b/internal/services/cosmos/cosmosdb_account_resource.go @@ -754,15 +754,11 @@ func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) r, err := client.DatabaseAccountsCheckNameExists(ctx, cosmosdb.NewDatabaseAccountNameID(id.DatabaseAccountName)) if err != nil { - // TODO: remove when https://github.com/Azure/azure-sdk-for-go/issues/9891 is fixed - if r.HttpResponse == nil || r.HttpResponse.StatusCode != http.StatusInternalServerError { - return fmt.Errorf("checking if CosmosDB Account %s: %+v", id, err) - } - } else { - if r.HttpResponse == nil || r.HttpResponse.StatusCode != http.StatusNotFound { + if !response.WasNotFound(r.HttpResponse) { return fmt.Errorf("CosmosDB Account %s already exists, please import the resource via terraform import", id.DatabaseAccountName) } } + geoLocations, err := expandAzureRmCosmosDBAccountGeoLocations(d) if err != nil { return fmt.Errorf("expanding %s geo locations: %+v", id, err) From d3fef476822373c98236bcc9168c6d04d938726c Mon Sep 17 00:00:00 2001 From: neil-yechenwei Date: Thu, 18 Jan 2024 15:41:20 +0800 Subject: [PATCH 6/9] update code --- internal/services/cosmos/cosmosdb_account_resource.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/internal/services/cosmos/cosmosdb_account_resource.go b/internal/services/cosmos/cosmosdb_account_resource.go index 7d4528562217..7ccc94a89193 100644 --- a/internal/services/cosmos/cosmosdb_account_resource.go +++ b/internal/services/cosmos/cosmosdb_account_resource.go @@ -752,11 +752,9 @@ func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) enableAnalyticalStorage := d.Get("analytical_storage_enabled").(bool) disableLocalAuthentication := d.Get("local_authentication_disabled").(bool) - r, err := client.DatabaseAccountsCheckNameExists(ctx, cosmosdb.NewDatabaseAccountNameID(id.DatabaseAccountName)) - if err != nil { - if !response.WasNotFound(r.HttpResponse) { - return fmt.Errorf("CosmosDB Account %s already exists, please import the resource via terraform import", id.DatabaseAccountName) - } + r, _ := client.DatabaseAccountsCheckNameExists(ctx, cosmosdb.NewDatabaseAccountNameID(id.DatabaseAccountName)) + if !response.WasNotFound(r.HttpResponse) { + return fmt.Errorf("CosmosDB Account %s already exists, please import the resource via terraform import", id.DatabaseAccountName) } geoLocations, err := expandAzureRmCosmosDBAccountGeoLocations(d) From aa944e337fc211eea6eefc4ffc56a66a8872fd78 Mon Sep 17 00:00:00 2001 From: neil-yechenwei Date: Fri, 19 Jan 2024 15:06:18 +0800 Subject: [PATCH 7/9] update code --- .../cosmos/cosmosdb_account_resource.go | 909 +++++++++--------- 1 file changed, 448 insertions(+), 461 deletions(-) diff --git a/internal/services/cosmos/cosmosdb_account_resource.go b/internal/services/cosmos/cosmosdb_account_resource.go index 7ccc94a89193..9e0f248f0b47 100644 --- a/internal/services/cosmos/cosmosdb_account_resource.go +++ b/internal/services/cosmos/cosmosdb_account_resource.go @@ -713,6 +713,7 @@ func resourceCosmosDbAccount() *pluginsdk.Resource { func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) error { client := meta.(*clients.Client).Cosmos.CosmosDBClient + databaseClient := meta.(*clients.Client).Cosmos.DatabaseClient subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -752,11 +753,17 @@ func resourceCosmosDbAccountCreate(d *pluginsdk.ResourceData, meta interface{}) enableAnalyticalStorage := d.Get("analytical_storage_enabled").(bool) disableLocalAuthentication := d.Get("local_authentication_disabled").(bool) - r, _ := client.DatabaseAccountsCheckNameExists(ctx, cosmosdb.NewDatabaseAccountNameID(id.DatabaseAccountName)) - if !response.WasNotFound(r.HttpResponse) { - return fmt.Errorf("CosmosDB Account %s already exists, please import the resource via terraform import", id.DatabaseAccountName) + r, err := databaseClient.CheckNameExists(ctx, id.DatabaseAccountName) + if err != nil { + // TODO: remove when https://github.com/Azure/azure-sdk-for-go/issues/9891 is fixed + if !utils.ResponseWasStatusCode(r, http.StatusInternalServerError) { + return fmt.Errorf("checking if CosmosDB Account %s: %+v", id, err) + } + } else { + if !utils.ResponseWasNotFound(r) { + return fmt.Errorf("CosmosDB Account %s already exists, please import the resource via terraform import", id.DatabaseAccountName) + } } - geoLocations, err := expandAzureRmCosmosDBAccountGeoLocations(d) if err != nil { return fmt.Errorf("expanding %s geo locations: %+v", id, err) @@ -892,379 +899,379 @@ func resourceCosmosDbAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) return fmt.Errorf("making Read request on %s: %s", id, err) } - if model := existing.Model; model != nil { - configLocations, err := expandAzureRmCosmosDBAccountGeoLocations(d) - if err != nil { - return fmt.Errorf("expanding %s geo locations: %+v", id, err) - } + if existing.Model == nil { + return fmt.Errorf("retrieving %s: properties were nil", id) + } - // Normalize Locations... - cosmosLocations := make([]cosmosdb.Location, 0) - cosmosLocationsMap := map[string]cosmosdb.Location{} + configLocations, err := expandAzureRmCosmosDBAccountGeoLocations(d) + if err != nil { + return fmt.Errorf("expanding %s geo locations: %+v", id, err) + } - if model.Properties.Locations != nil { - for _, l := range *model.Properties.Locations { - location := cosmosdb.Location{ - Id: l.Id, - LocationName: l.LocationName, - FailoverPriority: l.FailoverPriority, - IsZoneRedundant: l.IsZoneRedundant, - } + // Normalize Locations... + cosmosLocations := make([]cosmosdb.Location, 0) + cosmosLocationsMap := map[string]cosmosdb.Location{} - cosmosLocations = append(cosmosLocations, location) - cosmosLocationsMap[azure.NormalizeLocation(*location.LocationName)] = location + if existing.Model.Properties.Locations != nil { + for _, l := range *existing.Model.Properties.Locations { + location := cosmosdb.Location{ + Id: l.Id, + LocationName: l.LocationName, + FailoverPriority: l.FailoverPriority, + IsZoneRedundant: l.IsZoneRedundant, } - } - var capabilities *[]cosmosdb.Capability - if model.Properties.Capabilities != nil { - capabilities = model.Properties.Capabilities + cosmosLocations = append(cosmosLocations, location) + cosmosLocationsMap[azure.NormalizeLocation(*location.LocationName)] = location } + } - // backup must be updated independently - var backup cosmosdb.BackupPolicy - if model.Properties.BackupPolicy != nil { - backup = model.Properties.BackupPolicy - if d.HasChange("backup") { - if v, ok := d.GetOk("backup"); ok { - newBackup, err := expandCosmosdbAccountBackup(v.([]interface{}), d.HasChange("backup.0.type"), string(pointer.From(model.Properties.CreateMode))) - if err != nil { - return fmt.Errorf("expanding `backup`: %+v", err) - } - updateParameters := cosmosdb.DatabaseAccountUpdateParameters{ - Properties: &cosmosdb.DatabaseAccountUpdateProperties{ - BackupPolicy: newBackup, - }, - } + var capabilities *[]cosmosdb.Capability + if existing.Model.Properties.Capabilities != nil { + capabilities = existing.Model.Properties.Capabilities + } - // Update Database 'backup'... - if err := client.DatabaseAccountsUpdateThenPoll(ctx, *id, updateParameters); err != nil { - return fmt.Errorf("updating %q: %+v", id, err) - } + // backup must be updated independently + var backup cosmosdb.BackupPolicy + if existing.Model.Properties.BackupPolicy != nil { + backup = existing.Model.Properties.BackupPolicy + if d.HasChange("backup") { + if v, ok := d.GetOk("backup"); ok { + newBackup, err := expandCosmosdbAccountBackup(v.([]interface{}), d.HasChange("backup.0.type"), string(pointer.From(existing.Model.Properties.CreateMode))) + if err != nil { + return fmt.Errorf("expanding `backup`: %+v", err) + } + updateParameters := cosmosdb.DatabaseAccountUpdateParameters{ + Properties: &cosmosdb.DatabaseAccountUpdateProperties{ + BackupPolicy: newBackup, + }, + } - backup = newBackup - } else if string(pointer.From(model.Properties.CreateMode)) != "" { - return fmt.Errorf("`create_mode` only works when `backup.type` is `Continuous`") + // Update Database 'backup'... + if err := client.DatabaseAccountsUpdateThenPoll(ctx, *id, updateParameters); err != nil { + return fmt.Errorf("updating CosmosDB Account %q (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err) } + + backup = newBackup + } else if string(pointer.From(existing.Model.Properties.CreateMode)) != "" { + return fmt.Errorf("`create_mode` only works when `backup.type` is `Continuous`") } } + } - updateRequired := false - if props := model.Properties; props != nil { - location := azure.NormalizeLocation(pointer.From(model.Location)) - offerType := d.Get("offer_type").(string) - t := tags.Expand(d.Get("tags").(map[string]interface{})) - kind := cosmosdb.DatabaseAccountKind(d.Get("kind").(string)) - isVirtualNetworkFilterEnabled := pointer.To(d.Get("is_virtual_network_filter_enabled").(bool)) - enableFreeTier := pointer.To(d.Get("enable_free_tier").(bool)) - enableAutomaticFailover := pointer.To(d.Get("enable_automatic_failover").(bool)) - enableAnalyticalStorage := pointer.To(d.Get("analytical_storage_enabled").(bool)) - disableLocalAuthentication := pointer.To(d.Get("local_authentication_disabled").(bool)) - - networkByPass := cosmosdb.NetworkAclBypassNone - if d.Get("network_acl_bypass_for_azure_services").(bool) { - networkByPass = cosmosdb.NetworkAclBypassAzureServices - } + updateRequired := false + if props := existing.Model.Properties; props != nil { + location := azure.NormalizeLocation(pointer.From(existing.Model.Location)) + offerType := d.Get("offer_type").(string) + t := tags.Expand(d.Get("tags").(map[string]interface{})) + kind := cosmosdb.DatabaseAccountKind(d.Get("kind").(string)) + isVirtualNetworkFilterEnabled := pointer.To(d.Get("is_virtual_network_filter_enabled").(bool)) + enableFreeTier := pointer.To(d.Get("enable_free_tier").(bool)) + enableAutomaticFailover := pointer.To(d.Get("enable_automatic_failover").(bool)) + enableAnalyticalStorage := pointer.To(d.Get("analytical_storage_enabled").(bool)) + disableLocalAuthentication := pointer.To(d.Get("local_authentication_disabled").(bool)) + + networkByPass := cosmosdb.NetworkAclBypassNone + if d.Get("network_acl_bypass_for_azure_services").(bool) { + networkByPass = cosmosdb.NetworkAclBypassAzureServices + } - var ipRangeFilter *[]cosmosdb.IPAddressOrRange - if features.FourPointOhBeta() { - ipRangeFilter = common.CosmosDBIpRangeFilterToIpRules(*utils.ExpandStringSlice(d.Get("ip_range_filter").(*pluginsdk.Set).List())) - } else { - ipRangeFilter = common.CosmosDBIpRangeFilterToIpRulesThreePointOh(d.Get("ip_range_filter").(string)) - } + var ipRangeFilter *[]cosmosdb.IPAddressOrRange + if features.FourPointOhBeta() { + ipRangeFilter = common.CosmosDBIpRangeFilterToIpRules(*utils.ExpandStringSlice(d.Get("ip_range_filter").(*pluginsdk.Set).List())) + } else { + ipRangeFilter = common.CosmosDBIpRangeFilterToIpRulesThreePointOh(d.Get("ip_range_filter").(string)) + } - publicNetworkAccess := cosmosdb.PublicNetworkAccessEnabled - if enabled := d.Get("public_network_access_enabled").(bool); !enabled { - publicNetworkAccess = cosmosdb.PublicNetworkAccessDisabled - } + publicNetworkAccess := cosmosdb.PublicNetworkAccessEnabled + if enabled := d.Get("public_network_access_enabled").(bool); !enabled { + publicNetworkAccess = cosmosdb.PublicNetworkAccessDisabled + } - // NOTE: these fields are expanded directly into the - // 'DatabaseAccountCreateUpdateParameters' below or - // are included in the 'DatabaseAccountCreateUpdateParameters' - // later, however we need to know if they changed or not... - if d.HasChanges("consistency_policy", "virtual_network_rule", "cors_rule", "access_key_metadata_writes_enabled", - "network_acl_bypass_for_azure_services", "network_acl_bypass_ids", "analytical_storage", - "capacity", "create_mode", "restore", "key_vault_key_id", "mongo_server_version", - "public_network_access_enabled", "ip_range_filter", "offer_type", "is_virtual_network_filter_enabled", - "kind", "tags", "enable_free_tier", "enable_automatic_failover", "analytical_storage_enabled", - "local_authentication_disabled") { - updateRequired = true - } + // NOTE: these fields are expanded directly into the + // 'DatabaseAccountCreateUpdateParameters' below or + // are included in the 'DatabaseAccountCreateUpdateParameters' + // later, however we need to know if they changed or not... + if d.HasChanges("consistency_policy", "virtual_network_rule", "cors_rule", "access_key_metadata_writes_enabled", + "network_acl_bypass_for_azure_services", "network_acl_bypass_ids", "analytical_storage", + "capacity", "create_mode", "restore", "key_vault_key_id", "mongo_server_version", + "public_network_access_enabled", "ip_range_filter", "offer_type", "is_virtual_network_filter_enabled", + "kind", "tags", "enable_free_tier", "enable_automatic_failover", "analytical_storage_enabled", + "local_authentication_disabled") { + updateRequired = true + } - // Incident : #383341730 - // Azure Bug: #2209567 'Updating identities and default identity at the same time fails silently' - // - // The 'Identity' field should only ever be sent once to the endpoint, except for updates and removal. If the - // 'Identity' field is included in the update call with the 'DefaultIdentity' it will silently fail - // per the bug noted above (e.g. Azure Bug #2209567). - // - // In the update scenario where the end-user would like to update their 'Identity' and their 'DefaultIdentity' - // fields at the same time both of these operations need to happen atomically in separate PUT/PATCH calls - // to the service else you will hit the bug mentioned above. You need to update the 'Identity' field - // first then update the 'DefaultIdentity' in totally different PUT/PATCH calls where you have to drop - // the 'Identity' field on the floor when updating the 'DefaultIdentity' field. - // - // NOTE : If the 'Identity' field has not changed in the resource, do not send it in the payload. - // this workaround can be removed once the service team fixes the above mentioned bug. - // - // ADDITIONAL: You cannot update properties and add/remove replication locations or update the enabling of - // multiple write locations at the same time. So you must update any changed properties - // first, then address the replication locations and/or updating/enabling of - // multiple write locations. - - account := cosmosdb.DatabaseAccountCreateUpdateParameters{ - Location: pointer.To(location), - Kind: pointer.To(kind), - Properties: cosmosdb.DatabaseAccountCreateUpdateProperties{ - DatabaseAccountOfferType: cosmosdb.DatabaseAccountOfferType(offerType), - IPRules: ipRangeFilter, - IsVirtualNetworkFilterEnabled: isVirtualNetworkFilterEnabled, - EnableFreeTier: enableFreeTier, - EnableAutomaticFailover: enableAutomaticFailover, - Capabilities: capabilities, - ConsistencyPolicy: expandAzureRmCosmosDBAccountConsistencyPolicy(d), - Locations: cosmosLocations, - VirtualNetworkRules: expandAzureRmCosmosDBAccountVirtualNetworkRules(d), - EnableMultipleWriteLocations: props.EnableMultipleWriteLocations, - PublicNetworkAccess: pointer.To(publicNetworkAccess), - EnableAnalyticalStorage: enableAnalyticalStorage, - Cors: common.ExpandCosmosCorsRule(d.Get("cors_rule").([]interface{})), - DisableKeyBasedMetadataWriteAccess: pointer.To(!d.Get("access_key_metadata_writes_enabled").(bool)), - NetworkAclBypass: pointer.To(networkByPass), - NetworkAclBypassResourceIds: utils.ExpandStringSlice(d.Get("network_acl_bypass_ids").([]interface{})), - DisableLocalAuth: disableLocalAuthentication, - BackupPolicy: backup, - }, - Tags: t, + // Incident : #383341730 + // Azure Bug: #2209567 'Updating identities and default identity at the same time fails silently' + // + // The 'Identity' field should only ever be sent once to the endpoint, except for updates and removal. If the + // 'Identity' field is included in the update call with the 'DefaultIdentity' it will silently fail + // per the bug noted above (e.g. Azure Bug #2209567). + // + // In the update scenario where the end-user would like to update their 'Identity' and their 'DefaultIdentity' + // fields at the same time both of these operations need to happen atomically in separate PUT/PATCH calls + // to the service else you will hit the bug mentioned above. You need to update the 'Identity' field + // first then update the 'DefaultIdentity' in totally different PUT/PATCH calls where you have to drop + // the 'Identity' field on the floor when updating the 'DefaultIdentity' field. + // + // NOTE : If the 'Identity' field has not changed in the resource, do not send it in the payload. + // this workaround can be removed once the service team fixes the above mentioned bug. + // + // ADDITIONAL: You cannot update properties and add/remove replication locations or update the enabling of + // multiple write locations at the same time. So you must update any changed properties + // first, then address the replication locations and/or updating/enabling of + // multiple write locations. + + account := cosmosdb.DatabaseAccountCreateUpdateParameters{ + Location: pointer.To(location), + Kind: pointer.To(kind), + Properties: cosmosdb.DatabaseAccountCreateUpdateProperties{ + DatabaseAccountOfferType: cosmosdb.DatabaseAccountOfferType(offerType), + IPRules: ipRangeFilter, + IsVirtualNetworkFilterEnabled: isVirtualNetworkFilterEnabled, + EnableFreeTier: enableFreeTier, + EnableAutomaticFailover: enableAutomaticFailover, + Capabilities: capabilities, + ConsistencyPolicy: expandAzureRmCosmosDBAccountConsistencyPolicy(d), + Locations: cosmosLocations, + VirtualNetworkRules: expandAzureRmCosmosDBAccountVirtualNetworkRules(d), + EnableMultipleWriteLocations: props.EnableMultipleWriteLocations, + PublicNetworkAccess: pointer.To(publicNetworkAccess), + EnableAnalyticalStorage: enableAnalyticalStorage, + Cors: common.ExpandCosmosCorsRule(d.Get("cors_rule").([]interface{})), + DisableKeyBasedMetadataWriteAccess: pointer.To(!d.Get("access_key_metadata_writes_enabled").(bool)), + NetworkAclBypass: pointer.To(networkByPass), + NetworkAclBypassResourceIds: utils.ExpandStringSlice(d.Get("network_acl_bypass_ids").([]interface{})), + DisableLocalAuth: disableLocalAuthentication, + BackupPolicy: backup, + }, + Tags: t, + } + + if keyVaultKeyIDRaw, ok := d.GetOk("key_vault_key_id"); ok { + keyVaultKey, err := keyVaultParse.ParseOptionallyVersionedNestedItemID(keyVaultKeyIDRaw.(string)) + if err != nil { + return fmt.Errorf("could not parse Key Vault Key ID: %+v", err) } + account.Properties.KeyVaultKeyUri = pointer.To(keyVaultKey.ID()) + } - accountProps := account.Properties + // 'default_identity_type' will always have a value since it now has a default value of "FirstPartyIdentity" per the API documentation. + // I do not include 'DefaultIdentity' and 'Identity' in the 'accountProps' intentionally, these operations need to be + // performed mutually exclusive from each other in an atomic fashion, else you will hit the service teams bug... + updateDefaultIdentity := false + if d.HasChange("default_identity_type") { + updateDefaultIdentity = true + } - if keyVaultKeyIDRaw, ok := d.GetOk("key_vault_key_id"); ok { - keyVaultKey, err := keyVaultParse.ParseOptionallyVersionedNestedItemID(keyVaultKeyIDRaw.(string)) - if err != nil { - return fmt.Errorf("could not parse Key Vault Key ID: %+v", err) - } - accountProps.KeyVaultKeyUri = pointer.To(keyVaultKey.ID()) - } + // adding 'DefaultIdentity' to avoid causing it to fallback + // to "FirstPartyIdentity" on update(s), issue #22466 + if v, ok := d.GetOk("default_identity_type"); ok { + account.Properties.DefaultIdentity = pointer.To(v.(string)) + } - // 'default_identity_type' will always have a value since it now has a default value of "FirstPartyIdentity" per the API documentation. - // I do not include 'DefaultIdentity' and 'Identity' in the 'accountProps' intentionally, these operations need to be - // performed mutually exclusive from each other in an atomic fashion, else you will hit the service teams bug... - updateDefaultIdentity := false - if d.HasChange("default_identity_type") { - updateDefaultIdentity = true - } + // we need the following in the accountProps even if they have not changed... + if v, ok := d.GetOk("analytical_storage"); ok { + account.Properties.AnalyticalStorageConfiguration = expandCosmosDBAccountAnalyticalStorageConfiguration(v.([]interface{})) + } - // adding 'DefaultIdentity' to avoid causing it to fallback - // to "FirstPartyIdentity" on update(s), issue #22466 - if v, ok := d.GetOk("default_identity_type"); ok { - accountProps.DefaultIdentity = pointer.To(v.(string)) - } + if v, ok := d.GetOk("capacity"); ok { + account.Properties.Capacity = expandCosmosDBAccountCapacity(v.([]interface{})) + } - // we need the following in the accountProps even if they have not changed... - if v, ok := d.GetOk("analytical_storage"); ok { - accountProps.AnalyticalStorageConfiguration = expandCosmosDBAccountAnalyticalStorageConfiguration(v.([]interface{})) - } + var createMode string + if v, ok := d.GetOk("create_mode"); ok { + createMode = v.(string) + account.Properties.CreateMode = pointer.To(cosmosdb.CreateMode(createMode)) + } - if v, ok := d.GetOk("capacity"); ok { - accountProps.Capacity = expandCosmosDBAccountCapacity(v.([]interface{})) - } + if v, ok := d.GetOk("restore"); ok { + account.Properties.RestoreParameters = expandCosmosdbAccountRestoreParameters(v.([]interface{})) + } - var createMode string - if v, ok := d.GetOk("create_mode"); ok { - createMode = v.(string) - accountProps.CreateMode = pointer.To(cosmosdb.CreateMode(createMode)) + if v, ok := d.GetOk("mongo_server_version"); ok { + account.Properties.ApiProperties = &cosmosdb.ApiProperties{ + ServerVersion: pointer.To(cosmosdb.ServerVersion(v.(string))), } + } - if v, ok := d.GetOk("restore"); ok { - accountProps.RestoreParameters = expandCosmosdbAccountRestoreParameters(v.([]interface{})) - } + // Only do this update if a value has changed above... + if updateRequired { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DatabaseAccountCreateUpdateParameters'") - if v, ok := d.GetOk("mongo_server_version"); ok { - accountProps.ApiProperties = &cosmosdb.ApiProperties{ - ServerVersion: pointer.To(cosmosdb.ServerVersion(v.(string))), - } + // Update the database... + if err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, *id, account, d); err != nil { + return fmt.Errorf("updating %s: %+v", id, err) } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Update 'DatabaseAccountCreateUpdateParameters' [NO CHANGE]") + } - // Only do this update if a value has changed above... - if updateRequired { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DatabaseAccountCreateUpdateParameters'") + // Update the following properties independently after the initial CreateOrUpdate... + if d.HasChange("enable_multiple_write_locations") { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'EnableMultipleWriteLocations'") + + enableMultipleWriteLocations := pointer.To(d.Get("enable_multiple_write_locations").(bool)) + if props.EnableMultipleWriteLocations != enableMultipleWriteLocations { + account.Properties.EnableMultipleWriteLocations = enableMultipleWriteLocations // Update the database... if err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, *id, account, d); err != nil { - return fmt.Errorf("updating %s: %+v", id, err) + return fmt.Errorf("updating %q EnableMultipleWriteLocations: %+v", id, err) } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Update 'DatabaseAccountCreateUpdateParameters' [NO CHANGE]") } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'EnableMultipleWriteLocations' [NO CHANGE]") + } - // Update the following properties independently after the initial CreateOrUpdate... - if d.HasChange("enable_multiple_write_locations") { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'EnableMultipleWriteLocations'") - - enableMultipleWriteLocations := pointer.To(d.Get("enable_multiple_write_locations").(bool)) - if props.EnableMultipleWriteLocations != enableMultipleWriteLocations { - accountProps.EnableMultipleWriteLocations = enableMultipleWriteLocations - - // Update the database... - if err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, *id, account, d); err != nil { - return fmt.Errorf("updating %q EnableMultipleWriteLocations: %+v", id, err) + // determine if any locations have been renamed/priority reordered and remove them + updateLocations := false + for _, configLoc := range configLocations { + if cosmosLoc, ok := cosmosLocationsMap[pointer.From(configLoc.LocationName)]; ok { + // is the location in the config also in the database with the same 'FailoverPriority'? + if pointer.From(configLoc.FailoverPriority) != pointer.From(cosmosLoc.FailoverPriority) { + // The Failover Priority has been changed in the config... + if pointer.From(configLoc.FailoverPriority) == 0 { + return fmt.Errorf("cannot change the failover priority of %q location %q to %d", id, pointer.From(configLoc.LocationName), pointer.From(configLoc.FailoverPriority)) } + + // since the Locations FailoverPriority changed remove it from the map because + // we have to update the Location in the database. The Locations + // left in the map after this loop are the Locations that are + // the same in the database and in the config file... + delete(cosmosLocationsMap, pointer.From(configLoc.LocationName)) + updateLocations = true } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'EnableMultipleWriteLocations' [NO CHANGE]") } + } - // determine if any locations have been renamed/priority reordered and remove them - updateLocations := false - for _, configLoc := range configLocations { - if cosmosLoc, ok := cosmosLocationsMap[pointer.From(configLoc.LocationName)]; ok { - // is the location in the config also in the database with the same 'FailoverPriority'? - if pointer.From(configLoc.FailoverPriority) != pointer.From(cosmosLoc.FailoverPriority) { - // The Failover Priority has been changed in the config... - if pointer.From(configLoc.FailoverPriority) == 0 { - return fmt.Errorf("cannot change the failover priority of %q location %q to %d", id, pointer.From(configLoc.LocationName), pointer.From(configLoc.FailoverPriority)) - } - - // since the Locations FailoverPriority changed remove it from the map because - // we have to update the Location in the database. The Locations - // left in the map after this loop are the Locations that are - // the same in the database and in the config file... - delete(cosmosLocationsMap, pointer.From(configLoc.LocationName)) - updateLocations = true - } - } + if updateLocations { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Removing renamed 'Locations'") + locationsUnchanged := make([]cosmosdb.Location, 0, len(cosmosLocationsMap)) + for _, value := range cosmosLocationsMap { + locationsUnchanged = append(locationsUnchanged, value) } - if updateLocations { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Removing renamed 'Locations'") - locationsUnchanged := make([]cosmosdb.Location, 0, len(cosmosLocationsMap)) - for _, value := range cosmosLocationsMap { - locationsUnchanged = append(locationsUnchanged, value) - } + account.Properties.Locations = locationsUnchanged + + // Update the database... + if err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, *id, account, d); err != nil { + return fmt.Errorf("removing %q renamed `locations`: %+v", id, err) + } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Removing renamed 'Locations' [NO CHANGE]") + } - accountProps.Locations = locationsUnchanged + if d.HasChanges("geo_location") { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Locations'") + // add any new/renamed locations + account.Properties.Locations = configLocations - // Update the database... - if err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, *id, account, d); err != nil { - return fmt.Errorf("removing %q renamed `locations`: %+v", id, err) - } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Removing renamed 'Locations' [NO CHANGE]") + // Update the database locations... + err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, *id, account, d) + if err != nil { + return fmt.Errorf("updating %q `locations`: %+v", id, err) } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Locations' [NO CHANGE]") + } - if d.HasChanges("geo_location") { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Locations'") - // add any new/renamed locations - accountProps.Locations = configLocations + // Update Identity and Default Identity... + identityChanged := false + expandedIdentity, err := identity.ExpandLegacySystemAndUserAssignedMap(d.Get("identity").([]interface{})) + if err != nil { + return fmt.Errorf("expanding `identity`: %+v", err) + } - // Update the database locations... - err = resourceCosmosDbAccountApiCreateOrUpdate(client, ctx, *id, account, d) - if err != nil { - return fmt.Errorf("updating %q `locations`: %+v", id, err) - } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Locations' [NO CHANGE]") + if d.HasChange("identity") { + identityChanged = true + + // Looks like you have to always remove all the identities first before you can + // reassign/modify them, else it will append any new/changed identities + // resulting in a diff... + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Setting 'Identity' to 'None'") + + // can't set this back to account, because that will hit the bug... + identityVal := cosmosdb.DatabaseAccountUpdateParameters{ + Identity: pointer.To(identity.LegacySystemAndUserAssignedMap{ + Type: identity.TypeNone, + }), } - // Update Identity and Default Identity... - identityChanged := false - expandedIdentity, err := identity.ExpandLegacySystemAndUserAssignedMap(d.Get("identity").([]interface{})) + // Update the database 'Identity' to 'None'... + err = resourceCosmosDbAccountApiUpdate(client, ctx, *id, identityVal, d) if err != nil { - return fmt.Errorf("expanding `identity`: %+v", err) + return fmt.Errorf("updating 'identity' %q: %+v", id, err) } - if d.HasChange("identity") { - identityChanged = true - - // Looks like you have to always remove all the identities first before you can - // reassign/modify them, else it will append any new/changed identities - // resulting in a diff... - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Setting 'Identity' to 'None'") + // If the Identity was removed from the configuration file it will be set as type None + // so we can skip setting the Identity if it is going to be set to None... + if expandedIdentity.Type != identity.TypeNone { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Identity' to %q", expandedIdentity.Type) - // can't set this back to account, because that will hit the bug... identityVal := cosmosdb.DatabaseAccountUpdateParameters{ - Identity: pointer.To(identity.LegacySystemAndUserAssignedMap{ - Type: identity.TypeNone, - }), + Identity: expandedIdentity, } - // Update the database 'Identity' to 'None'... + // Update the database... err = resourceCosmosDbAccountApiUpdate(client, ctx, *id, identityVal, d) if err != nil { return fmt.Errorf("updating 'identity' %q: %+v", id, err) } + } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Identity' [NO CHANGE]") + } - // If the Identity was removed from the configuration file it will be set as type None - // so we can skip setting the Identity if it is going to be set to None... - if expandedIdentity.Type != identity.TypeNone { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Identity' to %q", expandedIdentity.Type) - - identityVal := cosmosdb.DatabaseAccountUpdateParameters{ - Identity: expandedIdentity, - } - - // Update the database... - err = resourceCosmosDbAccountApiUpdate(client, ctx, *id, identityVal, d) - if err != nil { - return fmt.Errorf("updating 'identity' %q: %+v", id, err) - } - } + // NOTE: updateDefaultIdentity now has a default value of 'FirstPartyIdentity'... This value now gets + // triggered if the default value does not match the value in Azure... + // + // NOTE: When you change the 'Identity', the 'DefaultIdentity' will be set to 'undefined', so if you change + // the identity you must also update the 'DefaultIdentity' as well... + if updateDefaultIdentity || identityChanged { + // This will now return the default of 'FirstPartyIdentity' if it + // is not set in the config, which is correct. + configDefaultIdentity := d.Get("default_identity_type").(string) + if identityChanged { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DefaultIdentity' to %q because the 'Identity' was changed to %q", configDefaultIdentity, expandedIdentity.Type) } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Identity' [NO CHANGE]") + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DefaultIdentity' to %q because 'default_identity_type' was changed", configDefaultIdentity) } - // NOTE: updateDefaultIdentity now has a default value of 'FirstPartyIdentity'... This value now gets - // triggered if the default value does not match the value in Azure... - // - // NOTE: When you change the 'Identity', the 'DefaultIdentity' will be set to 'undefined', so if you change - // the identity you must also update the 'DefaultIdentity' as well... - if updateDefaultIdentity || identityChanged { - // This will now return the default of 'FirstPartyIdentity' if it - // is not set in the config, which is correct. - configDefaultIdentity := d.Get("default_identity_type").(string) - if identityChanged { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DefaultIdentity' to %q because the 'Identity' was changed to %q", configDefaultIdentity, expandedIdentity.Type) - } else { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'DefaultIdentity' to %q because 'default_identity_type' was changed", configDefaultIdentity) - } - - // PATCH instead of PUT... - defaultIdentity := cosmosdb.DatabaseAccountUpdateParameters{ - Properties: &cosmosdb.DatabaseAccountUpdateProperties{ - DefaultIdentity: pointer.To(configDefaultIdentity), - }, - } + // PATCH instead of PUT... + defaultIdentity := cosmosdb.DatabaseAccountUpdateParameters{ + Properties: &cosmosdb.DatabaseAccountUpdateProperties{ + DefaultIdentity: pointer.To(configDefaultIdentity), + }, + } - // Update the database... - err = resourceCosmosDbAccountApiUpdate(client, ctx, *id, defaultIdentity, d) - if err != nil { - return fmt.Errorf("updating 'default_identity_type' %q: %+v", id, err) - } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'DefaultIdentity' [NO CHANGE]") + // Update the database... + err = resourceCosmosDbAccountApiUpdate(client, ctx, *id, defaultIdentity, d) + if err != nil { + return fmt.Errorf("updating 'default_identity_type' %q: %+v", id, err) } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'DefaultIdentity' [NO CHANGE]") + } + } - if props.Capabilities != nil { - if d.HasChange("capabilities") { - log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Capabilities'") + if existing.Model.Properties.Capabilities != nil { + if d.HasChange("capabilities") { + log.Printf("[INFO] Updating AzureRM Cosmos DB Account: Updating 'Capabilities'") - newCapabilities := expandAzureRmCosmosDBAccountCapabilities(d) - updateParameters := cosmosdb.DatabaseAccountUpdateParameters{ - Properties: &cosmosdb.DatabaseAccountUpdateProperties{ - Capabilities: newCapabilities, - }, - } + newCapabilities := expandAzureRmCosmosDBAccountCapabilities(d) + updateParameters := cosmosdb.DatabaseAccountUpdateParameters{ + Properties: &cosmosdb.DatabaseAccountUpdateProperties{ + Capabilities: newCapabilities, + }, + } - // Update Database 'capabilities'... - if err := client.DatabaseAccountsUpdateThenPoll(ctx, *id, updateParameters); err != nil { - return fmt.Errorf("updating %q: %+v", id, err) - } - } else { - log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Capabilities' [NO CHANGE]") - } + // Update Database 'capabilities'... + if err := client.DatabaseAccountsUpdateThenPoll(ctx, *id, updateParameters); err != nil { + return fmt.Errorf("updating CosmosDB Account %q (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err) } + } else { + log.Printf("[INFO] [SKIP] AzureRM Cosmos DB Account: Updating 'Capabilities' [NO CHANGE]") } } @@ -1288,140 +1295,133 @@ func resourceCosmosDbAccountRead(d *pluginsdk.ResourceData, meta interface{}) er return nil } - return fmt.Errorf("retrieving CosmosDB Account %q (Resource Group %q): %+v", id.DatabaseAccountName, id.DatabaseAccountName, err) + return fmt.Errorf("retrieving CosmosDB Account %q (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err) } d.Set("name", id.DatabaseAccountName) d.Set("resource_group_name", id.ResourceGroupName) + d.Set("location", location.NormalizeNilable(existing.Model.Location)) + d.Set("kind", pointer.From(existing.Model.Kind)) - if model := existing.Model; model != nil { - d.Set("location", location.NormalizeNilable(model.Location)) - d.Set("kind", pointer.From(model.Kind)) - - identity, err := identity.FlattenLegacySystemAndUserAssignedMap(model.Identity) - if err != nil { - return fmt.Errorf("flattening `identity`: %+v", err) - } - - if err := d.Set("identity", identity); err != nil { - return fmt.Errorf("setting `identity`: %+v", err) - } + identity, err := identity.FlattenLegacySystemAndUserAssignedMap(existing.Model.Identity) + if err != nil { + return fmt.Errorf("flattening `identity`: %+v", err) + } - if props := model.Properties; props != nil { - d.Set("offer_type", pointer.From(props.DatabaseAccountOfferType)) + if err := d.Set("identity", identity); err != nil { + return fmt.Errorf("setting `identity`: %+v", err) + } - if features.FourPointOhBeta() { - d.Set("ip_range_filter", common.CosmosDBIpRulesToIpRangeFilter(props.IPRules)) - } else { - d.Set("ip_range_filter", common.CosmosDBIpRulesToIpRangeFilterThreePointOh(props.IPRules)) - } + if props := existing.Model.Properties; props != nil { + d.Set("offer_type", pointer.From(props.DatabaseAccountOfferType)) - d.Set("endpoint", props.DocumentEndpoint) - d.Set("enable_free_tier", props.EnableFreeTier) - d.Set("analytical_storage_enabled", props.EnableAnalyticalStorage) - d.Set("public_network_access_enabled", pointer.From(props.PublicNetworkAccess) == cosmosdb.PublicNetworkAccessEnabled) - d.Set("default_identity_type", props.DefaultIdentity) - d.Set("create_mode", string(pointer.From(props.CreateMode))) + if features.FourPointOhBeta() { + d.Set("ip_range_filter", common.CosmosDBIpRulesToIpRangeFilter(props.IPRules)) + } else { + d.Set("ip_range_filter", common.CosmosDBIpRulesToIpRangeFilterThreePointOh(props.IPRules)) + } - if v := props.IsVirtualNetworkFilterEnabled; v != nil { - d.Set("is_virtual_network_filter_enabled", props.IsVirtualNetworkFilterEnabled) - } + d.Set("endpoint", props.DocumentEndpoint) + d.Set("enable_free_tier", props.EnableFreeTier) + d.Set("analytical_storage_enabled", props.EnableAnalyticalStorage) + d.Set("public_network_access_enabled", pointer.From(props.PublicNetworkAccess) == cosmosdb.PublicNetworkAccessEnabled) + d.Set("default_identity_type", props.DefaultIdentity) + d.Set("create_mode", props.CreateMode) - if v := props.EnableAutomaticFailover; v != nil { - d.Set("enable_automatic_failover", props.EnableAutomaticFailover) - } + if v := existing.Model.Properties.IsVirtualNetworkFilterEnabled; v != nil { + d.Set("is_virtual_network_filter_enabled", props.IsVirtualNetworkFilterEnabled) + } - if v := props.KeyVaultKeyUri; v != nil { - d.Set("key_vault_key_id", props.KeyVaultKeyUri) - } + if v := existing.Model.Properties.EnableAutomaticFailover; v != nil { + d.Set("enable_automatic_failover", props.EnableAutomaticFailover) + } - if v := props.EnableMultipleWriteLocations; v != nil { - d.Set("enable_multiple_write_locations", props.EnableMultipleWriteLocations) - } + if v := existing.Model.Properties.KeyVaultKeyUri; v != nil { + d.Set("key_vault_key_id", props.KeyVaultKeyUri) + } - if err := d.Set("analytical_storage", flattenCosmosDBAccountAnalyticalStorageConfiguration(props.AnalyticalStorageConfiguration)); err != nil { - return fmt.Errorf("setting `analytical_storage`: %+v", err) - } + if v := existing.Model.Properties.EnableMultipleWriteLocations; v != nil { + d.Set("enable_multiple_write_locations", props.EnableMultipleWriteLocations) + } - if err := d.Set("capacity", flattenCosmosDBAccountCapacity(props.Capacity)); err != nil { - return fmt.Errorf("setting `capacity`: %+v", err) - } + if err := d.Set("analytical_storage", flattenCosmosDBAccountAnalyticalStorageConfiguration(props.AnalyticalStorageConfiguration)); err != nil { + return fmt.Errorf("setting `analytical_storage`: %+v", err) + } - if err := d.Set("restore", flattenCosmosdbAccountRestoreParameters(props.RestoreParameters)); err != nil { - return fmt.Errorf("setting `restore`: %+v", err) - } + if err := d.Set("capacity", flattenCosmosDBAccountCapacity(props.Capacity)); err != nil { + return fmt.Errorf("setting `capacity`: %+v", err) + } - if err = d.Set("consistency_policy", flattenAzureRmCosmosDBAccountConsistencyPolicy(props.ConsistencyPolicy)); err != nil { - return fmt.Errorf("setting CosmosDB Account %q `consistency_policy` (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err) - } + if err := d.Set("restore", flattenCosmosdbAccountRestoreParameters(props.RestoreParameters)); err != nil { + return fmt.Errorf("setting `restore`: %+v", err) + } - if err = d.Set("geo_location", flattenAzureRmCosmosDBAccountGeoLocations(props)); err != nil { - return fmt.Errorf("setting `geo_location`: %+v", err) - } + if err = d.Set("consistency_policy", flattenAzureRmCosmosDBAccountConsistencyPolicy(props.ConsistencyPolicy)); err != nil { + return fmt.Errorf("setting CosmosDB Account %q `consistency_policy` (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err) + } - if err = d.Set("capabilities", flattenAzureRmCosmosDBAccountCapabilities(props.Capabilities)); err != nil { - return fmt.Errorf("setting `capabilities`: %+v", err) - } + if err = d.Set("geo_location", flattenAzureRmCosmosDBAccountGeoLocations(props)); err != nil { + return fmt.Errorf("setting `geo_location`: %+v", err) + } - if err = d.Set("virtual_network_rule", flattenAzureRmCosmosDBAccountVirtualNetworkRules(props.VirtualNetworkRules)); err != nil { - return fmt.Errorf("setting `virtual_network_rule`: %+v", err) - } + if err = d.Set("capabilities", flattenAzureRmCosmosDBAccountCapabilities(props.Capabilities)); err != nil { + return fmt.Errorf("setting `capabilities`: %+v", err) + } - d.Set("access_key_metadata_writes_enabled", !*props.DisableKeyBasedMetadataWriteAccess) - if apiProps := props.ApiProperties; apiProps != nil { - d.Set("mongo_server_version", string(pointer.From(apiProps.ServerVersion))) - } - d.Set("network_acl_bypass_for_azure_services", pointer.From(props.NetworkAclBypass) == cosmosdb.NetworkAclBypassAzureServices) - d.Set("network_acl_bypass_ids", utils.FlattenStringSlice(props.NetworkAclBypassResourceIds)) + if err = d.Set("virtual_network_rule", flattenAzureRmCosmosDBAccountVirtualNetworkRules(props.VirtualNetworkRules)); err != nil { + return fmt.Errorf("setting `virtual_network_rule`: %+v", err) + } - if v := props.DisableLocalAuth; v != nil { - d.Set("local_authentication_disabled", props.DisableLocalAuth) - } + d.Set("access_key_metadata_writes_enabled", !*props.DisableKeyBasedMetadataWriteAccess) + if apiProps := props.ApiProperties; apiProps != nil { + d.Set("mongo_server_version", apiProps.ServerVersion) + } + d.Set("network_acl_bypass_for_azure_services", pointer.From(props.NetworkAclBypass) == cosmosdb.NetworkAclBypassAzureServices) + d.Set("network_acl_bypass_ids", utils.FlattenStringSlice(props.NetworkAclBypassResourceIds)) - policy, err := flattenCosmosdbAccountBackup(props.BackupPolicy) - if err != nil { - return err - } + if v := existing.Model.Properties.DisableLocalAuth; v != nil { + d.Set("local_authentication_disabled", props.DisableLocalAuth) + } - if err = d.Set("backup", policy); err != nil { - return fmt.Errorf("setting `backup`: %+v", err) - } + policy, err := flattenCosmosdbAccountBackup(props.BackupPolicy) + if err != nil { + return err + } - d.Set("cors_rule", common.FlattenCosmosCorsRule(props.Cors)) + if err = d.Set("backup", policy); err != nil { + return fmt.Errorf("setting `backup`: %+v", err) + } - readEndpoints := make([]string, 0) - if p := props.ReadLocations; p != nil { - for _, l := range *p { - if l.DocumentEndpoint == nil { - continue - } + d.Set("cors_rule", common.FlattenCosmosCorsRule(props.Cors)) + } - readEndpoints = append(readEndpoints, *l.DocumentEndpoint) - } - } - if err := d.Set("read_endpoints", readEndpoints); err != nil { - return fmt.Errorf("setting `read_endpoints`: %s", err) + readEndpoints := make([]string, 0) + if p := existing.Model.Properties.ReadLocations; p != nil { + for _, l := range *p { + if l.DocumentEndpoint == nil { + continue } - writeEndpoints := make([]string, 0) - if p := props.WriteLocations; p != nil { - for _, l := range *p { - if l.DocumentEndpoint == nil { - continue - } + readEndpoints = append(readEndpoints, *l.DocumentEndpoint) + } + } + if err := d.Set("read_endpoints", readEndpoints); err != nil { + return fmt.Errorf("setting `read_endpoints`: %s", err) + } - writeEndpoints = append(writeEndpoints, *l.DocumentEndpoint) - } - } - if err := d.Set("write_endpoints", writeEndpoints); err != nil { - return fmt.Errorf("setting `write_endpoints`: %s", err) + writeEndpoints := make([]string, 0) + if p := existing.Model.Properties.WriteLocations; p != nil { + for _, l := range *p { + if l.DocumentEndpoint == nil { + continue } - } - if err := tags.FlattenAndSet(d, model.Tags); err != nil { - return err + writeEndpoints = append(writeEndpoints, *l.DocumentEndpoint) } } + if err := d.Set("write_endpoints", writeEndpoints); err != nil { + return fmt.Errorf("setting `write_endpoints`: %s", err) + } // ListKeys returns a data structure containing a DatabaseAccountListReadOnlyKeysResult pointer // implying that it also returns the read only keys, however this appears to not be the case @@ -1435,11 +1435,8 @@ func resourceCosmosDbAccountRead(d *pluginsdk.ResourceData, meta interface{}) er return fmt.Errorf("[ERROR] Unable to List Write keys for CosmosDB Account %s: %s", id.DatabaseAccountName, err) } - - if model := keys.Model; model != nil { - d.Set("primary_key", model.PrimaryMasterKey) - d.Set("secondary_key", model.SecondaryMasterKey) - } + d.Set("primary_key", keys.Model.PrimaryMasterKey) + d.Set("secondary_key", keys.Model.SecondaryMasterKey) readonlyKeys, err := client.DatabaseAccountsListReadOnlyKeys(ctx, *id) if err != nil { @@ -1451,16 +1448,13 @@ func resourceCosmosDbAccountRead(d *pluginsdk.ResourceData, meta interface{}) er return fmt.Errorf("[ERROR] Unable to List read-only keys for CosmosDB Account %s: %s", id.DatabaseAccountName, err) } - - if model := readonlyKeys.Model; model != nil { - d.Set("primary_readonly_key", model.PrimaryReadonlyMasterKey) - d.Set("secondary_readonly_key", model.SecondaryReadonlyMasterKey) - } + d.Set("primary_readonly_key", readonlyKeys.Model.PrimaryReadonlyMasterKey) + d.Set("secondary_readonly_key", readonlyKeys.Model.SecondaryReadonlyMasterKey) connStringResp, err := client.DatabaseAccountsListConnectionStrings(ctx, *id) if err != nil { if response.WasNotFound(keys.HttpResponse) { - log.Printf("[DEBUG] Connection Strings were not found for CosmosDB Account %q (Resource Group %q) - removing from state!", id.DatabaseAccountName, id.ResourceGroupName) + log.Printf("[DEBUG] Connection Strings were not found for CosmosDB Account %q (Resource Group %q) - removing from state!", id.ResourceGroupName, id.ResourceGroupName) d.SetId("") return nil } @@ -1468,22 +1462,20 @@ func resourceCosmosDbAccountRead(d *pluginsdk.ResourceData, meta interface{}) er return fmt.Errorf("[ERROR] Unable to List connection strings for CosmosDB Account %s: %s", id.DatabaseAccountName, err) } - if model := connStringResp.Model; model != nil { - var connStrings []string - if model.ConnectionStrings != nil { - connStrings = make([]string, len(*model.ConnectionStrings)) - for i, v := range *model.ConnectionStrings { - connStrings[i] = *v.ConnectionString - if propertyName, propertyExists := connStringPropertyMap[*v.Description]; propertyExists { - d.Set(propertyName, v.ConnectionString) // lintignore:R001 - } + var connStrings []string + if connStringResp.Model.ConnectionStrings != nil { + connStrings = make([]string, len(*connStringResp.Model.ConnectionStrings)) + for i, v := range *connStringResp.Model.ConnectionStrings { + connStrings[i] = *v.ConnectionString + if propertyName, propertyExists := connStringPropertyMap[*v.Description]; propertyExists { + d.Set(propertyName, v.ConnectionString) // lintignore:R001 } } - - d.Set("connection_strings", connStrings) } - return nil + d.Set("connection_strings", connStrings) + + return tags.FlattenAndSet(d, existing.Model.Tags) } func resourceCosmosDbAccountDelete(d *pluginsdk.ResourceData, meta interface{}) error { @@ -1497,7 +1489,7 @@ func resourceCosmosDbAccountDelete(d *pluginsdk.ResourceData, meta interface{}) } if err := client.DatabaseAccountsDeleteThenPoll(ctx, *id); err != nil { - return fmt.Errorf("deleting %q: %+v", id, err) + return fmt.Errorf("deleting CosmosDB Account %q (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err) } // the SDK now will return a `WasNotFound` response even when still deleting @@ -1527,9 +1519,8 @@ func resourceCosmosDbAccountDelete(d *pluginsdk.ResourceData, meta interface{}) } func resourceCosmosDbAccountApiUpdate(client *cosmosdb.CosmosDBClient, ctx context.Context, id cosmosdb.DatabaseAccountId, account cosmosdb.DatabaseAccountUpdateParameters, d *pluginsdk.ResourceData) error { - err := client.DatabaseAccountsUpdateThenPoll(ctx, id, account) - if err != nil { - return fmt.Errorf("updating %q: %+v", id, err) + if err := client.DatabaseAccountsUpdateThenPoll(ctx, id, account); err != nil { + return fmt.Errorf("updating CosmosDB Account %q (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err) } stateConf := &pluginsdk.StateChangeConf{ @@ -1550,7 +1541,7 @@ func resourceCosmosDbAccountApiUpdate(client *cosmosdb.CosmosDBClient, ctx conte stateConf.Timeout = d.Timeout(pluginsdk.TimeoutUpdate) - _, err = stateConf.WaitForStateContext(ctx) + _, err := stateConf.WaitForStateContext(ctx) if err != nil { return fmt.Errorf("waiting for the CosmosDB Account %q (Resource Group %q) to update: %+v", id.DatabaseAccountName, id.ResourceGroupName, err) } @@ -1560,7 +1551,7 @@ func resourceCosmosDbAccountApiUpdate(client *cosmosdb.CosmosDBClient, ctx conte func resourceCosmosDbAccountApiCreateOrUpdate(client *cosmosdb.CosmosDBClient, ctx context.Context, id cosmosdb.DatabaseAccountId, account cosmosdb.DatabaseAccountCreateUpdateParameters, d *pluginsdk.ResourceData) error { if err := client.DatabaseAccountsCreateOrUpdateThenPoll(ctx, id, account); err != nil { - return fmt.Errorf("creating/updating %q: %+v", id, err) + return fmt.Errorf("creating/updating CosmosDB Account %q (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err) } // if a replication location is added or removed it can take some time to provision @@ -1575,33 +1566,30 @@ func resourceCosmosDbAccountApiCreateOrUpdate(client *cosmosdb.CosmosDBClient, c return nil, "", fmt.Errorf("reading CosmosDB Account %q after create/update (Resource Group %q): %+v", id.DatabaseAccountName, id.ResourceGroupName, err2) } status := "Succeeded" + if props := resp.Model.Properties; props != nil { + var locations []cosmosdb.Location - if model := resp.Model; model != nil { - if props := model.Properties; props != nil { - var locations []cosmosdb.Location + if props.ReadLocations != nil { + locations = append(locations, *props.ReadLocations...) + } + if props.WriteLocations != nil { + locations = append(locations, *props.WriteLocations...) + } - if props.ReadLocations != nil { - locations = append(locations, *props.ReadLocations...) - } - if props.WriteLocations != nil { - locations = append(locations, *props.WriteLocations...) + for _, l := range locations { + if status = *l.ProvisioningState; status == "Creating" || status == "Updating" || status == "Deleting" { + break // return the first non successful status. } + } - for _, l := range locations { - if status = *l.ProvisioningState; status == "Creating" || status == "Updating" || status == "Deleting" { - break // return the first non successful status. + for _, desiredLocation := range account.Properties.Locations { + for index, l := range locations { + if azure.NormalizeLocation(*desiredLocation.LocationName) == azure.NormalizeLocation(*l.LocationName) { + break } - } - for _, desiredLocation := range *props.Locations { - for index, l := range locations { - if azure.NormalizeLocation(*desiredLocation.LocationName) == azure.NormalizeLocation(*l.LocationName) { - break - } - - if (index + 1) == len(locations) { - return resp, "Updating", nil - } + if (index + 1) == len(locations) { + return resp, "Updating", nil } } } @@ -1913,6 +1901,7 @@ func flattenCosmosdbAccountBackup(input cosmosdb.BackupPolicy) ([]interface{}, e "type": string(cosmosdb.BackupPolicyTypeContinuous), }, }, nil + case cosmosdb.PeriodicModeBackupPolicy: var interval, retention int if v := backupPolicy.PeriodicModeProperties.BackupIntervalInMinutes; v != nil { @@ -1933,6 +1922,7 @@ func flattenCosmosdbAccountBackup(input cosmosdb.BackupPolicy) ([]interface{}, e "storage_redundancy": storageRedundancy, }, }, nil + default: return nil, fmt.Errorf("unknown `type` in `backup`: %+v", input) } @@ -2025,7 +2015,6 @@ func expandCosmosdbAccountDatabasesToRestore(input []interface{}) *[]cosmosdb.Da CollectionNames: utils.ExpandStringSlice(v["collection_names"].(*pluginsdk.Set).List()), }) } - return &results } @@ -2033,7 +2022,6 @@ func flattenCosmosdbAccountRestoreParameters(input *cosmosdb.RestoreParameters) if input == nil { return make([]interface{}, 0) } - var restoreSource string if input.RestoreSource != nil { restoreSource = *input.RestoreSource @@ -2070,7 +2058,6 @@ func flattenCosmosdbAccountDatabasesToRestore(input *[]cosmosdb.DatabaseRestoreR "name": databaseName, }) } - return results } From 080c4e5de0123d97273b36e77042167a7c0ae1b8 Mon Sep 17 00:00:00 2001 From: neil-yechenwei Date: Fri, 19 Jan 2024 15:14:28 +0800 Subject: [PATCH 8/9] update code --- internal/services/cosmos/cosmosdb_account_resource.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/services/cosmos/cosmosdb_account_resource.go b/internal/services/cosmos/cosmosdb_account_resource.go index 9e0f248f0b47..7740e3d1e5a1 100644 --- a/internal/services/cosmos/cosmosdb_account_resource.go +++ b/internal/services/cosmos/cosmosdb_account_resource.go @@ -1326,7 +1326,7 @@ func resourceCosmosDbAccountRead(d *pluginsdk.ResourceData, meta interface{}) er d.Set("analytical_storage_enabled", props.EnableAnalyticalStorage) d.Set("public_network_access_enabled", pointer.From(props.PublicNetworkAccess) == cosmosdb.PublicNetworkAccessEnabled) d.Set("default_identity_type", props.DefaultIdentity) - d.Set("create_mode", props.CreateMode) + d.Set("create_mode", pointer.From(props.CreateMode)) if v := existing.Model.Properties.IsVirtualNetworkFilterEnabled; v != nil { d.Set("is_virtual_network_filter_enabled", props.IsVirtualNetworkFilterEnabled) @@ -1374,7 +1374,7 @@ func resourceCosmosDbAccountRead(d *pluginsdk.ResourceData, meta interface{}) er d.Set("access_key_metadata_writes_enabled", !*props.DisableKeyBasedMetadataWriteAccess) if apiProps := props.ApiProperties; apiProps != nil { - d.Set("mongo_server_version", apiProps.ServerVersion) + d.Set("mongo_server_version", pointer.From(apiProps.ServerVersion)) } d.Set("network_acl_bypass_for_azure_services", pointer.From(props.NetworkAclBypass) == cosmosdb.NetworkAclBypassAzureServices) d.Set("network_acl_bypass_ids", utils.FlattenStringSlice(props.NetworkAclBypassResourceIds)) From 3044990c453f1da49d15a7e1637fc095c36faaab Mon Sep 17 00:00:00 2001 From: neil-yechenwei Date: Fri, 19 Jan 2024 16:43:28 +0800 Subject: [PATCH 9/9] update code --- internal/services/cosmos/cosmosdb_account_resource_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/services/cosmos/cosmosdb_account_resource_test.go b/internal/services/cosmos/cosmosdb_account_resource_test.go index 26db73918bbd..fb4f08e5727f 100644 --- a/internal/services/cosmos/cosmosdb_account_resource_test.go +++ b/internal/services/cosmos/cosmosdb_account_resource_test.go @@ -4034,7 +4034,7 @@ resource "azurerm_cosmosdb_account" "test1" { } consistency_policy { - consistency_level = "Eventual" + consistency_level = "Session" } geo_location {