diff --git a/alicloud/data_source_alicloud_ess_scaling_groups.go b/alicloud/data_source_alicloud_ess_scaling_groups.go new file mode 100644 index 000000000000..a9ec3a65dc60 --- /dev/null +++ b/alicloud/data_source_alicloud_ess_scaling_groups.go @@ -0,0 +1,488 @@ +package alicloud + +import ( + "fmt" + "github.com/PaesslerAG/jsonpath" + util "github.com/alibabacloud-go/tea-utils/service" + "regexp" + + "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" +) + +func dataSourceAlicloudEssScalingGroups() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAlicloudEssScalingGroupsRead, + Schema: map[string]*schema.Schema{ + "name_regex": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.ValidateRegexp, + ForceNew: true, + }, + "ids": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Computed: true, + ForceNew: true, + }, + "output_file": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "names": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "groups": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "active_scaling_configuration": { + Type: schema.TypeString, + Computed: true, + }, + "launch_template_id": { + Type: schema.TypeString, + Computed: true, + }, + "launch_template_version": { + Type: schema.TypeString, + Computed: true, + }, + "region_id": { + Type: schema.TypeString, + Computed: true, + }, + "min_size": { + Type: schema.TypeInt, + Computed: true, + }, + "desired_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "max_instance_lifetime": { + Type: schema.TypeInt, + Computed: true, + }, + "max_size": { + Type: schema.TypeInt, + Computed: true, + }, + "stop_instance_timeout": { + Type: schema.TypeInt, + Computed: true, + }, + "on_demand_base_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "cooldown_time": { + Type: schema.TypeInt, + Computed: true, + }, + "removal_policies": { + Type: schema.TypeList, + Elem: &schema.Schema{Type: schema.TypeString}, + Computed: true, + }, + "load_balancer_ids": { + Type: schema.TypeList, + Elem: &schema.Schema{Type: schema.TypeString}, + Computed: true, + }, + "db_instance_ids": { + Type: schema.TypeList, + Elem: &schema.Schema{Type: schema.TypeString}, + Computed: true, + }, + "vswitch_ids": { + Type: schema.TypeList, + Elem: &schema.Schema{Type: schema.TypeString}, + Computed: true, + }, + "resource_group_id": { + Type: schema.TypeString, + Computed: true, + }, + "lifecycle_state": { + Type: schema.TypeString, + Computed: true, + }, + "vpc_id": { + Type: schema.TypeString, + Computed: true, + }, + "vswitch_id": { + Type: schema.TypeString, + Computed: true, + }, + "health_check_type": { + Type: schema.TypeString, + Computed: true, + }, + "az_balance": { + Type: schema.TypeBool, + Computed: true, + }, + "system_suspended": { + Type: schema.TypeBool, + Computed: true, + }, + "group_type": { + Type: schema.TypeString, + Computed: true, + }, + "monitor_group_id": { + Type: schema.TypeString, + Computed: true, + }, + "suspended_processes": { + Type: schema.TypeList, + Elem: &schema.Schema{Type: schema.TypeString}, + Computed: true, + }, + "multi_az_policy": { + Type: schema.TypeString, + Computed: true, + }, + "scaling_policy": { + Type: schema.TypeString, + Computed: true, + }, + "spot_allocation_strategy": { + Type: schema.TypeString, + Computed: true, + }, + "group_deletion_protection": { + Type: schema.TypeBool, + Computed: true, + }, + "on_demand_percentage_above_base_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "spot_instance_remedy": { + Type: schema.TypeBool, + Computed: true, + }, + "enable_desired_capacity": { + Type: schema.TypeBool, + Computed: true, + }, + "allocation_strategy": { + Type: schema.TypeString, + Computed: true, + }, + "modification_time": { + Type: schema.TypeString, + Computed: true, + }, + "spot_instance_pools": { + Type: schema.TypeInt, + Computed: true, + }, + "total_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "init_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "pending_wait_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "removing_wait_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "protected_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "standby_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "spot_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "stopped_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "total_instance_count": { + Type: schema.TypeInt, + Computed: true, + }, + "active_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "pending_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "removing_capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "creation_time": { + Type: schema.TypeString, + Computed: true, + }, + "tags": { + Type: schema.TypeMap, + Computed: true, + }, + }, + }, + }, + }, + } +} + +func dataSourceAlicloudEssScalingGroupsRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + + var response map[string]interface{} + conn, err := client.NewEssClient() + if err != nil { + return WrapError(err) + } + request := map[string]interface{}{ + "PageSize": requests.NewInteger(PageSizeLarge), + "PageNumber": requests.NewInteger(1), + "RegionId": client.RegionId, + } + + var allScalingGroups []interface{} + for { + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + response, err = conn.DoRequest(StringPointer("DescribeScalingGroups"), nil, StringPointer("POST"), StringPointer("2014-08-28"), StringPointer("AK"), nil, request, &runtime) + if err != nil { + return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ess_scalinggroups", "DescribeScalingGroups", AlibabaCloudSdkGoERROR) + } + + v, err := jsonpath.Get("$.ScalingGroups.ScalingGroup", response) + if err != nil { + return WrapErrorf(err, FailedGetAttributeMsg, "$.ScalingGroups.ScalingGroup", response) + } + + addDebug("DescribeScalingGroups", response, request, request) + if len(v.([]interface{})) < 1 { + break + } + + allScalingGroups = append(allScalingGroups, v.([]interface{})...) + + if len(v.([]interface{})) < PageSizeLarge { + break + } + + if page, err := getNextpageNumber(requests.Integer(fmt.Sprint(request["PageNumber"]))); err != nil { + return WrapError(err) + } else { + request["PageNumber"] = page + } + } + + var filteredScalingGroupsTemp []interface{} + + nameRegex, okNameRegex := d.GetOk("name_regex") + idsMap := make(map[string]string) + ids, okIds := d.GetOk("ids") + if okIds { + for _, i := range ids.([]interface{}) { + if i == nil { + continue + } + idsMap[i.(string)] = i.(string) + } + } + if okNameRegex || okIds { + for _, group := range allScalingGroups { + var object map[string]interface{} + object = group.(map[string]interface{}) + if okNameRegex && nameRegex != "" { + r, err := regexp.Compile(nameRegex.(string)) + if err != nil { + return WrapError(err) + } + if r != nil && !r.MatchString(object["ScalingGroupName"].(string)) { + continue + } + } + if okIds && len(idsMap) > 0 { + if _, ok := idsMap[object["ScalingGroupId"].(string)]; !ok { + continue + } + } + filteredScalingGroupsTemp = append(filteredScalingGroupsTemp, group) + } + } else { + filteredScalingGroupsTemp = allScalingGroups + } + return scalingGroupsDescriptionAttribute(d, filteredScalingGroupsTemp, meta, client) +} + +func scalingGroupsDescriptionAttribute(d *schema.ResourceData, scalingGroups []interface{}, meta interface{}, client *connectivity.AliyunClient) error { + var ids []string + var names []string + var s = make([]map[string]interface{}, 0) + essService := EssService{client} + + for _, scalingGroup := range scalingGroups { + var object map[string]interface{} + object = scalingGroup.(map[string]interface{}) + mapping := map[string]interface{}{ + "id": object["ScalingGroupId"], + "name": object["ScalingGroupName"], + "active_scaling_configuration": object["ActiveScalingConfigurationId"], + "launch_template_id": object["LaunchTemplateId"], + "launch_template_version": object["LaunchTemplateVersion"], + "region_id": object["RegionId"], + "min_size": object["MinSize"], + "max_size": object["MaxSize"], + "group_type": object["GroupType"], + "monitor_group_id": object["MonitorGroupId"], + "cooldown_time": object["DefaultCooldown"], + "stop_instance_timeout": object["StopInstanceTimeout"], + "lifecycle_state": object["LifecycleState"], + "total_capacity": object["TotalCapacity"], + "active_capacity": object["ActiveCapacity"], + "enable_desired_capacity": object["EnableDesiredCapacity"], + "pending_capacity": object["PendingCapacity"], + "removing_capacity": object["RemovingCapacity"], + "total_instance_count": object["TotalInstanceCount"], + "init_capacity": object["InitCapacity"], + "scaling_policy": object["ScalingPolicy"], + "pending_wait_capacity": object["PendingWaitCapacity"], + "removing_wait_capacity": object["RemovingWaitCapacity"], + "protected_capacity": object["ProtectedCapacity"], + "standby_capacity": object["StandbyCapacity"], + "spot_capacity": object["SpotCapacity"], + "stopped_capacity": object["StoppedCapacity"], + "system_suspended": object["SystemSuspended"], + "vpc_id": object["VpcId"], + "vswitch_id": object["VSwitchId"], + "health_check_type": object["HealthCheckType"], + "group_deletion_protection": object["GroupDeletionProtection"], + "spot_instance_remedy": object["SpotInstanceRemedy"], + "modification_time": object["ModificationTime"], + "creation_time": object["CreationTime"], + "multi_az_policy": object["MultiAZPolicy"], + "resource_group_id": object["ResourceGroupId"], + } + if object["DesiredCapacity"] != nil { + mapping["desired_capacity"] = object["DesiredCapacity"] + } + if object["AzBalance"] != nil { + mapping["az_balance"] = object["AzBalance"] + } + if object["SpotAllocationStrategy"] != nil { + mapping["spot_allocation_strategy"] = object["SpotAllocationStrategy"] + } + if object["AllocationStrategy"] != nil { + mapping["allocation_strategy"] = object["AllocationStrategy"] + } + if object["OnDemandBaseCapacity"] != nil { + mapping["on_demand_base_capacity"] = object["OnDemandBaseCapacity"] + } + if object["OnDemandPercentageAboveBaseCapacity"] != nil { + mapping["on_demand_percentage_above_base_capacity"] = object["OnDemandPercentageAboveBaseCapacity"] + } + if object["SpotInstancePools"] != nil { + mapping["spot_instance_pools"] = object["SpotInstancePools"] + } + if object["MaxInstanceLifetime"] != nil { + mapping["max_instance_lifetime"] = object["MaxInstanceLifetime"] + } + var dbIds []string + if len(object["DBInstanceIds"].(map[string]interface{})["DBInstanceId"].([]interface{})) > 0 { + for _, v := range object["DBInstanceIds"].(map[string]interface{})["DBInstanceId"].([]interface{}) { + dbIds = append(dbIds, v.(string)) + } + mapping["db_instance_ids"] = dbIds + } + + var slbIds []string + if len(object["LoadBalancerIds"].(map[string]interface{})["LoadBalancerId"].([]interface{})) > 0 { + for _, v := range object["LoadBalancerIds"].(map[string]interface{})["LoadBalancerId"].([]interface{}) { + slbIds = append(slbIds, v.(string)) + } + mapping["loadbalancer_ids"] = slbIds + } + + var polices []string + if len(object["RemovalPolicies"].(map[string]interface{})["RemovalPolicy"].([]interface{})) > 0 { + for _, v := range object["RemovalPolicies"].(map[string]interface{})["RemovalPolicy"].([]interface{}) { + polices = append(polices, v.(string)) + } + mapping["removal_policies"] = polices + } + + var vswitchIds []string + if object["VSwitchIds"] != nil && len(object["VSwitchIds"].(map[string]interface{})["VSwitchId"].([]interface{})) > 0 { + for _, v := range object["VSwitchIds"].(map[string]interface{})["VSwitchId"].([]interface{}) { + vswitchIds = append(vswitchIds, v.(string)) + } + mapping["vswitch_ids"] = vswitchIds + } + + var suspendedProcesses []string + if object["SuspendedProcesses"] != nil && len(object["SuspendedProcesses"].(map[string]interface{})["SuspendedProcess"].([]interface{})) > 0 { + for _, v := range object["SuspendedProcesses"].(map[string]interface{})["SuspendedProcess"].([]interface{}) { + suspendedProcesses = append(suspendedProcesses, v.(string)) + } + mapping["suspended_processes"] = suspendedProcesses + } + + listTagResourcesObject, err := essService.ListTagResources(d.Id(), client) + if err != nil { + return WrapError(err) + } + mapping["tags"] = tagsToMap(listTagResourcesObject) + + ids = append(ids, object["ScalingGroupId"].(string)) + names = append(names, object["ScalingGroupName"].(string)) + s = append(s, mapping) + } + + d.SetId(dataResourceIdHash(ids)) + if err := d.Set("groups", s); err != nil { + return WrapError(err) + } + + if err := d.Set("ids", ids); err != nil { + return WrapError(err) + } + + if err := d.Set("names", names); err != nil { + return WrapError(err) + } + + if output, ok := d.GetOk("output_file"); ok && output.(string) != "" { + writeToFile(output.(string), s) + } + return nil +} diff --git a/alicloud/data_source_alicloud_ess_scaling_groups_test.go b/alicloud/data_source_alicloud_ess_scaling_groups_test.go new file mode 100644 index 000000000000..11836b943cc9 --- /dev/null +++ b/alicloud/data_source_alicloud_ess_scaling_groups_test.go @@ -0,0 +1,290 @@ +package alicloud + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" +) + +func TestAccAliCloudEssScalingGroupsDataSource(t *testing.T) { + rand := acctest.RandInt() + nameRegexConf := dataSourceTestAccConfig{ + existConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ + "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}"`, + }), + fakeConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ + "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}_fake"`, + }), + } + + idsConf := dataSourceTestAccConfig{ + existConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ + "ids": `["${alicloud_ess_scaling_group.default.id}"]`, + }), + fakeConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ + "ids": `["${alicloud_ess_scaling_group.default.id}_fake"]`, + }), + } + + allConf := dataSourceTestAccConfig{ + existConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ + "ids": `["${alicloud_ess_scaling_group.default.id}"]`, + "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}"`, + }), + fakeConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ + "ids": `["${alicloud_ess_scaling_group.default.id}_fake"]`, + "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}"`, + }), + } + + var existEssScalingGroupsMapFunc = func(rand int) map[string]string { + return map[string]string{ + "groups.#": "1", + "ids.#": "1", + "names.#": "1", + "groups.0.id": CHECKSET, + "groups.0.name": fmt.Sprintf("tf-testAccDataSourceEssScalingGroups-%d", rand), + "groups.0.region_id": CHECKSET, + "groups.0.min_size": "0", + "groups.0.desired_capacity": "1", + "groups.0.max_size": "2", + "groups.0.cooldown_time": "20", + "groups.0.scaling_policy": "release", + "groups.0.stop_instance_timeout": "30", + "groups.0.max_instance_lifetime": "86400", + "groups.0.removal_policies.#": "2", + "groups.0.removal_policies.0": "OldestInstance", + "groups.0.removal_policies.1": "NewestInstance", + "groups.0.load_balancer_ids.#": "0", + "groups.0.db_instance_ids.#": "0", + "groups.0.vswitch_ids.#": "1", + "groups.0.enable_desired_capacity": CHECKSET, + "groups.0.monitor_group_id": CHECKSET, + "groups.0.system_suspended": CHECKSET, + "groups.0.resource_group_id": CHECKSET, + "groups.0.group_type": CHECKSET, + "groups.0.total_capacity": CHECKSET, + "groups.0.init_capacity": CHECKSET, + "groups.0.pending_wait_capacity": CHECKSET, + "groups.0.removing_wait_capacity": CHECKSET, + "groups.0.protected_capacity": CHECKSET, + "groups.0.standby_capacity": CHECKSET, + "groups.0.spot_capacity": CHECKSET, + "groups.0.stopped_capacity": CHECKSET, + "groups.0.multi_az_policy": CHECKSET, + "groups.0.active_capacity": CHECKSET, + "groups.0.pending_capacity": CHECKSET, + "groups.0.removing_capacity": CHECKSET, + "groups.0.creation_time": CHECKSET, + "groups.0.vpc_id": CHECKSET, + "groups.0.vswitch_id": CHECKSET, + "groups.0.health_check_type": CHECKSET, + "groups.0.suspended_processes.#": "0", + "groups.0.group_deletion_protection": CHECKSET, + "groups.0.spot_instance_remedy": CHECKSET, + "groups.0.modification_time": CHECKSET, + "groups.0.total_instance_count": CHECKSET, + "groups.0.lifecycle_state": CHECKSET, + "groups.0.tags.key": "value", + } + } + + var fakeEssScalingGroupsMapFunc = func(rand int) map[string]string { + return map[string]string{ + "groups.#": "0", + "ids.#": "0", + "names.#": "0", + } + } + + var essScalingGroupsCheckInfo = dataSourceAttr{ + resourceId: "data.alicloud_ess_scaling_groups.default", + existMapFunc: existEssScalingGroupsMapFunc, + fakeMapFunc: fakeEssScalingGroupsMapFunc, + } + + essScalingGroupsCheckInfo.dataSourceTestCheck(t, rand, nameRegexConf, idsConf, allConf) +} + +func TestAccAliCloudEssScalingGroupsDataSourceSupply(t *testing.T) { + rand := acctest.RandInt() + nameRegexConf := dataSourceTestAccConfig{ + existConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfigSupply(rand, map[string]string{ + "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}"`, + }), + fakeConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfigSupply(rand, map[string]string{ + "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}_fake"`, + }), + } + + idsConf := dataSourceTestAccConfig{ + existConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfigSupply(rand, map[string]string{ + "ids": `["${alicloud_ess_scaling_group.default.id}"]`, + }), + fakeConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfigSupply(rand, map[string]string{ + "ids": `["${alicloud_ess_scaling_group.default.id}_fake"]`, + }), + } + + allConf := dataSourceTestAccConfig{ + existConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfigSupply(rand, map[string]string{ + "ids": `["${alicloud_ess_scaling_group.default.id}"]`, + "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}"`, + }), + fakeConfig: testAccCheckAliCloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ + "ids": `["${alicloud_ess_scaling_group.default.id}_fake"]`, + "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}"`, + }), + } + + var existEssScalingGroupsMapFunc = func(rand int) map[string]string { + return map[string]string{ + "groups.#": "1", + "ids.#": "1", + "names.#": "1", + "groups.0.id": CHECKSET, + "groups.0.name": fmt.Sprintf("tf-testAccDataSourceEssScalingGroups-%d", rand), + "groups.0.region_id": CHECKSET, + "groups.0.min_size": "0", + "groups.0.desired_capacity": "1", + "groups.0.max_size": "2", + "groups.0.cooldown_time": "20", + "groups.0.stop_instance_timeout": "30", + "groups.0.max_instance_lifetime": "86400", + "groups.0.az_balance": "true", + "groups.0.removal_policies.#": "2", + "groups.0.removal_policies.0": "OldestInstance", + "groups.0.removal_policies.1": "NewestInstance", + "groups.0.load_balancer_ids.#": "0", + "groups.0.db_instance_ids.#": "0", + "groups.0.vswitch_ids.#": "1", + "groups.0.monitor_group_id": CHECKSET, + "groups.0.enable_desired_capacity": CHECKSET, + "groups.0.system_suspended": CHECKSET, + "groups.0.resource_group_id": CHECKSET, + "groups.0.scaling_policy": "release", + "groups.0.group_type": CHECKSET, + "groups.0.total_capacity": CHECKSET, + "groups.0.init_capacity": CHECKSET, + "groups.0.pending_wait_capacity": CHECKSET, + "groups.0.removing_wait_capacity": CHECKSET, + "groups.0.protected_capacity": CHECKSET, + "groups.0.standby_capacity": CHECKSET, + "groups.0.spot_capacity": CHECKSET, + "groups.0.stopped_capacity": CHECKSET, + "groups.0.multi_az_policy": CHECKSET, + "groups.0.spot_instance_pools": "2", + "groups.0.on_demand_percentage_above_base_capacity": "100", + "groups.0.spot_allocation_strategy": "lowestPrice", + "groups.0.allocation_strategy": "lowestPrice", + "groups.0.on_demand_base_capacity": "1", + "groups.0.active_capacity": CHECKSET, + "groups.0.pending_capacity": CHECKSET, + "groups.0.removing_capacity": CHECKSET, + "groups.0.creation_time": CHECKSET, + "groups.0.vpc_id": CHECKSET, + "groups.0.vswitch_id": CHECKSET, + "groups.0.health_check_type": CHECKSET, + "groups.0.suspended_processes.#": "0", + "groups.0.group_deletion_protection": CHECKSET, + "groups.0.spot_instance_remedy": CHECKSET, + "groups.0.modification_time": CHECKSET, + "groups.0.total_instance_count": CHECKSET, + "groups.0.lifecycle_state": CHECKSET, + "groups.0.tags.key": "value", + } + } + + var fakeEssScalingGroupsMapFunc = func(rand int) map[string]string { + return map[string]string{ + "groups.#": "0", + "ids.#": "0", + "names.#": "0", + } + } + + var essScalingGroupsCheckInfo = dataSourceAttr{ + resourceId: "data.alicloud_ess_scaling_groups.default", + existMapFunc: existEssScalingGroupsMapFunc, + fakeMapFunc: fakeEssScalingGroupsMapFunc, + } + + essScalingGroupsCheckInfo.dataSourceTestCheck(t, rand, nameRegexConf, idsConf, allConf) +} + +func testAccCheckAliCloudEssScalinggroupsDataSourceConfigSupply(rand int, attrMap map[string]string) string { + var pairs []string + for k, v := range attrMap { + pairs = append(pairs, k+" = "+v) + } + + config := fmt.Sprintf(` +%s + +variable "name" { + default = "tf-testAccDataSourceEssScalingGroups-%d" +} + +resource "alicloud_ess_scaling_group" "default" { + min_size = 0 + max_size = 2 + desired_capacity = 1 + scaling_group_name = "${var.name}" + default_cooldown = 20 + multi_az_policy = "COMPOSABLE" + on_demand_percentage_above_base_capacity = "100" + on_demand_base_capacity = 1 + removal_policies = ["OldestInstance", "NewestInstance"] + vswitch_ids = ["${alicloud_vswitch.default.id}"] + stop_instance_timeout = 30 + tags = {"key": "value"} + max_instance_lifetime = 86400 + spot_allocation_strategy = "lowestPrice" + allocation_strategy = "lowestPrice" + az_balance = "true" + scaling_policy = "release" +} + + +data "alicloud_ess_scaling_groups" "default" { + %s +} +`, EcsInstanceCommonTestCase, rand, strings.Join(pairs, "\n ")) + return config +} + +func testAccCheckAliCloudEssScalinggroupsDataSourceConfig(rand int, attrMap map[string]string) string { + var pairs []string + for k, v := range attrMap { + pairs = append(pairs, k+" = "+v) + } + + config := fmt.Sprintf(` +%s + +variable "name" { + default = "tf-testAccDataSourceEssScalingGroups-%d" +} + +resource "alicloud_ess_scaling_group" "default" { + min_size = 0 + max_size = 2 + desired_capacity = 1 + scaling_group_name = "${var.name}" + default_cooldown = 20 + removal_policies = ["OldestInstance", "NewestInstance"] + vswitch_ids = ["${alicloud_vswitch.default.id}"] + stop_instance_timeout = 30 + tags = {"key": "value"} + max_instance_lifetime = 86400 + scaling_policy = "release" +} + +data "alicloud_ess_scaling_groups" "default" { + %s +} +`, EcsInstanceCommonTestCase, rand, strings.Join(pairs, "\n ")) + return config +} diff --git a/alicloud/data_source_alicloud_ess_scalinggroups.go b/alicloud/data_source_alicloud_ess_scalinggroups.go deleted file mode 100644 index 65bbcaaacb66..000000000000 --- a/alicloud/data_source_alicloud_ess_scalinggroups.go +++ /dev/null @@ -1,298 +0,0 @@ -package alicloud - -import ( - "regexp" - - "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" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" -) - -func dataSourceAlicloudEssScalingGroups() *schema.Resource { - return &schema.Resource{ - Read: dataSourceAlicloudEssScalingGroupsRead, - Schema: map[string]*schema.Schema{ - "name_regex": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.ValidateRegexp, - ForceNew: true, - }, - "ids": { - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Computed: true, - ForceNew: true, - }, - "output_file": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - }, - "names": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "groups": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "active_scaling_configuration": { - Type: schema.TypeString, - Computed: true, - }, - "launch_template_id": { - Type: schema.TypeString, - Computed: true, - }, - "launch_template_version": { - Type: schema.TypeString, - Computed: true, - }, - "region_id": { - Type: schema.TypeString, - Computed: true, - }, - "min_size": { - Type: schema.TypeInt, - Computed: true, - }, - "max_size": { - Type: schema.TypeInt, - Computed: true, - }, - "cooldown_time": { - Type: schema.TypeInt, - Computed: true, - }, - "removal_policies": { - Type: schema.TypeList, - Elem: &schema.Schema{Type: schema.TypeString}, - Computed: true, - }, - "load_balancer_ids": { - Type: schema.TypeList, - Elem: &schema.Schema{Type: schema.TypeString}, - Computed: true, - }, - "db_instance_ids": { - Type: schema.TypeList, - Elem: &schema.Schema{Type: schema.TypeString}, - Computed: true, - }, - "vswitch_ids": { - Type: schema.TypeList, - Elem: &schema.Schema{Type: schema.TypeString}, - Computed: true, - }, - "lifecycle_state": { - Type: schema.TypeString, - Computed: true, - }, - "vpc_id": { - Type: schema.TypeString, - Computed: true, - }, - "vswitch_id": { - Type: schema.TypeString, - Computed: true, - }, - "health_check_type": { - Type: schema.TypeString, - Computed: true, - }, - "suspended_processes": { - Type: schema.TypeList, - Elem: &schema.Schema{Type: schema.TypeString}, - Computed: true, - }, - "group_deletion_protection": { - Type: schema.TypeBool, - Computed: true, - }, - "modification_time": { - Type: schema.TypeString, - Computed: true, - }, - "total_capacity": { - Type: schema.TypeInt, - Computed: true, - }, - "total_instance_count": { - Type: schema.TypeInt, - Computed: true, - }, - "active_capacity": { - Type: schema.TypeInt, - Computed: true, - }, - "pending_capacity": { - Type: schema.TypeInt, - Computed: true, - }, - "removing_capacity": { - Type: schema.TypeInt, - Computed: true, - }, - "creation_time": { - Type: schema.TypeString, - Computed: true, - }, - "tags": tagsSchema(), - }, - }, - }, - }, - } -} - -func dataSourceAlicloudEssScalingGroupsRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*connectivity.AliyunClient) - request := ess.CreateDescribeScalingGroupsRequest() - request.RegionId = client.RegionId - request.PageSize = requests.NewInteger(PageSizeLarge) - request.PageNumber = requests.NewInteger(1) - - var allScalingGroups []ess.ScalingGroup - - for { - raw, err := client.WithEssClient(func(essClient *ess.Client) (interface{}, error) { - return essClient.DescribeScalingGroups(request) - }) - if err != nil { - return WrapErrorf(err, DataDefaultErrorMsg, "alicloud_ess_scalinggroups", request.GetActionName(), AlibabaCloudSdkGoERROR) - } - addDebug(request.GetActionName(), raw, request.RpcRequest, request) - response, _ := raw.(*ess.DescribeScalingGroupsResponse) - if len(response.ScalingGroups.ScalingGroup) < 1 { - break - } - - allScalingGroups = append(allScalingGroups, response.ScalingGroups.ScalingGroup...) - - if len(response.ScalingGroups.ScalingGroup) < PageSizeLarge { - break - } - - if page, err := getNextpageNumber(request.PageNumber); err != nil { - return WrapError(err) - } else { - request.PageNumber = page - } - } - - var filteredScalingGroupsTemp = make([]ess.ScalingGroup, 0) - - nameRegex, okNameRegex := d.GetOk("name_regex") - idsMap := make(map[string]string) - ids, okIds := d.GetOk("ids") - if okIds { - for _, i := range ids.([]interface{}) { - if i == nil { - continue - } - idsMap[i.(string)] = i.(string) - } - } - if okNameRegex || okIds { - for _, group := range allScalingGroups { - if okNameRegex && nameRegex != "" { - r, err := regexp.Compile(nameRegex.(string)) - if err != nil { - return WrapError(err) - } - if r != nil && !r.MatchString(group.ScalingGroupName) { - continue - } - } - if okIds && len(idsMap) > 0 { - if _, ok := idsMap[group.ScalingGroupId]; !ok { - continue - } - } - filteredScalingGroupsTemp = append(filteredScalingGroupsTemp, group) - } - } else { - filteredScalingGroupsTemp = allScalingGroups - } - return scalingGroupsDescriptionAttribute(d, filteredScalingGroupsTemp, meta, client) -} - -func scalingGroupsDescriptionAttribute(d *schema.ResourceData, scalingGroups []ess.ScalingGroup, meta interface{}, client *connectivity.AliyunClient) error { - var ids []string - var names []string - var s = make([]map[string]interface{}, 0) - essService := EssService{client} - - for _, scalingGroup := range scalingGroups { - mapping := map[string]interface{}{ - "id": scalingGroup.ScalingGroupId, - "name": scalingGroup.ScalingGroupName, - "active_scaling_configuration": scalingGroup.ActiveScalingConfigurationId, - "launch_template_id": scalingGroup.LaunchTemplateId, - "launch_template_version": scalingGroup.LaunchTemplateVersion, - "region_id": scalingGroup.RegionId, - "min_size": scalingGroup.MinSize, - "max_size": scalingGroup.MaxSize, - "cooldown_time": scalingGroup.DefaultCooldown, - "removal_policies": scalingGroup.RemovalPolicies.RemovalPolicy, - "load_balancer_ids": scalingGroup.LoadBalancerIds.LoadBalancerId, - "db_instance_ids": scalingGroup.DBInstanceIds.DBInstanceId, - "vswitch_ids": scalingGroup.VSwitchIds.VSwitchId, - "lifecycle_state": scalingGroup.LifecycleState, - "total_capacity": scalingGroup.TotalCapacity, - "active_capacity": scalingGroup.ActiveCapacity, - "pending_capacity": scalingGroup.PendingCapacity, - "removing_capacity": scalingGroup.RemovingCapacity, - "total_instance_count": scalingGroup.TotalInstanceCount, - "vpc_id": scalingGroup.VpcId, - "vswitch_id": scalingGroup.VSwitchId, - "health_check_type": scalingGroup.HealthCheckType, - "suspended_processes": scalingGroup.SuspendedProcesses.SuspendedProcess, - "group_deletion_protection": scalingGroup.GroupDeletionProtection, - "modification_time": scalingGroup.ModificationTime, - "creation_time": scalingGroup.CreationTime, - } - - listTagResourcesObject, err := essService.ListTagResources(d.Id(), client) - if err != nil { - return WrapError(err) - } - mapping["tags"] = tagsToMap(listTagResourcesObject) - - ids = append(ids, scalingGroup.ScalingGroupId) - names = append(names, scalingGroup.ScalingGroupName) - s = append(s, mapping) - } - - d.SetId(dataResourceIdHash(ids)) - if err := d.Set("groups", s); err != nil { - return WrapError(err) - } - - if err := d.Set("ids", ids); err != nil { - return WrapError(err) - } - - if err := d.Set("names", names); err != nil { - return WrapError(err) - } - - if output, ok := d.GetOk("output_file"); ok && output.(string) != "" { - writeToFile(output.(string), s) - } - return nil -} diff --git a/alicloud/data_source_alicloud_ess_scalinggroups_test.go b/alicloud/data_source_alicloud_ess_scalinggroups_test.go deleted file mode 100644 index 9aa59850abec..000000000000 --- a/alicloud/data_source_alicloud_ess_scalinggroups_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package alicloud - -import ( - "fmt" - "strings" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" -) - -func TestAccAlicloudEssScalingGroupsDataSource(t *testing.T) { - rand := acctest.RandInt() - nameRegexConf := dataSourceTestAccConfig{ - existConfig: testAccCheckAlicloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ - "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}"`, - }), - fakeConfig: testAccCheckAlicloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ - "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}_fake"`, - }), - } - - idsConf := dataSourceTestAccConfig{ - existConfig: testAccCheckAlicloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ - "ids": `["${alicloud_ess_scaling_group.default.id}"]`, - }), - fakeConfig: testAccCheckAlicloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ - "ids": `["${alicloud_ess_scaling_group.default.id}_fake"]`, - }), - } - - allConf := dataSourceTestAccConfig{ - existConfig: testAccCheckAlicloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ - "ids": `["${alicloud_ess_scaling_group.default.id}"]`, - "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}"`, - }), - fakeConfig: testAccCheckAlicloudEssScalinggroupsDataSourceConfig(rand, map[string]string{ - "ids": `["${alicloud_ess_scaling_group.default.id}_fake"]`, - "name_regex": `"${alicloud_ess_scaling_group.default.scaling_group_name}"`, - }), - } - - var existEssScalingGroupsMapFunc = func(rand int) map[string]string { - return map[string]string{ - "groups.#": "1", - "ids.#": "1", - "names.#": "1", - "groups.0.id": CHECKSET, - "groups.0.name": fmt.Sprintf("tf-testAccDataSourceEssScalingGroups-%d", rand), - "groups.0.region_id": CHECKSET, - "groups.0.min_size": "0", - "groups.0.max_size": "2", - "groups.0.cooldown_time": "20", - "groups.0.removal_policies.#": "2", - "groups.0.removal_policies.0": "OldestInstance", - "groups.0.removal_policies.1": "NewestInstance", - "groups.0.load_balancer_ids.#": "0", - "groups.0.db_instance_ids.#": "0", - "groups.0.vswitch_ids.#": "1", - "groups.0.total_capacity": CHECKSET, - "groups.0.active_capacity": CHECKSET, - "groups.0.pending_capacity": CHECKSET, - "groups.0.removing_capacity": CHECKSET, - "groups.0.creation_time": CHECKSET, - "groups.0.vpc_id": CHECKSET, - "groups.0.vswitch_id": CHECKSET, - "groups.0.health_check_type": CHECKSET, - "groups.0.suspended_processes.#": "0", - "groups.0.group_deletion_protection": CHECKSET, - "groups.0.modification_time": CHECKSET, - "groups.0.total_instance_count": CHECKSET, - "groups.0.lifecycle_state": CHECKSET, - "groups.0.tags.key": "value", - } - } - - var fakeEssScalingGroupsMapFunc = func(rand int) map[string]string { - return map[string]string{ - "groups.#": "0", - "ids.#": "0", - "names.#": "0", - } - } - - var essScalingGroupsCheckInfo = dataSourceAttr{ - resourceId: "data.alicloud_ess_scaling_groups.default", - existMapFunc: existEssScalingGroupsMapFunc, - fakeMapFunc: fakeEssScalingGroupsMapFunc, - } - - essScalingGroupsCheckInfo.dataSourceTestCheck(t, rand, nameRegexConf, idsConf, allConf) -} - -func testAccCheckAlicloudEssScalinggroupsDataSourceConfig(rand int, attrMap map[string]string) string { - var pairs []string - for k, v := range attrMap { - pairs = append(pairs, k+" = "+v) - } - - config := fmt.Sprintf(` -%s - -variable "name" { - default = "tf-testAccDataSourceEssScalingGroups-%d" -} - -resource "alicloud_ess_scaling_group" "default" { - min_size = 0 - max_size = 2 - scaling_group_name = "${var.name}" - default_cooldown = 20 - removal_policies = ["OldestInstance", "NewestInstance"] - vswitch_ids = ["${alicloud_vswitch.default.id}"] - tags = {"key": "value"} -} - -data "alicloud_ess_scaling_groups" "default" { - %s -} -`, EcsInstanceCommonTestCase, rand, strings.Join(pairs, "\n ")) - return config -} diff --git a/website/docs/d/ess_scaling_groups.html.markdown b/website/docs/d/ess_scaling_groups.html.markdown index e7b88f8823c9..f2569099fc4d 100644 --- a/website/docs/d/ess_scaling_groups.html.markdown +++ b/website/docs/d/ess_scaling_groups.html.markdown @@ -11,12 +11,52 @@ description: |- This data source provides available scaling group resources. +-> **NOTE:** Available since v1.241.0 + ## Example Usage -``` +```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" +} + +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_ess_scaling_group" "default" { + min_size = 1 + max_size = 1 + scaling_group_name = local.name + removal_policies = ["OldestInstance", "NewestInstance"] + vswitch_ids = [alicloud_vswitch.default.id] +} + data "alicloud_ess_scaling_groups" "scalinggroups_ds" { - ids = ["scaling_group_id1", "scaling_group_id2"] - name_regex = "scaling_group_name" + ids = [alicloud_ess_scaling_group.default.id] + name_regex = local.name } output "first_scaling_group" { @@ -28,9 +68,9 @@ output "first_scaling_group" { The following arguments are supported: -* `name_regex` - (Optional) A regex string to filter resulting scaling groups by name. -* `ids` - (Optional) A list of scaling group IDs. -* `output_file` - (Optional) File name where to save data source results (after running `terraform plan`). +* `name_regex` - (Optional, ForceNew) A regex string to filter resulting scaling groups by name. +* `ids` - (Optional, ForceNew) A list of scaling group IDs. +* `output_file` - (Optional, ForceNew) File name where to save data source results (after running `terraform plan`). ## Attributes Reference @@ -62,9 +102,41 @@ The following attributes are exported in addition to the arguments listed above: * `total_capacity` - Number of instances in scaling group. * `total_instance_count` - The number of all ECS instances in the scaling group. * `active_capacity` - Number of active instances in scaling group. + * `init_capacity` - The number of instances that are in the Initialized state and ready to be scaled out in the scaling group. + * `pending_wait_capacity` - The number of ECS instances that are in the Pending Add state in the scaling group. + * `removing_wait_capacity` - The number of ECS instances that are in the Pending Remove state in the scaling group. + * `protected_capacity` - The number of ECS instances that are in the Protected state in the scaling group. + * `standby_capacity` - The number of instances that are in the Standby state in the scaling group. + * `spot_capacity` - The number of instances that are in Economical Mode in the scaling group. + * `stopped_capacity` - Number of active instances in scaling group. * `pending_capacity` - Number of pending instances in scaling group. * `removing_capacity` - Number of removing instances in scaling group. + * `system_suspended` - Indicates whether Auto Scaling stops executing the scaling operation in the scaling group. + * `monitor_group_id` - The ID of the CloudMonitor application group that is associated with the scaling group. + * `enable_desired_capacity` - Indicates whether the Expected Number of Instances feature is enabled. * `creation_time` - Creation time of scaling group. * `tags` - A mapping of tags to assign to the resource. + * `stop_instance_timeout` - The period of time required by the ECS instance to enter the Stopped state. + * `desired_capacity` - Expected number of ECS instances in the scaling group. + * `max_instance_lifetime` - The maximum life span of an instance in the scaling group. Unit: seconds. + * `multi_az_policy` - Multi-AZ scaling group ECS instance expansion and contraction strategy. + * `group_type` - Resource type within scaling group. + * `resource_group_id` - The ID of the resource group to which you want to add the scaling group. + * `spot_instance_remedy` - Whether to replace spot instances with newly created spot/onDemand instance when receive a spot recycling message. + * `spot_instance_pools` - The number of Spot pools to use to allocate your Spot capacity. The Spot pools is composed of instance types of lowest price. + * `on_demand_percentage_above_base_capacity` - Controls the percentages of On-Demand Instances and Spot Instances for your additional capacity beyond OnDemandBaseCapacity. + * `on_demand_base_capacity` - The minimum amount of the Auto Scaling group's capacity that must be fulfilled by On-Demand Instances. This base portion is provisioned first as your group scales. + * `spot_allocation_strategy` - The allocation policy of preemptible instances. You can use this parameter to individually specify the allocation policy for preemptible instances. This parameter takes effect only if you set MultiAZPolicy to COMPOSABLE. + * `allocation_strategy` - The allocation policy of instances. Auto Scaling selects instance types based on the allocation policy to create instances. The policy can be applied to pay-as-you-go instances and preemptible instances. This parameter takes effect only if you set MultiAZPolicy to COMPOSABLE. + * `az_balance` - Specifies whether to evenly distribute instances in the scaling group across multiple zones. This parameter takes effect only if you set MultiAZPolicy to COMPOSABLE. + * `scaling_policy` - The reclaim mode of the scaling group. + + + + + + + +