All Products
Search
Document Center

Auto Scaling:Use Terraform to create Auto Scaling resources

Last Updated:Dec 27, 2024

This topic describes how to use a Terraform template to create scaling groups, scaling configurations, scaling rules and other Auto Scaling resources the first time you use Auto Scaling.

Note

You can run the sample code in this topic with one click. For more information about the sample code, see Code.

Before you begin

  • An Alibaba Cloud account has all permissions on resources within the account. If an Alibaba Cloud account is leaked, the resources are exposed to major risks. We recommend that you use a Resource Access Management (RAM) user and create an AccessKey pair for the RAM user. For more information, see Create a RAM user and Create an AccessKey pair.

  • You can use RAM to manage access permissions on cloud resources in an efficient manner. This helps meet the requirements for multi-user collaboration and allows you to grant permissions to users based on the principle of least privilege (PoLP) to prevent security vulnerabilities caused by excessive permissions. For more information, see Grant permissions to a RAM user.

    {
        "Version": "1",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "ecs:CreateSecurityGroup",
                    "ecs:ModifySecurityGroupPolicy",
                    "ecs:DescribeSecurityGroups",
                    "ecs:ListTagResources",
                    "ecs:DeleteSecurityGroup",
                    "ecs:DescribeSecurityGroupAttribute",
                    "ecs:AuthorizeSecurityGroup",
                    "ecs:RevokeSecurityGroup"
                ],
                "Resource": "*"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "vpc:DescribeVpcAttribute",
                    "vpc:DescribeRouteTableList",
                    "vpc:DescribeVSwitchAttributes",
                    "vpc:DeleteVpc",
                    "vpc:DeleteVSwitch",
                    "vpc:CreateVpc",
                    "vpc:CreateVSwitch"
                ],
                "Resource": "*"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "ess:CreateScalingGroup",
                    "ess:DescribeScalingGroups",
                    "ess:ListTagResources",
                    "ess:DeleteScalingGroup",
                    "ess:ModifyScalingGroup",
                    "ess:CreateScalingConfiguration",
                    "ess:DescribeScalingConfigurations",
                    "ess:ModifyScalingConfiguration",
                    "ess:CreateScalingRule",
                    "ess:DescribeScalingRules",
                    "ess:DeleteScalingRule"
                ],
                "Resource": "*"
            }
        ]
    }
  • Prepare the Terraform environment. You can use one of the following methods to use Terraform:

    • Use Terraform in Terraform Explorer: Alibaba Cloud provides Terraform Explorer, an online runtime environment for Terraform. You can use Terraform after you log on to Terraform Explorer without the need to install Terraform. This method is suitable for scenarios in which you want to use and debug Terraform in a fast and convenient manner at no additional cost.

    • Use Terraform in Cloud Shell: Terraform is preinstalled in Cloud Shell and identity credentials are configured. You can directly run Terraform commands in Cloud Shell. This method is suitable for scenarios in which you want to use and debug Terraform in a fast and convenient manner at low cost.

    • Install and configure Terraform in an on-premises environment: This method is suitable for scenarios in which network conditions are poor or a custom development environment is used.

Required resources

Use Terraform to create Auto Scaling resources

