From 79ceaa1bf208f38ca8c799d3c6b26b9cd48fa092 Mon Sep 17 00:00:00 2001 From: chenhanzhang Date: Wed, 15 Jan 2025 15:03:34 +0800 Subject: [PATCH] New Resource: alicloud_alb_load_balancer_zone_shifted_attachment. --- alicloud/provider.go | 1 + ...b_load_balancer_zone_shifted_attachment.go | 190 ++++++++++++++++++ ...d_balancer_zone_shifted_attachment_test.go | 121 +++++++++++ alicloud/service_alicloud_alb_v2.go | 94 +++++++++ ...ncer_zone_shifted_attachment.html.markdown | 113 +++++++++++ 5 files changed, 519 insertions(+) create mode 100644 alicloud/resource_alicloud_alb_load_balancer_zone_shifted_attachment.go create mode 100644 alicloud/resource_alicloud_alb_load_balancer_zone_shifted_attachment_test.go create mode 100644 website/docs/r/alb_load_balancer_zone_shifted_attachment.html.markdown diff --git a/alicloud/provider.go b/alicloud/provider.go index 4db295096d12..2e15250b5753 100644 --- a/alicloud/provider.go +++ b/alicloud/provider.go @@ -887,6 +887,7 @@ func Provider() terraform.ResourceProvider { "alicloud_vpc_ipam_ipams": dataSourceAliCloudVpcIpamIpams(), }, ResourcesMap: map[string]*schema.Resource{ + "alicloud_alb_load_balancer_zone_shifted_attachment": resourceAliCloudAlbLoadBalancerZoneShiftedAttachment(), "alicloud_alb_load_balancer_access_log_config_attachment": resourceAliCloudAlbLoadBalancerAccessLogConfigAttachment(), "alicloud_data_works_di_alarm_rule": resourceAliCloudDataWorksDiAlarmRule(), "alicloud_data_works_di_job": resourceAliCloudDataWorksDiJob(), diff --git a/alicloud/resource_alicloud_alb_load_balancer_zone_shifted_attachment.go b/alicloud/resource_alicloud_alb_load_balancer_zone_shifted_attachment.go new file mode 100644 index 000000000000..25336c4e5138 --- /dev/null +++ b/alicloud/resource_alicloud_alb_load_balancer_zone_shifted_attachment.go @@ -0,0 +1,190 @@ +// Package alicloud. This file is generated automatically. Please do not modify it manually, thank you! +package alicloud + +import ( + "encoding/json" + "fmt" + "log" + "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" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/tidwall/sjson" +) + +func resourceAliCloudAlbLoadBalancerZoneShiftedAttachment() *schema.Resource { + return &schema.Resource{ + Create: resourceAliCloudAlbLoadBalancerZoneShiftedAttachmentCreate, + Read: resourceAliCloudAlbLoadBalancerZoneShiftedAttachmentRead, + Delete: resourceAliCloudAlbLoadBalancerZoneShiftedAttachmentDelete, + 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{ + "load_balancer_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "vswitch_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "zone_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + } +} + +func resourceAliCloudAlbLoadBalancerZoneShiftedAttachmentCreate(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*connectivity.AliyunClient) + + action := "StartShiftLoadBalancerZones" + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) + conn, err := client.NewAlbClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + if v, ok := d.GetOk("load_balancer_id"); ok { + request["LoadBalancerId"] = v + } + + request["ClientToken"] = buildClientToken(action) + + jsonString := convertObjectToJsonString(request) + jsonString, _ = sjson.Set(jsonString, "ZoneMappings.0.ZoneId", d.Get("zone_id")) + jsonString, _ = sjson.Set(jsonString, "ZoneMappings.0.VSwitchId", d.Get("vswitch_id")) + err = json.Unmarshal([]byte(jsonString), &request) + if err != nil { + return WrapError(err) + } + + 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("2020-06-16"), 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_alb_load_balancer_zone_shifted_attachment", action, AlibabaCloudSdkGoERROR) + } + + ZoneMappingsVSwitchIdVar, _ := jsonpath.Get("ZoneMappings[0].VSwitchId", request) + ZoneMappingsZoneIdVar, _ := jsonpath.Get("ZoneMappings[0].ZoneId", request) + d.SetId(fmt.Sprintf("%v:%v:%v", request["LoadBalancerId"], ZoneMappingsVSwitchIdVar, ZoneMappingsZoneIdVar)) + + return resourceAliCloudAlbLoadBalancerZoneShiftedAttachmentRead(d, meta) +} + +func resourceAliCloudAlbLoadBalancerZoneShiftedAttachmentRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + albServiceV2 := AlbServiceV2{client} + + objectRaw, err := albServiceV2.DescribeAlbLoadBalancerZoneShiftedAttachment(d.Id()) + if err != nil { + if !d.IsNewResource() && NotFoundError(err) { + log.Printf("[DEBUG] Resource alicloud_alb_load_balancer_zone_shifted_attachment DescribeAlbLoadBalancerZoneShiftedAttachment Failed!!! %s", err) + d.SetId("") + return nil + } + return WrapError(err) + } + + if objectRaw["Status"] != nil { + d.Set("status", objectRaw["Status"]) + } + if objectRaw["VSwitchId"] != nil { + d.Set("vswitch_id", objectRaw["VSwitchId"]) + } + if objectRaw["ZoneId"] != nil { + d.Set("zone_id", objectRaw["ZoneId"]) + } + + parts := strings.Split(d.Id(), ":") + d.Set("load_balancer_id", parts[0]) + + return nil +} + +func resourceAliCloudAlbLoadBalancerZoneShiftedAttachmentDelete(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*connectivity.AliyunClient) + parts := strings.Split(d.Id(), ":") + action := "CancelShiftLoadBalancerZones" + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) + conn, err := client.NewAlbClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + request["LoadBalancerId"] = parts[0] + + request["ClientToken"] = buildClientToken(action) + + jsonString := convertObjectToJsonString(request) + jsonString, _ = sjson.Set(jsonString, "ZoneMappings.0.VSwitchId", parts[1]) + jsonString, _ = sjson.Set(jsonString, "ZoneMappings.0.ZoneId", parts[2]) + err = json.Unmarshal([]byte(jsonString), &request) + if err != nil { + return WrapError(err) + } + + 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("2020-06-16"), StringPointer("AK"), query, request, &runtime) + request["ClientToken"] = buildClientToken(action) + + if err != nil { + if 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_alb_load_balancer_zone_shifted_attachment_test.go b/alicloud/resource_alicloud_alb_load_balancer_zone_shifted_attachment_test.go new file mode 100644 index 000000000000..976c5c06aa46 --- /dev/null +++ b/alicloud/resource_alicloud_alb_load_balancer_zone_shifted_attachment_test.go @@ -0,0 +1,121 @@ +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 Alb LoadBalancerZoneShiftedAttachment. >>> Resource test cases, automatically generated. +// Case test 9795 +func TestAccAliCloudAlbLoadBalancerZoneShiftedAttachment_basic9795(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_alb_load_balancer_zone_shifted_attachment.default" + ra := resourceAttrInit(resourceId, AlicloudAlbLoadBalancerZoneShiftedAttachmentMap9795) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &AlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeAlbLoadBalancerZoneShiftedAttachment") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%salbloadbalancerzoneshiftedattachment%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudAlbLoadBalancerZoneShiftedAttachmentBasicDependence9795) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-beijing"}) + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "zone_id": "${alicloud_vswitch.defaultDSY0JJ.zone_id}", + "vswitch_id": "${alicloud_vswitch.defaultDSY0JJ.id}", + "load_balancer_id": "${alicloud_alb_load_balancer.default78TIYG.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "zone_id": CHECKSET, + "vswitch_id": CHECKSET, + "load_balancer_id": CHECKSET, + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +var AlicloudAlbLoadBalancerZoneShiftedAttachmentMap9795 = map[string]string{ + "status": CHECKSET, +} + +func AlicloudAlbLoadBalancerZoneShiftedAttachmentBasicDependence9795(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +resource "alicloud_vpc" "alb_test_tf_vpc" { + vpc_name = var.name + cidr_block = "192.168.0.0/16" +} + +resource "alicloud_vswitch" "alb_test_tf_j" { + vpc_id = alicloud_vpc.alb_test_tf_vpc.id + zone_id = "cn-beijing-j" + cidr_block = "192.168.1.0/24" + vswitch_name = format("%%s1", var.name) +} + +resource "alicloud_vswitch" "alb_test_tf_k" { + vpc_id = alicloud_vpc.alb_test_tf_vpc.id + zone_id = "cn-beijing-k" + cidr_block = "192.168.2.0/24" + vswitch_name = format("%%s2", var.name) +} + +resource "alicloud_vswitch" "defaultDSY0JJ" { + vpc_id = alicloud_vpc.alb_test_tf_vpc.id + zone_id = "cn-beijing-f" + cidr_block = "192.168.3.0/24" + vswitch_name = format("%%s3", var.name) +} + +resource "alicloud_alb_load_balancer" "default78TIYG" { + load_balancer_edition = "Standard" + vpc_id = alicloud_vpc.alb_test_tf_vpc.id + load_balancer_billing_config { + pay_type = "PayAsYouGo" + } + address_type = "Intranet" + address_allocated_mode = "Fixed" + zone_mappings { + vswitch_id = alicloud_vswitch.alb_test_tf_j.id + zone_id = alicloud_vswitch.alb_test_tf_j.zone_id + } + zone_mappings { + vswitch_id = alicloud_vswitch.alb_test_tf_k.id + zone_id = alicloud_vswitch.alb_test_tf_k.zone_id + } + zone_mappings { + vswitch_id = alicloud_vswitch.defaultDSY0JJ.id + zone_id = alicloud_vswitch.defaultDSY0JJ.zone_id + } +} + + +`, name) +} + +// Test Alb LoadBalancerZoneShiftedAttachment. <<< Resource test cases, automatically generated. diff --git a/alicloud/service_alicloud_alb_v2.go b/alicloud/service_alicloud_alb_v2.go index 7368c283c737..19527a3f9e56 100644 --- a/alicloud/service_alicloud_alb_v2.go +++ b/alicloud/service_alicloud_alb_v2.go @@ -691,3 +691,97 @@ func (s *AlbServiceV2) DescribeAsyncAlbLoadBalancerAccessLogConfigAttachmentStat } // DescribeAlbLoadBalancerAccessLogConfigAttachment >>> Encapsulated. + +// DescribeAlbLoadBalancerZoneShiftedAttachment <<< Encapsulated get interface for Alb LoadBalancerZoneShiftedAttachment. + +func (s *AlbServiceV2) DescribeAlbLoadBalancerZoneShiftedAttachment(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) != 3 { + err = WrapError(fmt.Errorf("invalid Resource Id %s. Expected parts' length %d, got %d", id, 3, len(parts))) + } + action := "GetLoadBalancerAttribute" + conn, err := client.NewAlbClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["LoadBalancerId"] = parts[0] + + 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("2020-06-16"), 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("$.ZoneMappings[*]", response) + if err != nil { + return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.ZoneMappings[*]", response) + } + + if len(v.([]interface{})) == 0 { + return object, WrapErrorf(Error(GetNotFoundMessage("LoadBalancerZoneShiftedAttachment", id)), NotFoundMsg, response) + } + + result, _ := v.([]interface{}) + for _, v := range result { + item := v.(map[string]interface{}) + if fmt.Sprint(item["VSwitchId"]) != parts[1] { + continue + } + if fmt.Sprint(item["ZoneId"]) != parts[2] { + continue + } + return item, nil + } + return object, WrapErrorf(Error(GetNotFoundMessage("LoadBalancerZoneShiftedAttachment", id)), NotFoundMsg, response) +} + +func (s *AlbServiceV2) AlbLoadBalancerZoneShiftedAttachmentStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeAlbLoadBalancerZoneShiftedAttachment(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 + } +} + +// DescribeAlbLoadBalancerZoneShiftedAttachment >>> Encapsulated. diff --git a/website/docs/r/alb_load_balancer_zone_shifted_attachment.html.markdown b/website/docs/r/alb_load_balancer_zone_shifted_attachment.html.markdown new file mode 100644 index 000000000000..2e38e5dc08a1 --- /dev/null +++ b/website/docs/r/alb_load_balancer_zone_shifted_attachment.html.markdown @@ -0,0 +1,113 @@ +--- +subcategory: "Application Load Balancer (ALB)" +layout: "alicloud" +page_title: "Alicloud: alicloud_alb_load_balancer_zone_shifted_attachment" +description: |- + Provides a Alicloud Application Load Balancer (ALB) Load Balancer Zone Shifted Attachment resource. +--- + +# alicloud_alb_load_balancer_zone_shifted_attachment + +Provides a Application Load Balancer (ALB) Load Balancer Zone Shifted Attachment resource. + +Application load balancer start-stop zone. + +For information about Application Load Balancer (ALB) Load Balancer Zone Shifted Attachment and how to use it, see [What is Load Balancer Zone Shifted Attachment](https://www.alibabacloud.com/help/en/). + +-> **NOTE:** Available since v1.242.0. + +## Example Usage + +Basic Usage + +```terraform +variable "name" { + default = "terraform-example" +} + +provider "alicloud" { + region = "cn-beijing" +} + +resource "alicloud_vpc" "alb_example_tf_vpc" { + vpc_name = var.name + cidr_block = "192.168.0.0/16" +} + +resource "alicloud_vswitch" "alb_example_tf_j" { + vpc_id = alicloud_vpc.alb_example_tf_vpc.id + zone_id = "cn-beijing-j" + cidr_block = "192.168.1.0/24" + vswitch_name = format("%s1", var.name) +} + +resource "alicloud_vswitch" "alb_example_tf_k" { + vpc_id = alicloud_vpc.alb_example_tf_vpc.id + zone_id = "cn-beijing-k" + cidr_block = "192.168.2.0/24" + vswitch_name = format("%s2", var.name) +} + +resource "alicloud_vswitch" "defaultDSY0JJ" { + vpc_id = alicloud_vpc.alb_example_tf_vpc.id + zone_id = "cn-beijing-f" + cidr_block = "192.168.3.0/24" + vswitch_name = format("%s3", var.name) +} + +resource "alicloud_alb_load_balancer" "default78TIYG" { + load_balancer_edition = "Standard" + vpc_id = alicloud_vpc.alb_example_tf_vpc.id + load_balancer_billing_config { + pay_type = "PayAsYouGo" + } + address_type = "Intranet" + address_allocated_mode = "Fixed" + zone_mappings { + vswitch_id = alicloud_vswitch.alb_example_tf_j.id + zone_id = alicloud_vswitch.alb_example_tf_j.zone_id + } + zone_mappings { + vswitch_id = alicloud_vswitch.alb_example_tf_k.id + zone_id = alicloud_vswitch.alb_example_tf_k.zone_id + } + zone_mappings { + vswitch_id = alicloud_vswitch.defaultDSY0JJ.id + zone_id = alicloud_vswitch.defaultDSY0JJ.zone_id + } +} + + +resource "alicloud_alb_load_balancer_zone_shifted_attachment" "default" { + zone_id = alicloud_vswitch.defaultDSY0JJ.zone_id + vswitch_id = alicloud_vswitch.defaultDSY0JJ.id + load_balancer_id = alicloud_alb_load_balancer.default78TIYG.id +} +``` + +## Argument Reference + +The following arguments are supported: +* `load_balancer_id` - (Required, ForceNew) The ID of the load balancing instance. +* `vswitch_id` - (Required, ForceNew) The VSwitch corresponding to the zone. By default, each zone uses one VSwitch and one subnet. +* `zone_id` - (Required, ForceNew) The ID of the zone. + +## Attributes Reference + +The following attributes are exported: +* `id` - The ID of the resource supplied above.The value is formulated as `::`. +* `status` - Availability zone status. Value: + +## 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 Load Balancer Zone Shifted Attachment. +* `delete` - (Defaults to 5 mins) Used when delete the Load Balancer Zone Shifted Attachment. + +## Import + +Application Load Balancer (ALB) Load Balancer Zone Shifted Attachment can be imported using the id, e.g. + +```shell +$ terraform import alicloud_alb_load_balancer_zone_shifted_attachment.example :: +``` \ No newline at end of file