diff --git a/alicloud/provider.go b/alicloud/provider.go index 7fddae3819ca..802035b4920a 100644 --- a/alicloud/provider.go +++ b/alicloud/provider.go @@ -1061,6 +1061,7 @@ func Provider() terraform.ResourceProvider { "alicloud_ess_alarm": resourceAlicloudEssAlarm(), "alicloud_ess_scalinggroup_vserver_groups": resourceAlicloudEssScalingGroupVserverGroups(), "alicloud_ess_alb_server_group_attachment": resourceAlicloudEssAlbServerGroupAttachment(), + "alicloud_ess_server_group_attachment": resourceAliCloudEssServerGroupAttachment(), "alicloud_vpc": resourceAliCloudVpcVpc(), "alicloud_nat_gateway": resourceAlicloudNatGateway(), "alicloud_nas_file_system": resourceAlicloudNasFileSystem(), diff --git a/alicloud/resource_alicloud_ess_server_group_attachment.go b/alicloud/resource_alicloud_ess_server_group_attachment.go new file mode 100644 index 000000000000..94f37d2f9f35 --- /dev/null +++ b/alicloud/resource_alicloud_ess_server_group_attachment.go @@ -0,0 +1,204 @@ +package alicloud + +import ( + "fmt" + "strconv" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + + "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" + "github.com/aliyun/alibaba-cloud-sdk-go/services/ess" + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func resourceAliCloudEssServerGroupAttachment() *schema.Resource { + return &schema.Resource{ + Create: resourceAliyunEssServerGroupAttachmentCreate, + Read: resourceAliyunEssServerGroupAttachmentRead, + Update: resourceAliyunEssServerGroupAttachmentUpdate, + Delete: resourceAliyunEssServerGroupAttachmentDelete, + 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{ + "scaling_group_id": { + Type: schema.TypeString, + ForceNew: true, + Required: true, + }, + "server_group_id": { + Type: schema.TypeString, + ForceNew: true, + Required: true, + }, + "port": { + Type: schema.TypeInt, + ForceNew: true, + Required: true, + }, + "type": { + Type: schema.TypeString, + ForceNew: true, + ValidateFunc: StringInSlice([]string{"ALB", "NLB"}, false), + Required: true, + }, + "weight": { + Type: schema.TypeInt, + ForceNew: true, + Required: true, + }, + "force_attach": { + Type: schema.TypeBool, + Optional: true, + }, + }, + } +} + +func resourceAliyunEssServerGroupAttachmentCreate(d *schema.ResourceData, meta interface{}) error { + scalingGroupId := d.Get("scaling_group_id").(string) + serverGroupId := d.Get("server_group_id").(string) + typeAttribute := d.Get("type").(string) + port := strconv.Itoa(formatInt(d.Get("port"))) + + client := meta.(*connectivity.AliyunClient) + request := ess.CreateAttachServerGroupsRequest() + request.RegionId = client.RegionId + request.ScalingGroupId = scalingGroupId + request.ForceAttach = requests.NewBoolean(d.Get("force_attach").(bool)) + attachScalingGroupServerGroups := make([]ess.AttachServerGroupsServerGroup, 0) + attachScalingGroupServerGroups = append(attachScalingGroupServerGroups, ess.AttachServerGroupsServerGroup{ + ServerGroupId: serverGroupId, + Port: port, + Weight: strconv.Itoa(formatInt(d.Get("weight"))), + Type: typeAttribute, + }) + request.ServerGroup = &attachScalingGroupServerGroups + wait := incrementalWait(1*time.Second, 2*time.Second) + + var raw interface{} + var err error + err = resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutCreate)), func() *resource.RetryError { + raw, err = client.WithEssClient(func(essClient *ess.Client) (interface{}, error) { + return essClient.AttachServerGroups(request) + }) + if err != nil { + if IsExpectedErrors(err, []string{"IncorrectScalingGroupStatus", "InvalidOperation.Conflict"}) || NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR) + } + addDebug(request.GetActionName(), raw, request.RpcRequest, request) + + response, _ := raw.(*ess.AttachServerGroupsResponse) + + d.SetId(fmt.Sprint(scalingGroupId, ":", serverGroupId, ":", typeAttribute, ":", port)) + if len(response.ScalingActivityId) == 0 { + return resourceAliyunEssServerGroupAttachmentRead(d, meta) + } + essService := EssService{client} + stateConf := BuildStateConf([]string{}, []string{"Successful"}, d.Timeout(schema.TimeoutCreate), 1*time.Minute, essService.ActivityStateRefreshFunc(response.ScalingActivityId, []string{"Failed", "Rejected"})) + if _, err := stateConf.WaitForState(); err != nil { + return WrapErrorf(err, IdMsg, d.Id()) + } + return resourceAliyunEssServerGroupAttachmentRead(d, meta) +} + +func resourceAliyunEssServerGroupAttachmentUpdate(d *schema.ResourceData, meta interface{}) error { + return WrapErrorf(Error("server_group_attachment not support modify operation"), DefaultErrorMsg, "alicloud_ess_server_groups", "Modify", AlibabaCloudSdkGoERROR) +} + +func resourceAliyunEssServerGroupAttachmentRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + essService := EssService{client} + strs, _ := ParseResourceId(d.Id(), 4) + scalingGroupId, serverGroupId, typeAttribute, port := strs[0], strs[1], strs[2], strs[3] + + object, err := essService.DescribeEssScalingGroup(scalingGroupId) + if err != nil { + return WrapError(err) + } + + for _, v := range object.ServerGroups.ServerGroup { + if v.ServerGroupId == serverGroupId && v.Port == formatInt(port) && v.Type == typeAttribute { + d.Set("scaling_group_id", object.ScalingGroupId) + d.Set("type", v.Type) + d.Set("server_group_id", v.ServerGroupId) + d.Set("weight", v.Weight) + d.Set("port", v.Port) + return nil + } + } + return WrapErrorf(Error(GetNotFoundMessage("ServerGroup", d.Id())), NotFoundMsg, ProviderERROR) +} + +func resourceAliyunEssServerGroupAttachmentDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + request := ess.CreateDetachServerGroupsRequest() + request.RegionId = client.RegionId + strs, _ := ParseResourceId(d.Id(), 4) + scalingGroupId, serverGroupId, typeAttribute, port := strs[0], strs[1], strs[2], strs[3] + + request.ScalingGroupId = scalingGroupId + request.ForceDetach = requests.NewBoolean(d.Get("force_attach").(bool)) + detachScalingGroupServerGroups := make([]ess.DetachServerGroupsServerGroup, 0) + detachScalingGroupServerGroups = append(detachScalingGroupServerGroups, ess.DetachServerGroupsServerGroup{ + ServerGroupId: serverGroupId, + Port: port, + Type: typeAttribute, + }) + request.ServerGroup = &detachScalingGroupServerGroups + + activityId := "" + err := resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutDelete)), func() *resource.RetryError { + raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) { + return essClient.DetachServerGroups(request) + }) + if err != nil { + if IsExpectedErrors(err, []string{"IncorrectScalingGroupStatus", "InvalidOperation.Conflict"}) { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + response, _ := raw.(*ess.DetachServerGroupsResponse) + activityId = response.ScalingActivityId + if len(response.ScalingActivityId) == 0 { + return nil + } + + addDebug(request.GetActionName(), raw, request.RpcRequest, request) + return nil + }) + if err != nil { + if strings.Contains(err.Error(), "The specified value of parameter \"ScalingGroupId\" is not valid") { + return nil + } + return WrapErrorf(err, DefaultErrorMsg, d.Id(), request.GetActionName(), AlibabaCloudSdkGoERROR) + } + essService := EssService{client} + if activityId == "" { + return nil + } + stateConf := BuildStateConf([]string{}, []string{"Successful"}, d.Timeout(schema.TimeoutDelete), 1*time.Minute, essService.ActivityStateRefreshFunc(activityId, []string{"Failed", "Rejected"})) + if _, err := stateConf.WaitForState(); err != nil { + if strings.Contains(err.Error(), "activity not found") { + return nil + } + return WrapErrorf(err, IdMsg, d.Id()) + } + return nil +} diff --git a/alicloud/resource_alicloud_ess_server_group_attachment_test.go b/alicloud/resource_alicloud_ess_server_group_attachment_test.go new file mode 100644 index 000000000000..89d1ef8bab1f --- /dev/null +++ b/alicloud/resource_alicloud_ess_server_group_attachment_test.go @@ -0,0 +1,517 @@ +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" + "github.com/hashicorp/terraform-plugin-sdk/terraform" +) + +func TestAccAliCloudEssServerGroupAttachment_basic_alb(t *testing.T) { + rand := acctest.RandIntRange(1000, 999999) + resourceId := "alicloud_ess_server_group_attachment.default" + basicMap := map[string]string{ + "scaling_group_id": CHECKSET, + } + ra := resourceAttrInit(resourceId, basicMap) + testAccCheck := ra.resourceAttrMapUpdateSet() + name := fmt.Sprintf("tf-testAccEssScalingGroupServerGroup-%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, testAccEssScalingGroupServerGroup) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + // module name + IDRefreshName: resourceId, + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssServerGroupsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "depends_on": []string{"alicloud_ess_scaling_configuration.default"}, + "force_attach": true, + "weight": "100", + "port": "80", + "type": "ALB", + "server_group_id": "${alicloud_alb_server_group.default.id}", + "scaling_group_id": "${alicloud_ess_scaling_group.default.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "id": CHECKSET, + "weight": "100", + "port": "80", + "type": "ALB", + "server_group_id": CHECKSET, + "scaling_group_id": CHECKSET, + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"force_attach"}, + }, + }, + }) +} + +func TestAccAliCloudEssServerGroupAttachment_nonForceAttach_alb(t *testing.T) { + rand := acctest.RandIntRange(1000, 999999) + resourceId := "alicloud_ess_server_group_attachment.default" + basicMap := map[string]string{ + "scaling_group_id": CHECKSET, + } + ra := resourceAttrInit(resourceId, basicMap) + testAccCheck := ra.resourceAttrMapUpdateSet() + name := fmt.Sprintf("tf-testAccEssScalingGroupServerGroup-%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, testAccEssScalingGroupServerGroupNotForceAttach) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + // module name + IDRefreshName: resourceId, + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssServerGroupsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "depends_on": []string{"alicloud_ess_scaling_configuration.default"}, + "force_attach": false, + "weight": "11", + "port": "22", + "type": "ALB", + "server_group_id": "${alicloud_alb_server_group.default.id}", + "scaling_group_id": "${alicloud_ess_scaling_group.default.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "id": CHECKSET, + "weight": "11", + "port": "22", + "type": "ALB", + "server_group_id": CHECKSET, + "scaling_group_id": CHECKSET, + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"force_attach"}, + }, + }, + }) +} + +func TestAccAliCloudEssServerGroupAttachment_basic_nlb(t *testing.T) { + rand := acctest.RandIntRange(1000, 999999) + resourceId := "alicloud_ess_server_group_attachment.default" + basicMap := map[string]string{ + "scaling_group_id": CHECKSET, + } + ra := resourceAttrInit(resourceId, basicMap) + testAccCheck := ra.resourceAttrMapUpdateSet() + name := fmt.Sprintf("tf-testAccEssScalingGroupServerGroup-%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, testAccEssScalingGroupServerGroup) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + // module name + IDRefreshName: resourceId, + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssServerGroupsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "depends_on": []string{"alicloud_ess_scaling_configuration.default"}, + "force_attach": true, + "weight": "100", + "port": "80", + "type": "NLB", + "server_group_id": "${alicloud_nlb_server_group.default.id}", + "scaling_group_id": "${alicloud_ess_scaling_group.default.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "id": CHECKSET, + "weight": "100", + "port": "80", + "type": "NLB", + "server_group_id": CHECKSET, + "scaling_group_id": CHECKSET, + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"force_attach"}, + }, + }, + }) +} + +func TestAccAliCloudEssServerGroupAttachment_nonForceAttach_nlb(t *testing.T) { + rand := acctest.RandIntRange(1000, 999999) + resourceId := "alicloud_ess_server_group_attachment.default" + basicMap := map[string]string{ + "scaling_group_id": CHECKSET, + } + ra := resourceAttrInit(resourceId, basicMap) + testAccCheck := ra.resourceAttrMapUpdateSet() + name := fmt.Sprintf("tf-testAccEssScalingGroupServerGroup-%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, testAccEssScalingGroupServerGroupNotForceAttach) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + // module name + IDRefreshName: resourceId, + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssServerGroupsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "depends_on": []string{"alicloud_ess_scaling_configuration.default"}, + "force_attach": false, + "weight": "11", + "port": "22", + "type": "NLB", + "server_group_id": "${alicloud_nlb_server_group.default.id}", + "scaling_group_id": "${alicloud_ess_scaling_group.default.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "id": CHECKSET, + "server_group_id": CHECKSET, + "scaling_group_id": CHECKSET, + "weight": "11", + "port": "22", + "type": "NLB", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"force_attach"}, + }, + }, + }) +} + +func TestAccAliCloudEssServerGroupAttachment_nonForceAttach_mutil(t *testing.T) { + rand := acctest.RandIntRange(1000, 999999) + resourceId := "alicloud_ess_server_group_attachment.default.1" + basicMap := map[string]string{ + "scaling_group_id": CHECKSET, + } + ra := resourceAttrInit(resourceId, basicMap) + testAccCheck := ra.resourceAttrMapUpdateSet() + name := fmt.Sprintf("tf-testAccEssScalingGroupServerGroup-%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, testAccEssScalingGroupServerGroupNotForceAttachMutil) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + // module name + IDRefreshName: resourceId, + + Providers: testAccProviders, + CheckDestroy: testAccCheckEssServerGroupsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "count": "2", + "depends_on": []string{"alicloud_ess_scaling_configuration.default"}, + "force_attach": false, + "weight": "11", + "port": "22", + "type": "ALB", + "server_group_id": "${element(alicloud_alb_server_group.default.*.id,count.index)}", + "scaling_group_id": "${alicloud_ess_scaling_group.default.id}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "weight": "11", + "port": "22", + "type": "ALB", + "server_group_id": CHECKSET, + "scaling_group_id": CHECKSET, + }), + ), + }, + }, + }) +} + +func testAccCheckEssServerGroupsDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*connectivity.AliyunClient) + essService := EssService{client} + for _, rs := range s.RootModule().Resources { + if rs.Type != "alicloud_ess_scaling_group" { + continue + } + + scalingGroup, err := essService.DescribeEssScalingGroup(rs.Primary.ID) + if err != nil { + if NotFoundError(err) { + continue + } + return WrapError(err) + } + if len(scalingGroup.ServerGroups.ServerGroup) > 0 { + return WrapError(fmt.Errorf("There are still attached server groups.")) + } + } + return nil +} +func testAccEssScalingGroupServerGroupNotForceAttach(name string) string { + return fmt.Sprintf(` + %s + variable "name" { + default = "%s" + } + + resource "alicloud_ess_scaling_group" "default" { + min_size = "0" + max_size = "2" + default_cooldown = 200 + scaling_group_name = "${var.name}" + removal_policies = ["OldestInstance"] + vswitch_ids = ["${alicloud_vswitch.default.id}"] + } + data "alicloud_images" "default2" { + name_regex = "^aliyun" + most_recent = true + owners = "system" + } + data "alicloud_instance_types" "c6" { + instance_type_family = "ecs.c6" + availability_zone = "${data.alicloud_zones.default.zones.0.id}" + } + data "alicloud_resource_manager_resource_groups" "default" {} + resource "alicloud_nlb_server_group" "default" { + resource_group_id = data.alicloud_resource_manager_resource_groups.default.ids.0 + server_group_name = var.name + server_group_type = "Instance" + vpc_id = alicloud_vpc.default.id + scheduler = "Wrr" + protocol = "TCP" + health_check { + health_check_url = "/test/index.html" + health_check_domain = "tf-testAcc.com" + health_check_enabled = true + health_check_type = "TCP" + health_check_connect_port = 0 + healthy_threshold = 2 + unhealthy_threshold = 2 + health_check_connect_timeout = 5 + health_check_interval = 10 + http_check_method = "GET" + health_check_http_code = ["http_2xx", "http_3xx", "http_4xx"] + } + connection_drain = true + connection_drain_timeout = 60 + preserve_client_ip_enabled = true + tags = { + Created = "TF" + } + address_ip_version = "Ipv4" + } + resource "alicloud_ess_scaling_configuration" "default" { + scaling_group_id = alicloud_ess_scaling_group.default.id + image_id = data.alicloud_images.default2.images[0].id + instance_type = data.alicloud_instance_types.c6.instance_types[0].id + security_group_id = alicloud_security_group.default.id + force_delete = true + active = true + enable = true + } + + resource "alicloud_alb_server_group" "default" { + server_group_name = "${var.name}" + vpc_id = "${alicloud_vpc.default.id}" + health_check_config { + health_check_enabled = "false" + } + sticky_session_config { + sticky_session_enabled = true + cookie = "tf-testAcc" + sticky_session_type = "Server" + } + } + `, EcsInstanceCommonTestCase, name) +} + +func testAccEssScalingGroupServerGroupNotForceAttachMutil(name string) string { + return fmt.Sprintf(` + %s + variable "name" { + default = "%s" + } + + resource "alicloud_ess_scaling_group" "default" { + min_size = "0" + max_size = "2" + default_cooldown = 200 + scaling_group_name = "${var.name}" + removal_policies = ["OldestInstance"] + vswitch_ids = ["${alicloud_vswitch.default.id}"] + } + data "alicloud_images" "default2" { + name_regex = "^aliyun" + most_recent = true + owners = "system" + } + data "alicloud_instance_types" "c6" { + instance_type_family = "ecs.c6" + availability_zone = "${data.alicloud_zones.default.zones.0.id}" + } + data "alicloud_resource_manager_resource_groups" "default" {} + resource "alicloud_nlb_server_group" "default" { + resource_group_id = data.alicloud_resource_manager_resource_groups.default.ids.0 + server_group_name = var.name + server_group_type = "Instance" + vpc_id = alicloud_vpc.default.id + scheduler = "Wrr" + protocol = "TCP" + health_check { + health_check_url = "/test/index.html" + health_check_domain = "tf-testAcc.com" + health_check_enabled = true + health_check_type = "TCP" + health_check_connect_port = 0 + healthy_threshold = 2 + unhealthy_threshold = 2 + health_check_connect_timeout = 5 + health_check_interval = 10 + http_check_method = "GET" + health_check_http_code = ["http_2xx", "http_3xx", "http_4xx"] + } + connection_drain = true + connection_drain_timeout = 60 + preserve_client_ip_enabled = true + tags = { + Created = "TF" + } + address_ip_version = "Ipv4" + } + resource "alicloud_ess_scaling_configuration" "default" { + scaling_group_id = alicloud_ess_scaling_group.default.id + image_id = data.alicloud_images.default2.images[0].id + instance_type = data.alicloud_instance_types.c6.instance_types[0].id + security_group_id = alicloud_security_group.default.id + force_delete = true + active = true + enable = true + } + + resource "alicloud_alb_server_group" "default" { + count = 2 + server_group_name = "${var.name}" + vpc_id = "${alicloud_vpc.default.id}" + health_check_config { + health_check_enabled = "false" + } + sticky_session_config { + sticky_session_enabled = true + cookie = "tf-testAcc" + sticky_session_type = "Server" + } + } + `, EcsInstanceCommonTestCase, name) +} + +func testAccEssScalingGroupServerGroup(name string) string { + return fmt.Sprintf(` + %s + variable "name" { + default = "%s" + } + + resource "alicloud_ess_scaling_group" "default" { + min_size = "0" + max_size = "2" + default_cooldown = 200 + scaling_group_name = "${var.name}" + removal_policies = ["OldestInstance"] + vswitch_ids = ["${alicloud_vswitch.default.id}"] + } + + data "alicloud_images" "default2" { + name_regex = "^aliyun" + most_recent = true + owners = "system" + } + data "alicloud_instance_types" "c6" { + instance_type_family = "ecs.c6" + availability_zone = "${data.alicloud_zones.default.zones.0.id}" + } + data "alicloud_resource_manager_resource_groups" "default" {} + resource "alicloud_nlb_server_group" "default" { + resource_group_id = data.alicloud_resource_manager_resource_groups.default.ids.0 + server_group_name = var.name + server_group_type = "Instance" + vpc_id = alicloud_vpc.default.id + scheduler = "Wrr" + protocol = "TCP" + health_check { + health_check_url = "/test/index.html" + health_check_domain = "tf-testAcc.com" + health_check_enabled = true + health_check_type = "TCP" + health_check_connect_port = 0 + healthy_threshold = 2 + unhealthy_threshold = 2 + health_check_connect_timeout = 5 + health_check_interval = 10 + http_check_method = "GET" + health_check_http_code = ["http_2xx", "http_3xx", "http_4xx"] + } + connection_drain = true + connection_drain_timeout = 60 + preserve_client_ip_enabled = true + tags = { + Created = "TF" + } + address_ip_version = "Ipv4" + } + resource "alicloud_ess_scaling_configuration" "default" { + scaling_group_id = alicloud_ess_scaling_group.default.id + image_id = data.alicloud_images.default2.images[0].id + instance_type = data.alicloud_instance_types.c6.instance_types[0].id + security_group_id = alicloud_security_group.default.id + force_delete = true + active = true + enable = true + } + + resource "alicloud_alb_server_group" "default" { + server_group_name = "${var.name}" + vpc_id = "${alicloud_vpc.default.id}" + health_check_config { + health_check_enabled = "false" + } + sticky_session_config { + sticky_session_enabled = true + cookie = "tf-testAcc" + sticky_session_type = "Server" + } + } + `, EcsInstanceCommonTestCase, name) +} diff --git a/website/docs/r/ess_server_group_attachment.html.markdown b/website/docs/r/ess_server_group_attachment.html.markdown new file mode 100644 index 000000000000..9a827e93d1de --- /dev/null +++ b/website/docs/r/ess_server_group_attachment.html.markdown @@ -0,0 +1,153 @@ +--- +subcategory: "Auto Scaling" +layout: "alicloud" +page_title: "Alicloud: alicloud_ess_server_group_attachment" +sidebar_current: "docs-alicloud-resource-ess-server-group-attachment" +description: |- + Provides a ESS Attachment resource to attach or remove server group. +--- + +# alicloud_ess_server_group_attachment + +Attaches/Detaches server group to a specified scaling group. + +For information about server group attachment, see [AttachServerGroups](https://www.alibabacloud.com/help/en/auto-scaling/developer-reference/api-attachservergroups). + +-> **NOTE:** If scaling group's network type is `VPC`, the server groups must be in the same `VPC`. + +-> **NOTE:** server group attachment is defined uniquely by `scaling_group_id`, `server_group_id`,`type`, `port`. + +-> **NOTE:** Resource `alicloud_ess_server_group_attachment` don't support modification. + +-> **NOTE:** Available since v1.231.0. + +## Example Usage + +
+ + Open in AliCloud + +
+ +```terraform +variable "name" { + default = "terraform-example" +} + +resource "random_integer" "default" { + min = 10000 + max = 99999 +} + +locals { + name = "${var.name}-${random_integer.default.result}" +} + +data "alicloud_zones" "default" { + available_disk_category = "cloud_efficiency" + available_resource_creation = "VSwitch" +} + +data "alicloud_instance_types" "default" { + availability_zone = data.alicloud_zones.default.zones[0].id + cpu_core_count = 2 + memory_size = 4 +} + +data "alicloud_images" "default" { + name_regex = "^ubuntu_18.*64" + most_recent = true + owners = "system" +} + +resource "alicloud_vpc" "default" { + vpc_name = local.name + cidr_block = "172.16.0.0/16" +} + +resource "alicloud_vswitch" "default" { + vpc_id = alicloud_vpc.default.id + cidr_block = "172.16.0.0/24" + zone_id = data.alicloud_zones.default.zones[0].id + vswitch_name = local.name +} + +resource "alicloud_security_group" "default" { + name = local.name + vpc_id = alicloud_vpc.default.id +} + +resource "alicloud_ess_scaling_group" "default" { + min_size = "0" + max_size = "2" + scaling_group_name = local.name + default_cooldown = 200 + removal_policies = ["OldestInstance"] + vswitch_ids = [alicloud_vswitch.default.id] +} + +resource "alicloud_ess_scaling_configuration" "default" { + scaling_group_id = alicloud_ess_scaling_group.default.id + image_id = data.alicloud_images.default.images[0].id + instance_type = data.alicloud_instance_types.default.instance_types[0].id + security_group_id = alicloud_security_group.default.id + force_delete = true + active = true + enable = true +} + +resource "alicloud_alb_server_group" "default" { + server_group_name = local.name + vpc_id = alicloud_vpc.default.id + health_check_config { + health_check_enabled = "false" + } + sticky_session_config { + sticky_session_enabled = true + cookie = "tf-example" + sticky_session_type = "Server" + } +} + +resource "alicloud_ess_server_group_attachment" "default" { + scaling_group_id = alicloud_ess_scaling_configuration.default.scaling_group_id + server_group_id = alicloud_alb_server_group.default.id + port = 9000 + type = "ALB" + weight = 50 + force_attach = true +} +``` + +## Argument Reference + +The following arguments are supported: + +* `scaling_group_id` - (Required, ForceNew) ID of the scaling group. +* `server_group_id` - (Required, ForceNew) ID of Server Group. +* `type` - (Required, ForceNew) The type of server group N. Valid values: ALB, NLB. +* `port` - (Required, ForceNew) - The port will be used for Server Group backend server. +* `weight` - (Required, ForceNew) The weight of an ECS instance attached to the Alb Server Group. +* `force_attach` - (Optional) If instances of scaling group are attached/removed from backend server when + server group from scaling group. Default to false. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The ESS server group attachment resource ID,in the follwing format: scaling_group_id: + server_group_id:type:port. + +## 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 connecting the scaling group. +* `delete` - (Defaults to 5 mins) Used when unbundling the scaling group. +画 + +ESS server groups can be imported using the id, e.g. + +```shell +$ terraform import alicloud_ess_server_group_attachment.example asg-xxx:sgp-xxx:ALB:5000 +```