From cf06abe6d524ced7a319de2608b9443e29153278 Mon Sep 17 00:00:00 2001 From: chenhanzhang Date: Wed, 25 Dec 2024 16:38:10 +0800 Subject: [PATCH] New Resource: alicloud_mongodb_private_srv_network_address. --- alicloud/provider.go | 1 + ...oud_mongodb_private_srv_network_address.go | 158 ++++++++++++++++++ ...ongodb_private_srv_network_address_test.go | 100 +++++++++++ alicloud/service_alicloud_mongodb_v2.go | 92 ++++++++++ ..._private_srv_network_address.html.markdown | 92 ++++++++++ 5 files changed, 443 insertions(+) create mode 100644 alicloud/resource_alicloud_mongodb_private_srv_network_address.go create mode 100644 alicloud/resource_alicloud_mongodb_private_srv_network_address_test.go create mode 100644 alicloud/service_alicloud_mongodb_v2.go create mode 100644 website/docs/r/mongodb_private_srv_network_address.html.markdown diff --git a/alicloud/provider.go b/alicloud/provider.go index cb383a36fb86..d46b5e062057 100644 --- a/alicloud/provider.go +++ b/alicloud/provider.go @@ -879,6 +879,7 @@ func Provider() terraform.ResourceProvider { "alicloud_cms_site_monitors": dataSourceAliCloudCloudMonitorServiceSiteMonitors(), }, ResourcesMap: map[string]*schema.Resource{ + "alicloud_mongodb_private_srv_network_address": resourceAliCloudMongodbPrivateSrvNetworkAddress(), "alicloud_schedulerx_app_group": resourceAliCloudSchedulerxAppGroup(), "alicloud_schedulerx_job": resourceAliCloudSchedulerxJob(), "alicloud_express_connect_router_grant_association": resourceAliCloudExpressConnectRouterGrantAssociation(), diff --git a/alicloud/resource_alicloud_mongodb_private_srv_network_address.go b/alicloud/resource_alicloud_mongodb_private_srv_network_address.go new file mode 100644 index 000000000000..faf59921e77d --- /dev/null +++ b/alicloud/resource_alicloud_mongodb_private_srv_network_address.go @@ -0,0 +1,158 @@ +// Package alicloud. This file is generated automatically. Please do not modify it manually, thank you! +package alicloud + +import ( + "fmt" + "log" + "time" + + 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 resourceAliCloudMongodbPrivateSrvNetworkAddress() *schema.Resource { + return &schema.Resource{ + Create: resourceAliCloudMongodbPrivateSrvNetworkAddressCreate, + Read: resourceAliCloudMongodbPrivateSrvNetworkAddressRead, + Delete: resourceAliCloudMongodbPrivateSrvNetworkAddressDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(5 * time.Minute), + Delete: schema.DefaultTimeout(5 * time.Minute), + }, + Schema: map[string]*schema.Schema{ + "db_instance_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "private_srv_connection_string_uri": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceAliCloudMongodbPrivateSrvNetworkAddressCreate(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*connectivity.AliyunClient) + + action := "AllocateDBInstanceSrvNetworkAddress" + 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("db_instance_id"); ok { + request["DBInstanceId"] = v + } + request["RegionId"] = client.RegionId + + request["SrvConnectionType"] = "vpc" + request["NodeId"] = "ConnectionStringURI" + 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 IsExpectedErrors(err, []string{"InvalidStatus.NotFound"}) || 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_private_srv_network_address", action, AlibabaCloudSdkGoERROR) + } + + d.SetId(fmt.Sprint(request["DBInstanceId"])) + + mongodbServiceV2 := MongodbServiceV2{client} + stateConf := BuildStateConf([]string{}, []string{"#CHECKSET"}, d.Timeout(schema.TimeoutCreate), 30*time.Second, mongodbServiceV2.MongodbPrivateSrvNetworkAddressStateRefreshFunc(d.Id(), "#PrivateSrvConnectionStringUri", []string{})) + if _, err := stateConf.WaitForState(); err != nil { + return WrapErrorf(err, IdMsg, d.Id()) + } + + return resourceAliCloudMongodbPrivateSrvNetworkAddressRead(d, meta) +} + +func resourceAliCloudMongodbPrivateSrvNetworkAddressRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + mongodbServiceV2 := MongodbServiceV2{client} + + objectRaw, err := mongodbServiceV2.DescribeMongodbPrivateSrvNetworkAddress(d.Id()) + if err != nil { + if !d.IsNewResource() && NotFoundError(err) { + log.Printf("[DEBUG] Resource alicloud_mongodb_private_srv_network_address DescribeMongodbPrivateSrvNetworkAddress Failed!!! %s", err) + d.SetId("") + return nil + } + return WrapError(err) + } + + if objectRaw["PrivateSrvConnectionStringUri"] != nil { + d.Set("private_srv_connection_string_uri", objectRaw["PrivateSrvConnectionStringUri"]) + } + + d.Set("db_instance_id", d.Id()) + + return nil +} + +func resourceAliCloudMongodbPrivateSrvNetworkAddressDelete(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*connectivity.AliyunClient) + action := "ReleaseNodePrivateNetworkAddress" + 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{}) + request["DBInstanceId"] = d.Id() + request["RegionId"] = client.RegionId + + request["NodeId"] = "ConnectionStringURI" + request["ConnectionType"] = "SRV" + request["NetworkType"] = "VPC" + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutDelete), 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 IsExpectedErrors(err, []string{"OperationDenied.DBInstanceStatus"}) || NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + + if err != nil { + if NotFoundError(err) { + return nil + } + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + + return nil +} diff --git a/alicloud/resource_alicloud_mongodb_private_srv_network_address_test.go b/alicloud/resource_alicloud_mongodb_private_srv_network_address_test.go new file mode 100644 index 000000000000..54ada2111ee1 --- /dev/null +++ b/alicloud/resource_alicloud_mongodb_private_srv_network_address_test.go @@ -0,0 +1,100 @@ +package alicloud + +import ( + "fmt" + "testing" + + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +// Test Mongodb PrivateSrvNetworkAddress. >>> Resource test cases, automatically generated. +// Case 私有网络srv测试 9657 +func TestAccAliCloudMongodbPrivateSrvNetworkAddress_basic9657(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_mongodb_private_srv_network_address.default" + ra := resourceAttrInit(resourceId, AlicloudMongodbPrivateSrvNetworkAddressMap9657) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &MongodbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeMongodbPrivateSrvNetworkAddress") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%smongodbprivatesrvnetworkaddress%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudMongodbPrivateSrvNetworkAddressBasicDependence9657) + 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{}{ + "db_instance_id": "${alicloud_mongodb_instance.defaultHrZmxC.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "db_instance_id": CHECKSET, + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +var AlicloudMongodbPrivateSrvNetworkAddressMap9657 = map[string]string{ + "private_srv_connection_string_uri": CHECKSET, +} + +func AlicloudMongodbPrivateSrvNetworkAddressBasicDependence9657(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +variable "zone_id" { + default = "cn-shanghai-b" +} + +variable "region_id" { + default = "cn-shanghai" +} + +resource "alicloud_vpc" "defaultie35CW" { + cidr_block = "10.0.0.0/8" + vpc_name = var.name +} + +resource "alicloud_vswitch" "defaultg0DCAR" { + vpc_id = alicloud_vpc.defaultie35CW.id + zone_id = var.zone_id + cidr_block = "10.0.0.0/24" +} + +resource "alicloud_mongodb_instance" "defaultHrZmxC" { + engine_version = "4.4" + storage_type = "cloud_essd1" + vswitch_id = alicloud_vswitch.defaultg0DCAR.id + db_instance_storage = "20" + vpc_id = alicloud_vpc.defaultie35CW.id + db_instance_class = "mdb.shard.4x.large.d" + storage_engine = "WiredTiger" + network_type = "VPC" + zone_id = var.zone_id +} + + +`, name) +} + +// Test Mongodb PrivateSrvNetworkAddress. <<< Resource test cases, automatically generated. diff --git a/alicloud/service_alicloud_mongodb_v2.go b/alicloud/service_alicloud_mongodb_v2.go new file mode 100644 index 000000000000..1332d84ae9e1 --- /dev/null +++ b/alicloud/service_alicloud_mongodb_v2.go @@ -0,0 +1,92 @@ +package alicloud + +import ( + "fmt" + "strings" + "time" + + "github.com/PaesslerAG/jsonpath" + util "github.com/alibabacloud-go/tea-utils/service" + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +type MongodbServiceV2 struct { + client *connectivity.AliyunClient +} + +// DescribeMongodbPrivateSrvNetworkAddress <<< Encapsulated get interface for Mongodb PrivateSrvNetworkAddress. + +func (s *MongodbServiceV2) DescribeMongodbPrivateSrvNetworkAddress(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{} + action := "DescribeAllNetworkAddress" + conn, err := client.NewDdsClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["DBInstanceId"] = id + 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) + } + + currentStatus := response["PrivateSrvConnectionStringUri"] + if currentStatus == nil { + return object, WrapErrorf(Error(GetNotFoundMessage("PrivateSrvNetworkAddress", id)), NotFoundMsg, response) + } + + return response, nil +} + +func (s *MongodbServiceV2) MongodbPrivateSrvNetworkAddressStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeMongodbPrivateSrvNetworkAddress(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 + } +} + +// DescribeMongodbPrivateSrvNetworkAddress >>> Encapsulated. diff --git a/website/docs/r/mongodb_private_srv_network_address.html.markdown b/website/docs/r/mongodb_private_srv_network_address.html.markdown new file mode 100644 index 000000000000..99fdcf7aeaf5 --- /dev/null +++ b/website/docs/r/mongodb_private_srv_network_address.html.markdown @@ -0,0 +1,92 @@ +--- +subcategory: "MongoDB" +layout: "alicloud" +page_title: "Alicloud: alicloud_mongodb_private_srv_network_address" +description: |- + Provides a Alicloud Mongo D B Private Srv Network Address resource. +--- + +# alicloud_mongodb_private_srv_network_address + +Provides a Mongo D B Private Srv Network Address resource. + +Private network SRV highly available link address. + +For information about Mongo D B Private Srv Network Address and how to use it, see [What is Private Srv Network Address](https://www.alibabacloud.com/help/en/). + +-> **NOTE:** Available since v1.240.0. + +## Example Usage + +Basic Usage + +```terraform +variable "name" { + default = "terraform-example" +} + +provider "alicloud" { + region = "cn-shanghai" +} + +variable "zone_id" { + default = "cn-shanghai-b" +} + +variable "region_id" { + default = "cn-shanghai" +} + +resource "alicloud_vpc" "defaultie35CW" { + cidr_block = "10.0.0.0/8" + vpc_name = var.name +} + +resource "alicloud_vswitch" "defaultg0DCAR" { + vpc_id = alicloud_vpc.defaultie35CW.id + zone_id = var.zone_id + cidr_block = "10.0.0.0/24" +} + +resource "alicloud_mongodb_instance" "defaultHrZmxC" { + engine_version = "4.4" + storage_type = "cloud_essd1" + vswitch_id = alicloud_vswitch.defaultg0DCAR.id + db_instance_storage = "20" + vpc_id = alicloud_vpc.defaultie35CW.id + db_instance_class = "mdb.shard.4x.large.d" + storage_engine = "WiredTiger" + network_type = "VPC" + zone_id = var.zone_id +} + + +resource "alicloud_mongodb_private_srv_network_address" "default" { + db_instance_id = alicloud_mongodb_instance.defaultHrZmxC.id +} +``` + +## Argument Reference + +The following arguments are supported: +* `db_instance_id` - (Required, ForceNew) The instance ID. + +## Attributes Reference + +The following attributes are exported: +* `id` - The ID of the resource supplied above. +* `private_srv_connection_string_uri` - Private network SRV highly available connection address + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration-0-11/resources.html#timeouts) for certain actions: +* `create` - (Defaults to 5 mins) Used when create the Private Srv Network Address. +* `delete` - (Defaults to 5 mins) Used when delete the Private Srv Network Address. + +## Import + +Mongo D B Private Srv Network Address can be imported using the id, e.g. + +```shell +$ terraform import alicloud_mongodb_private_srv_network_address.example +``` \ No newline at end of file