In this example, Terraform is used to create Auto Scaling resources such as scaling groups, scaling configurations, and scaling rules.

  1. Create a working directory and a configuration file named main.tf in the directory. Copy the following code to the main.tf configuration file:

    variable "region" {
      default = "cn-heyuan"
    }
    
    variable "instance_type" {
      default = "ecs.hfc7.xlarge"
    }
    
    variable "image_id" {
      default = "aliyun_2_1903_x64_20G_alibase_20210120.vhd"
    }
    
    variable "zone_id" {
      default = "cn-heyuan-b"
    }
    
    provider "alicloud" {
      region = var.region
    }
    
    # Create a VPC. 
    resource "alicloud_vpc" "vpc" {
      vpc_name   = "tf-test-vpc-wjt"
      cidr_block = "172.16.0.0/12" # Plan a private CIDR block for the VPC. 
    }
    
    # Create a vSwitch in the VPC. 
    resource "alicloud_vswitch" "vsw" {
      vpc_id       = alicloud_vpc.vpc.id
      cidr_block = "172.16.0.0/21" # Plan a private CIDR block for the vSwitch. 
      zone_id=var.zone_id# Select a zone for the vSwitch. 
      vswitch_name = "tf-test-vswitch-wjt"
    }
    
    # Create a security group. 
    resource "alicloud_security_group" "security" {
      name        = "tf_test_security"
      description = "New security group"
      vpc_id      = alicloud_vpc.vpc.id
    }
    
    # Add a security group rule that allows access from all addresses to the security group. 
    resource "alicloud_security_group_rule" "allow_all_tcp" {
      type              = "ingress"
      ip_protocol       = "tcp"
      nic_type          = "intranet"
      policy            = "accept"
      port_range        = "1/65535"
      priority          = 1
      security_group_id = alicloud_security_group.security.id
      cidr_ip           = "0.0.0.0/0"
    }
    
    # In this example, a scaling group that can contain up to 100 instances is created. 
    resource "alicloud_ess_scaling_group" "group" {
      scaling_group_name = "tf_test_scalinggroup"
      min_size           = 0
      max_size           = 100
      vswitch_ids        = [alicloud_vswitch.vsw.id]
    }
    
    # In this example, a scaling configuration of the Elastic Compute Service (ECS) type is created. 
    resource "alicloud_ess_scaling_configuration" "configuration" {
      scaling_group_id           = alicloud_ess_scaling_group.group.id
      instance_type              = var.instance_type
      image_id                   = var.image_id
      security_group_id          = alicloud_security_group.security.id
      scaling_configuration_name = "tf_test_scalingconfiguration"
      system_disk_category       = "cloud_essd"
      spot_strategy              = "SpotWithPriceLimit"
      active                     = true
      force_delete               = true
    }
    
    # Create a scaling rule.
    resource "alicloud_ess_scaling_rule" "rule" {
      scaling_group_id = alicloud_ess_scaling_group.group.id
      adjustment_type  = "QuantityChangeInCapacity"
      adjustment_value = 1
    }
  2. Run the following command to initialize the runtime environment for Terraform:

    terraform init

    If the following information is returned, Terraform is initialized.

    Initializing the backend...
    
    Initializing provider plugins...
    - Checking for available provider plugins...
    - Downloading plugin for provider "alicloud" (hashicorp/alicloud) 1.90.1...
    ...
    
    You may now begin working with Terraform. Try running "terraform plan" to see
    any changes that are required for your infrastructure. All Terraform commands
    should now work.
    
    If you ever set or change modules or backend configuration for Terraform,
    rerun this command to reinitialize your working directory. If you forget, other
    commands will detect it and remind you to do so if necessary.
  3. Create an execution plan and preview the changes.

    terraform plan
  4. Run the following command to create resources:

    terraform apply

    During command execution, enter yes as prompted and press the Enter key. Wait until the command is run. If the following information is returned, the Auto Scaling resources are created.

    Do you want to perform these actions?
      Terraform will perform the actions described above.
      Only 'yes' will be accepted to approve.
    
      Enter a value: yes
    
    ...
    alicloud_security_group_rule.allow_all_tcp: Creation complete after 0s [id=sg-f8z1mes******:ingress:tcp:1/65535:intranet:0.0.0.0/0:accept:1]
    alicloud_vswitch.vsw: Creation complete after 3s [id=vsw-f8ztgc4******]
    alicloud_ess_scaling_group.group: Creating...
    alicloud_ess_scaling_group.group: Creation complete after 2s [id=asg-f8z9mo******]
    ...
    
    Apply complete!  Resources: 7 added, 0 changed, 0 destroyed.
  5. Verify the result

    Run the terraform show command

    Run the following command to query the details of the resources that are created by using Terraform:

    terraform show

    image

    Log on to the Auto Scaling console

    You can log on to the Auto Scaling console to view the created scaling group.

    image

Clear resources

If you no longer require the preceding resources that are created or managed by using Terraform, run the following command to release the resources. For more information about terraform destroy, see Common commands.

terraform destroy

Complete sample code

Note

You can run the sample code with one click. Click here to run the sample code.

Sample code

variable "region" {
  default = "cn-heyuan"
}

variable "instance_type" {
  default = "ecs.hfc7.xlarge"
}

variable "image_id" {
  default = "aliyun_2_1903_x64_20G_alibase_20210120.vhd"
}

variable "zone_id" {
  default = "cn-heyuan-b"
}

provider "alicloud" {
  region = var.region
}

# Create a VPC. 
resource "alicloud_vpc" "vpc" {
  vpc_name   = "tf-test-vpc-wjt"
  cidr_block = "172.16.0.0/12" # Plan a private CIDR block for the VPC. 
}

# Create a vSwitch in the VPC. 
resource "alicloud_vswitch" "vsw" {
  vpc_id       = alicloud_vpc.vpc.id
  cidr_block = "172.16.0.0/21" # Plan a private CIDR block for the vSwitch. 
  zone_id=var.zone_id# Select a zone for the vSwitch. 
  vswitch_name = "tf-test-vswitch-wjt"
}

# Create a security group. 
resource "alicloud_security_group" "security" {
  name        = "tf_test_security"
  description = "New security group"
  vpc_id      = alicloud_vpc.vpc.id
}

# Add a security group rule that allows access from all addresses to the security group. 
resource "alicloud_security_group_rule" "allow_all_tcp" {
  type              = "ingress"
  ip_protocol       = "tcp"
  nic_type          = "intranet"
  policy            = "accept"
  port_range        = "1/65535"
  priority          = 1
  security_group_id = alicloud_security_group.security.id
  cidr_ip           = "0.0.0.0/0"
}

# In this example, a scaling group that can contain up to 100 instances is created. 
resource "alicloud_ess_scaling_group" "group" {
  scaling_group_name = "tf_test_scalinggroup"
  min_size           = 0
  max_size           = 100
  vswitch_ids        = [alicloud_vswitch.vsw.id]
}

# In this example, a scaling configuration of the ECS type is created. 
resource "alicloud_ess_scaling_configuration" "configuration" {
  scaling_group_id           = alicloud_ess_scaling_group.group.id
  instance_type              = var.instance_type
  image_id                   = var.image_id
  security_group_id          = alicloud_security_group.security.id
  scaling_configuration_name = "tf_test_scalingconfiguration"
  system_disk_category       = "cloud_essd"
  spot_strategy              = "SpotWithPriceLimit"
  active                     = true
  force_delete               = true
}

# Create a scaling rule.
resource "alicloud_ess_scaling_rule" "rule" {
  scaling_group_id = alicloud_ess_scaling_group.group.id
  adjustment_type  = "QuantityChangeInCapacity"
  adjustment_value = 1
}