diff --git a/alicloud/provider.go b/alicloud/provider.go index bf24904b9d52..429257d0dc4d 100644 --- a/alicloud/provider.go +++ b/alicloud/provider.go @@ -1608,7 +1608,7 @@ func Provider() terraform.ResourceProvider { "alicloud_click_house_backup_policy": resourceAlicloudClickHouseBackupPolicy(), "alicloud_mongodb_audit_policy": resourceAlicloudMongodbAuditPolicy(), "alicloud_cloud_sso_access_configuration_provisioning": resourceAlicloudCloudSsoAccessConfigurationProvisioning(), - "alicloud_mongodb_account": resourceAlicloudMongodbAccount(), + "alicloud_mongodb_account": resourceAliCloudMongodbAccount(), "alicloud_mongodb_serverless_instance": resourceAlicloudMongodbServerlessInstance(), "alicloud_ecs_session_manager_status": resourceAliCloudEcsSessionManagerStatus(), "alicloud_cddc_dedicated_host_account": resourceAlicloudCddcDedicatedHostAccount(), diff --git a/alicloud/resource_alicloud_mongodb_account.go b/alicloud/resource_alicloud_mongodb_account.go index 07e1d7a5d169..9983eef8138d 100644 --- a/alicloud/resource_alicloud_mongodb_account.go +++ b/alicloud/resource_alicloud_mongodb_account.go @@ -1,48 +1,52 @@ +// Package alicloud. This file is generated automatically. Please do not modify it manually, thank you! package alicloud import ( "fmt" "log" - "regexp" + "strings" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - util "github.com/alibabacloud-go/tea-utils/service" "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) -func resourceAlicloudMongodbAccount() *schema.Resource { +func resourceAliCloudMongodbAccount() *schema.Resource { return &schema.Resource{ - Create: resourceAlicloudMongodbAccountCreate, - Read: resourceAlicloudMongodbAccountRead, - Update: resourceAlicloudMongodbAccountUpdate, - Delete: resourceAlicloudMongodbAccountDelete, + Create: resourceAliCloudMongodbAccountCreate, + Read: resourceAliCloudMongodbAccountRead, + Update: resourceAliCloudMongodbAccountUpdate, + Delete: resourceAliCloudMongodbAccountDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(10 * time.Minute), - Update: schema.DefaultTimeout(10 * time.Minute), + Create: schema.DefaultTimeout(5 * time.Minute), + Update: schema.DefaultTimeout(5 * time.Minute), + Delete: schema.DefaultTimeout(5 * time.Minute), }, Schema: map[string]*schema.Schema{ "account_description": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.All(validation.StringDoesNotMatch(regexp.MustCompile(`(^http://.*)|(^https://.*)`), "It cannot begin with \"http://\", \"https://\"."), validation.StringMatch(regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_-]{1,255}$`), "It must be `2` to `256` characters in length, The description must start with a letter, and can contain letters, digits, underscores (_), and hyphens (-).")), + Type: schema.TypeString, + Optional: true, }, "account_name": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{"root"}, false), + Type: schema.TypeString, + Required: true, + ForceNew: true, }, "account_password": { - Type: schema.TypeString, - Required: true, - Sensitive: true, - ValidateFunc: validation.StringMatch(regexp.MustCompile(`[a-zA-Z!#$%^&*()_+-=]{8,32}`), "account_password must consist of uppercase letters, lowercase letters, numbers, and special characters"), + Type: schema.TypeString, + Required: true, + Sensitive: true, + }, + "character_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, }, "instance_id": { Type: schema.TypeString, @@ -57,87 +61,187 @@ func resourceAlicloudMongodbAccount() *schema.Resource { } } -func resourceAlicloudMongodbAccountCreate(d *schema.ResourceData, meta interface{}) error { +func resourceAliCloudMongodbAccountCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) - var response map[string]interface{} - action := "ResetAccountPassword" - request := make(map[string]interface{}) - conn, err := client.NewDdsClient() - if err != nil { - return WrapError(err) - } - request["AccountName"] = d.Get("account_name") - request["AccountPassword"] = d.Get("account_password") - request["DBInstanceId"] = d.Get("instance_id") - wait := incrementalWait(3*time.Second, 3*time.Second) - err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { - response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{}) + if v, ok := d.GetOk("character_type"); ok && InArray(fmt.Sprint(v), []string{"db"}) { + action := "CreateAccount" + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) + conn, err := client.NewDdsClient() if err != nil { - if NeedRetry(err) { - wait() - return resource.RetryableError(err) + return WrapError(err) + } + request = make(map[string]interface{}) + if v, ok := d.GetOk("account_name"); ok { + request["AccountName"] = v + } + if v, ok := d.GetOk("instance_id"); ok { + request["DBInstanceId"] = v + } + request["RegionId"] = client.RegionId + + request["AccountPassword"] = d.Get("account_password") + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), query, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) } - return resource.NonRetryableError(err) + return nil + }) + addDebug(action, response, request) + + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, "alicloud_mongodb_account", action, AlibabaCloudSdkGoERROR) } - return nil - }) - addDebug(action, response, request) - if err != nil { - return WrapErrorf(err, DefaultErrorMsg, "alicloud_mongodb_account", action, AlibabaCloudSdkGoERROR) + + d.SetId(fmt.Sprintf("%v:%v", request["DBInstanceId"], request["AccountName"])) + + mongodbServiceV2 := MongodbServiceV2{client} + stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 4*time.Minute, mongodbServiceV2.MongodbAccountStateRefreshFunc(d.Id(), "AccountStatus", []string{})) + if _, err := stateConf.WaitForState(); err != nil { + return WrapErrorf(err, IdMsg, d.Id()) + } + } - d.SetId(fmt.Sprint(request["DBInstanceId"], ":", request["AccountName"])) - MongoDBService := MongoDBService{client} - stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, MongoDBService.MongodbAccountStateRefreshFunc(d.Id(), []string{})) - if _, err := stateConf.WaitForState(); err != nil { - return WrapErrorf(err, IdMsg, d.Id()) + + invalidCreate := false + if v, ok := d.GetOk("character_type"); ok { + if InArray(fmt.Sprint(v), []string{"db"}) { + invalidCreate = true + } } + if !invalidCreate { - return resourceAlicloudMongodbAccountUpdate(d, meta) + action := "ResetAccountPassword" + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) + conn, err := client.NewDdsClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + if v, ok := d.GetOk("account_name"); ok { + request["AccountName"] = v + } + if v, ok := d.GetOk("instance_id"); ok { + request["DBInstanceId"] = v + } + request["RegionId"] = client.RegionId + + request["AccountPassword"] = d.Get("account_password") + if v, ok := d.GetOk("character_type"); ok { + request["CharacterType"] = v + } + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), query, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, "alicloud_mongodb_account", action, AlibabaCloudSdkGoERROR) + } + + d.SetId(fmt.Sprintf("%v:%v", request["DBInstanceId"], request["AccountName"])) + + mongodbServiceV2 := MongodbServiceV2{client} + stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 4*time.Minute, mongodbServiceV2.MongodbAccountStateRefreshFunc(d.Id(), "AccountStatus", []string{})) + if _, err := stateConf.WaitForState(); err != nil { + return WrapErrorf(err, IdMsg, d.Id()) + } + + } + + return resourceAliCloudMongodbAccountUpdate(d, meta) } -func resourceAlicloudMongodbAccountRead(d *schema.ResourceData, meta interface{}) error { + +func resourceAliCloudMongodbAccountRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) - MongoDBService := MongoDBService{client} - object, err := MongoDBService.DescribeMongodbAccount(d.Id()) + mongodbServiceV2 := MongodbServiceV2{client} + + objectRaw, err := mongodbServiceV2.DescribeMongodbAccount(d.Id()) if err != nil { - if NotFoundError(err) { - log.Printf("[DEBUG] Resource alicloud_mongodb_account MongoDBService.DescribeMongodbAccount Failed!!! %s", err) + if !d.IsNewResource() && NotFoundError(err) { + log.Printf("[DEBUG] Resource alicloud_mongodb_account DescribeMongodbAccount Failed!!! %s", err) d.SetId("") return nil } return WrapError(err) } - d.Set("account_name", object["AccountName"]) - d.Set("instance_id", object["DBInstanceId"]) - d.Set("account_description", object["AccountDescription"]) - d.Set("status", object["AccountStatus"]) + + if objectRaw["AccountDescription"] != nil { + d.Set("account_description", objectRaw["AccountDescription"]) + } + if objectRaw["CharacterType"] != nil { + d.Set("character_type", objectRaw["CharacterType"]) + } + if objectRaw["AccountStatus"] != nil { + d.Set("status", objectRaw["AccountStatus"]) + } + if objectRaw["AccountName"] != nil { + d.Set("account_name", objectRaw["AccountName"]) + } + if objectRaw["DBInstanceId"] != nil { + d.Set("instance_id", objectRaw["DBInstanceId"]) + } + return nil } -func resourceAlicloudMongodbAccountUpdate(d *schema.ResourceData, meta interface{}) error { + +func resourceAliCloudMongodbAccountUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) - MongoDBService := MongoDBService{client} + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + update := false + d.Partial(true) + + parts := strings.Split(d.Id(), ":") + action := "ResetAccountPassword" conn, err := client.NewDdsClient() if err != nil { return WrapError(err) } - var response map[string]interface{} - parts, err := ParseResourceId(d.Id(), 2) - if err != nil { - return WrapError(err) + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["AccountName"] = parts[1] + request["DBInstanceId"] = parts[0] + request["RegionId"] = client.RegionId + if !d.IsNewResource() && d.HasChange("account_password") { + update = true + } + request["AccountPassword"] = d.Get("account_password") + if !d.IsNewResource() && d.HasChange("character_type") { + update = true + request["CharacterType"] = d.Get("character_type") } - d.Partial(true) - if d.HasChange("account_description") { - request := map[string]interface{}{ - "AccountName": parts[1], - "DBInstanceId": parts[0], - } - if v, ok := d.GetOk("account_description"); ok { - request["AccountDescription"] = v - } - action := "ModifyAccountDescription" - wait := incrementalWait(3*time.Second, 3*time.Second) + if update { + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { - response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{}) + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), query, request, &runtime) if err != nil { if NeedRetry(err) { wait() @@ -151,23 +255,34 @@ func resourceAlicloudMongodbAccountUpdate(d *schema.ResourceData, meta interface if err != nil { return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) } - stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, MongoDBService.MongodbAccountStateRefreshFunc(d.Id(), []string{})) + mongodbServiceV2 := MongodbServiceV2{client} + stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, mongodbServiceV2.MongodbAccountStateRefreshFunc(d.Id(), "AccountStatus", []string{})) if _, err := stateConf.WaitForState(); err != nil { return WrapErrorf(err, IdMsg, d.Id()) } - d.SetPartial("account_description") } - - if !d.IsNewResource() && d.HasChange("account_password") { - request := map[string]interface{}{ - "AccountName": parts[1], - "DBInstanceId": parts[0], - } - request["AccountPassword"] = d.Get("account_password") - action := "ResetAccountPassword" - wait := incrementalWait(3*time.Second, 3*time.Second) + update = false + parts = strings.Split(d.Id(), ":") + action = "ModifyAccountDescription" + conn, err = client.NewDdsClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["AccountName"] = parts[1] + request["DBInstanceId"] = parts[0] + request["RegionId"] = client.RegionId + if d.HasChange("account_description") { + update = true + } + request["AccountDescription"] = d.Get("account_description") + if update { + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { - response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), nil, request, &util.RuntimeOptions{}) + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), query, request, &runtime) if err != nil { if NeedRetry(err) { wait() @@ -181,17 +296,13 @@ func resourceAlicloudMongodbAccountUpdate(d *schema.ResourceData, meta interface if err != nil { return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) } - stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, MongoDBService.MongodbAccountStateRefreshFunc(d.Id(), []string{})) - if _, err := stateConf.WaitForState(); err != nil { - return WrapErrorf(err, IdMsg, d.Id()) - } - d.SetPartial("account_password") } d.Partial(false) - return resourceAlicloudMongodbAccountRead(d, meta) + return resourceAliCloudMongodbAccountRead(d, meta) } -func resourceAlicloudMongodbAccountDelete(d *schema.ResourceData, meta interface{}) error { - log.Printf("[WARN] Cannot destroy resource Alicloud Mongodb Account. Terraform will remove this resource from the state file, however resources may remain.") + +func resourceAliCloudMongodbAccountDelete(d *schema.ResourceData, meta interface{}) error { + log.Printf("[WARN] Cannot destroy resource AliCloud Resource Account. Terraform will remove this resource from the state file, however resources may remain.") return nil } diff --git a/alicloud/resource_alicloud_mongodb_account_test.go b/alicloud/resource_alicloud_mongodb_account_test.go index fc59fbe498e8..3bae3cb45e24 100644 --- a/alicloud/resource_alicloud_mongodb_account_test.go +++ b/alicloud/resource_alicloud_mongodb_account_test.go @@ -19,7 +19,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) -func TestAccAlicloudMongoDBAccount_basic0(t *testing.T) { +func TestAccAliCloudMongoDBAccount_basic0(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_mongodb_account.default" checkoutSupportedRegions(t, true, connectivity.MongoDBSupportRegions) @@ -202,7 +202,7 @@ func TestUnitAlicloudMongoDBAccount(t *testing.T) { StatusCode: tea.Int(400), } }) - err = resourceAlicloudMongodbAccountCreate(dInit, rawClient) + err = resourceAliCloudMongodbAccountCreate(dInit, rawClient) patches.Reset() assert.NotNil(t, err) ReadMockResponseDiff := map[string]interface{}{ @@ -237,7 +237,7 @@ func TestUnitAlicloudMongoDBAccount(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudMongodbAccountCreate(dInit, rawClient) + err := resourceAliCloudMongodbAccountCreate(dInit, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -264,7 +264,7 @@ func TestUnitAlicloudMongoDBAccount(t *testing.T) { StatusCode: tea.Int(400), } }) - err = resourceAlicloudMongodbAccountUpdate(dExisted, rawClient) + err = resourceAliCloudMongodbAccountUpdate(dExisted, rawClient) patches.Reset() assert.NotNil(t, err) // ModifyAccountDescription @@ -304,7 +304,7 @@ func TestUnitAlicloudMongoDBAccount(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudMongodbAccountUpdate(dExisted, rawClient) + err := resourceAliCloudMongodbAccountUpdate(dExisted, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -352,7 +352,7 @@ func TestUnitAlicloudMongoDBAccount(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudMongodbAccountUpdate(dExisted, rawClient) + err := resourceAliCloudMongodbAccountUpdate(dExisted, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -391,7 +391,7 @@ func TestUnitAlicloudMongoDBAccount(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudMongodbAccountRead(dExisted, rawClient) + err := resourceAliCloudMongodbAccountRead(dExisted, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -402,7 +402,223 @@ func TestUnitAlicloudMongoDBAccount(t *testing.T) { } // Delete - err = resourceAlicloudMongodbAccountDelete(dExisted, rawClient) + err = resourceAliCloudMongodbAccountDelete(dExisted, rawClient) assert.Nil(t, err) } + +// Test Mongodb Account. >>> Resource test cases, automatically generated. +// Case 账号测试用例初始化_分片集群_create账号覆盖度 9243 +func TestAccAliCloudMongodbAccount_basic9243(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_mongodb_account.default" + ra := resourceAttrInit(resourceId, AlicloudMongodbAccountMap9243) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &MongodbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeMongodbAccount") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf_testacc%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudMongodbAccountBasicDependence9243) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-shanghai"}) + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "account_name": name, + "account_password": "qwer1234!!!", + "instance_id": "${alicloud_mongodb_sharding_instance.default7eOftZ.id}", + "character_type": "db", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "account_name": name, + "account_password": "qwer1234!!!", + "instance_id": CHECKSET, + "character_type": "db", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"account_password"}, + }, + }, + }) +} + +var AlicloudMongodbAccountMap9243 = map[string]string{ + "status": CHECKSET, +} + +func AlicloudMongodbAccountBasicDependence9243(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +variable "zone_id" { + default = "cn-shanghai-b" +} + +variable "region_id" { + default = "cn-shanghai" +} + +variable "other_zone_id" { + default = "cn-shanghai-g" +} + +resource "alicloud_vpc" "defaultIzCngN" { + cidr_block = "10.0.0.0/8" + vpc_name = var.name +} + +resource "alicloud_vswitch" "defaultLWEsPM" { + vpc_id = alicloud_vpc.defaultIzCngN.id + zone_id = var.zone_id + cidr_block = "10.0.0.0/24" +} + +resource "alicloud_mongodb_sharding_instance" "default7eOftZ" { + engine_version = "4.4" + storage_type = "cloud_essd1" + vswitch_id = alicloud_vswitch.defaultLWEsPM.id + vpc_id = alicloud_vpc.defaultIzCngN.id + storage_engine = "WiredTiger" + network_type = "VPC" + zone_id = var.zone_id + name = var.name + mongo_list { + node_class = "mdb.shard.4x.large.d" + } + mongo_list { + node_class = "mdb.shard.4x.large.d" + } + shard_list { + node_class = "mdb.shard.4x.large.d" + node_storage = "20" + } + shard_list { + node_class = "mdb.shard.4x.large.d" + node_storage = "20" + } + config_server_list { + node_class = "mdb.shard.2x.xlarge.d" + node_storage = "80" + } +} + + +`, name) +} + +// Case 账号测试用例初始化_副本集_2024年11月7日_写入 8763 +func TestAccAliCloudMongodbAccount_basic8763(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_mongodb_account.default" + ra := resourceAttrInit(resourceId, AlicloudMongodbAccountMap8763) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &MongodbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeMongodbAccount") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf_testacc%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudMongodbAccountBasicDependence8763) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-shanghai"}) + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "account_name": "root", + "account_password": "qwer1234!!!", + "instance_id": "${alicloud_mongodb_instance.default7eOftZ.id}", + "character_type": "normal", + "account_description": "bgg-test-power", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "account_name": "root", + "account_password": "qwer1234!!!", + "instance_id": CHECKSET, + "character_type": "normal", + "account_description": "bgg-test-power", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"account_password"}, + }, + }, + }) +} + +var AlicloudMongodbAccountMap8763 = map[string]string{ + "status": CHECKSET, +} + +func AlicloudMongodbAccountBasicDependence8763(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +variable "zone_id" { + default = "cn-shanghai-b" +} + +variable "region_id" { + default = "cn-shanghai" +} + +variable "other_zone_id" { + default = "cn-shanghai-g" +} + +resource "alicloud_vpc" "defaultIzCngN" { + cidr_block = "10.0.0.0/8" + vpc_name = var.name +} + +resource "alicloud_vswitch" "defaultLWEsPM" { + vpc_id = alicloud_vpc.defaultIzCngN.id + zone_id = var.zone_id + cidr_block = "10.0.0.0/24" +} + +resource "alicloud_mongodb_instance" "default7eOftZ" { + engine_version = "4.4" + storage_type = "cloud_essd1" + vswitch_id = alicloud_vswitch.defaultLWEsPM.id + vpc_id = alicloud_vpc.defaultIzCngN.id + storage_engine = "WiredTiger" + network_type = "VPC" + zone_id = var.zone_id + db_instance_storage = "20" + db_instance_class = "mdb.shard.4x.large.d" +} + + +`, name) +} + +// Test Mongodb Account. <<< Resource test cases, automatically generated. diff --git a/alicloud/service_alicloud_mongodb_v2.go b/alicloud/service_alicloud_mongodb_v2.go index 1332d84ae9e1..2e6327e9bff5 100644 --- a/alicloud/service_alicloud_mongodb_v2.go +++ b/alicloud/service_alicloud_mongodb_v2.go @@ -90,3 +90,88 @@ func (s *MongodbServiceV2) MongodbPrivateSrvNetworkAddressStateRefreshFunc(id st } // DescribeMongodbPrivateSrvNetworkAddress >>> Encapsulated. + +// DescribeMongodbAccount <<< Encapsulated get interface for Mongodb Account. + +func (s *MongodbServiceV2) DescribeMongodbAccount(id string) (object map[string]interface{}, err error) { + client := s.client + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + parts := strings.Split(id, ":") + if len(parts) != 2 { + err = WrapError(fmt.Errorf("invalid Resource Id %s. Expected parts' length %d, got %d", id, 2, len(parts))) + } + action := "DescribeAccounts" + conn, err := client.NewDdsClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["AccountName"] = parts[1] + request["DBInstanceId"] = parts[0] + request["RegionId"] = client.RegionId + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2015-12-01"), StringPointer("AK"), query, request, &runtime) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + v, err := jsonpath.Get("$.Accounts.Account[*]", response) + if err != nil { + return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Accounts.Account[*]", response) + } + + if len(v.([]interface{})) == 0 { + return object, WrapErrorf(Error(GetNotFoundMessage("Account", id)), NotFoundMsg, response) + } + + return v.([]interface{})[0].(map[string]interface{}), nil +} + +func (s *MongodbServiceV2) MongodbAccountStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeMongodbAccount(id) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + if strings.HasPrefix(field, "#") { + v, _ := jsonpath.Get(strings.TrimPrefix(field, "#"), object) + if v != nil { + currentStatus = "#CHECKSET" + } + } + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +// DescribeMongodbAccount >>> Encapsulated. diff --git a/website/docs/r/mongodb_account.html.markdown b/website/docs/r/mongodb_account.html.markdown index 2c2eb8ebe320..123904ad4df7 100644 --- a/website/docs/r/mongodb_account.html.markdown +++ b/website/docs/r/mongodb_account.html.markdown @@ -2,16 +2,17 @@ subcategory: "MongoDB" layout: "alicloud" page_title: "Alicloud: alicloud_mongodb_account" -sidebar_current: "docs-alicloud-resource-mongodb-account" description: |- - Provides a Alicloud MongoDB Account resource. + Provides a Alicloud Mongo D B Account resource. --- # alicloud_mongodb_account -Provides a MongoDB Account resource. +Provides a Mongo D B Account resource. -For information about MongoDB Account and how to use it, see [What is Account](https://www.alibabacloud.com/help/en/doc-detail/62154.html). + + +For information about Mongo D B Account and how to use it, see [What is Account](https://www.alibabacloud.com/help/en/doc-detail/62154.html). -> **NOTE:** Available since v1.148.0. @@ -19,12 +20,6 @@ For information about MongoDB Account and how to use it, see [What is Account](h Basic Usage -