All Products
Search
Document Center

Elastic Compute Service:Create and use an ECS instance with Terraform

Last Updated:Jun 21, 2026

Terraform is an IaC (Infrastructure as Code) tool for automating infrastructure management. It allows you to define and provision cloud infrastructure using simple code. This topic shows you how to use Terraform to create an ECS instance.

Note

For more information about Terraform, see What is Alibaba Cloud Terraform?.

Prerequisites

1. Install Terraform

This topic shows how to install Terraform from a package on a Linux or Windows operating system.

Note

Alibaba Cloud offers two online environments where you can run Terraform commands without a local installation:

  1. Terraform Explorer: Click Initiate Debugging to run the sample code in this topic.

  2. Cloud Shell: Copy the code provided in this topic and run Terraform commands directly in Create resources with Terraform.

  1. Go to the official Terraform website to download the package for your operating system.

  2. Configure the Terraform runtime environment.

    Linux

    Run the following command to extract the package to /usr/local/bin.

    # Replace {your_zip_path} with the path to your package. If your system does not support the unzip command, install it first.
    sudo unzip {your_zip_path} -d /usr/local/bin

    Windows

    1. Extract the package. For example, the destination directory is D:\tool\terraform.

    2. On the desktop, right-click This PC and select Type > Advanced system settings > Environment Variable > System variables/User variables.

    3. Click Path in System variables or User variables, select Edit > New, enter the directory where you unzipped Terraform (such as D:\tool\terraform), and click OK to complete the configuration.

  3. Run the terraform command to verify the path configuration.

    terraform

    If the command displays a list of Terraform options, the installation is successful.

    ➜  ~ terraform
    Usage: terraform [global options] <subcommand> [args]
    The available commands for execution are listed below.
    The primary workflow commands are given first, followed by
    less common or more advanced commands.
    Main commands:
      init          Prepare your working directory for other commands
      validate      Check whether the configuration is valid
      plan          Show changes required by the current configuration
      apply         Create or update infrastructure
      destroy       Destroy previously-created infrastructure
    All other commands:
      console       Try Terraform expressions at an interactive command prompt
      fmt           Reformat your configuration in the standard style
      force-unlock  Release a stuck lock on the current workspace
      get           Install or upgrade remote Terraform modules
      graph         Generate a Graphviz graph of the steps in an operation
      import        Associate existing infrastructure with a Terraform resource
      login         Obtain and save credentials for a remote host
      logout        Remove locally-stored credentials for a remote host
      metadata      Metadata related commands
      output        Show output values from your root module
      providers     Show the providers required for this configuration
      refresh       Update the state to match remote systems
      show          Inspect Terraform state or plan
      state         Advanced state management
      taint         Mark a resource instance as not fully functional
      test          Execute integration tests for Terraform modules
      untaint       Remove the 'tainted' state from a resource instance
      version       Show the current Terraform version
      workspace     Workspace management
    
    Global options (use these before the subcommand, if any):
      -chdir=DIR    Switch to a different working directory before executing the
                    given subcommand.
      -help         Show this message, or the help for a given subcommand.
      -version      An alias for the "version" subcommand.
      show          Show the current state or a saved plan
      state         Advanced state management
      taint         Mark a resource instance as not fully functional
      test          Experimental support for module integration testing
      untaint       Remove the 'tainted' state from a resource instance
      version       Show the current Terraform version
      workspace     Workspace management
    Global options (use these before the subcommand, if any):
      -chdir=DIR    Switch to a different working directory before executing the
                    given subcommand.
      -help         Show this help output, or the help for a specified subcommand.
      -version      An alias for the "version" subcommand.

2. Configure Terraform authentication

Before using Terraform to manage Alibaba Cloud resources, you must configure authentication for the Alibaba Cloud provider. This allows Terraform to call the necessary APIs to create and manage your infrastructure.

Note

If you use Terraform Explorer or Cloud Shell, you do not need to configure authentication manually. Just ensure that your logged-in account has permissions to manage VPC and ECS resources.

This topic uses a RAM user's AccessKey, stored as an environment variable, for authentication:

  1. Because an Alibaba Cloud account has full permissions over its resources, a leaked AccessKey poses a high security risk. We recommend using a RAM user AccessKey instead. For more information about how to create a RAM user AccessKey, see Create an AccessKey pair.

  2. When you grant a RAM user permissions to manage ECS and VPC resources, we recommend that you follow the principle of least privilege. For more information about how to grant permissions to a RAM user, see Manage RAM user permissions. The sample code in this topic requires you to create resources such as ECS, VPCs, and vSwitches. To run the examples, you can grant the following permissions to the RAM user:

    Service

    Policy

    VPC

    In this example, select the system policy AliyunVPCFullAccess.

    ECS

    In this example, select the system policy AliyunECSFullAccess.

  3. Create environment variables to store your authentication credentials.

    Linux

    Important

    Environment variables set with the export command are temporary and last only for the current session. To make them permanent, add the command to your shell's startup file.

    # Your AccessKey ID.
    export ALICLOUD_ACCESS_KEY="yourAccessKeyID"
    # Your AccessKey secret.
    export ALICLOUD_SECRET_KEY="yourAccessKeySecret"
    # The region where the resources will be deployed.
    export ALICLOUD_REGION="cn-chengdu"

    Windows

    1. On the desktop, right-click This PC and select Type > Advanced system settings > Environment Variable > System variables/User variables.

    2. In the System variables or User variables section, click New to create the following environment variables.

      Variable

      Description

      Value

      ALICLOUD_ACCESS_KEY

      Your AccessKey ID.

      yourAccessKeyID

      ALICLOUD_SECRET_KEY

      Your AccessKey secret.

      yourAccessKeySecret

      ALICLOUD_REGION

      The region where the resources will be deployed.

      Example: cn-chengdu

Related Terraform resources

The sample code in this topic uses the following Terraform resources.

Note

Some resources used in this tutorial incur fees. To avoid unexpected charges, clean up the resources when they are no longer needed.

Resource

Data source

alicloud_zones: Finds available zones for a specified instance type.

Create a Terraform configuration file

Define the infrastructure resources required to create an ECS instance, such as the ECS instance and a VPC, in a main.tf file. You can copy the code from the Complete sample code section into your configuration file.

  1. Create a configuration file.

    This file, which should end with a .tf extension, contains all your resource definitions.

    Linux

    # Create a working directory.
    mkdir terraform-projects && cd terraform-projects
    mkdir ecs-quickstart && cd ecs-quickstart
    # Create and edit the configuration file.
    touch main.tf && vim main.tf

    Windows

    Create a new folder named ecs-quickstart. In the folder, create a Terraform configuration file named main.tf.

  2. Define the provider configuration.

    Configure the region for your Alibaba Cloud resource deployment.

    # The region where the resources are located.
    variable "region" {
      default = "cn-chengdu"
    }
    provider "alicloud" {
      region = var.region
    }
  3. Define the VPC and its vSwitch.

    A VPC is a logically isolated private network in the cloud that you can configure and manage.

    variable "instance_name" {
      default = "tf-sample"
    }
    # The instance type of the ECS instance.
    variable "instance_type" {
      default = "ecs.e-c1m2.large"
    }
    # Query for availability zones that meet the specified conditions.
    data "alicloud_zones" "default" {
      available_disk_category     = "cloud_essd"
      available_resource_creation = "VSwitch"
      available_instance_type     = var.instance_type
    }
    # Create a VPC.
    resource "alicloud_vpc" "vpc" {
      vpc_name   = var.instance_name
      cidr_block = "172.16.0.0/12"
    }
    # Create a vSwitch.
    resource "alicloud_vswitch" "vsw" {
      vpc_id     = alicloud_vpc.vpc.id
      cidr_block = "172.16.0.0/21"
      zone_id    = data.alicloud_zones.default.zones.0.id
    }
  4. Define the security group.

    A security group acts as a virtual firewall that controls inbound and outbound traffic for your ECS instance.

    # Create a security group.
    resource "alicloud_security_group" "default" {
      name   = var.instance_name
      vpc_id = alicloud_vpc.vpc.id
    }
    # Add an inbound rule to the security group.
    resource "alicloud_security_group_rule" "allow_tcp_22" {
      type              = "ingress"
      ip_protocol       = "tcp"
      nic_type          = "intranet"
      policy            = "accept"
      port_range        = "22/22"
      priority          = 1
      security_group_id = alicloud_security_group.default.id
      cidr_ip           = "0.0.0.0/0"
    }
  5. Define the ECS instance.

    ECS provides secure, scalable, and high-performance computing capacity for various scenarios, including application deployment, website hosting, and data processing.

    # The image ID of the ECS instance.
    variable "image_id" {
      default = "ubuntu_18_04_64_20G_alibase_20190624.vhd"
    }
    # The public bandwidth for the ECS instance.
    variable "internet_bandwidth" {
      default = "10"
    }
    # The logon password for the ECS instance.
    variable "password" {
      default = "Test@12345"
    }
    # The number of ECS instances to create. The default value is 1.
    variable "ecs_count" {
      default = 1
    }
    # Create the ECS instance.
    resource "alicloud_instance" "instance" {
      count                      = var.ecs_count
      availability_zone          = data.alicloud_zones.default.zones.0.id
      security_groups            = alicloud_security_group.default.*.id
      password                   = var.password
      instance_type              = var.instance_type
      system_disk_category       = "cloud_essd"
      image_id                   = var.image_id
      instance_name              = var.instance_name
      vswitch_id                 = alicloud_vswitch.vsw.id
      internet_max_bandwidth_out = var.internet_bandwidth
    }
    output "public_ip" {
      value = [for i in range(var.ecs_count) : alicloud_instance.instance[i].public_ip]
    }
                  

Complete sample code

Note

You can run the sample code with a single click. Initiate Debugging

variable "region" {
  default = "cn-chengdu"
}
provider "alicloud" {
  region = var.region
}
variable "instance_name" {
  default = "tf-sample"
}
variable "instance_type" {
  default = "ecs.e-c1m2.large"
}
data "alicloud_zones" "default" {
  available_disk_category     = "cloud_essd"
  available_resource_creation = "VSwitch"
  available_instance_type     = var.instance_type
}
resource "alicloud_vpc" "vpc" {
  vpc_name   = var.instance_name
  cidr_block = "172.16.0.0/12"
}
resource "alicloud_vswitch" "vsw" {
  vpc_id     = alicloud_vpc.vpc.id
  cidr_block = "172.16.0.0/21"
  zone_id    = data.alicloud_zones.default.zones.0.id
}
resource "alicloud_security_group" "default" {
  name   = var.instance_name
  vpc_id = alicloud_vpc.vpc.id
}
resource "alicloud_security_group_rule" "allow_tcp_22" {
  type              = "ingress"
  ip_protocol       = "tcp"
  nic_type          = "intranet"
  policy            = "accept"
  port_range        = "22/22"
  priority          = 1
  security_group_id = alicloud_security_group.default.id
  cidr_ip           = "0.0.0.0/0"
}
variable "image_id" {
  default = "ubuntu_18_04_64_20G_alibase_20190624.vhd"
}
variable "internet_bandwidth" {
  default = "10"
}
variable "password" {
  default = "Test@12345"
}
variable "ecs_count" {
  default = 1
}
resource "alicloud_instance" "instance" {
  count                      = var.ecs_count
  availability_zone          = data.alicloud_zones.default.zones.0.id
  security_groups            = alicloud_security_group.default.*.id
  password                   = var.password
  instance_type              = var.instance_type
  system_disk_category       = "cloud_essd"
  image_id                   = var.image_id
  instance_name              = var.instance_name
  vswitch_id                 = alicloud_vswitch.vsw.id
  internet_max_bandwidth_out = var.internet_bandwidth
}
output "public_ip" {
  value = [for i in range(var.ecs_count) : alicloud_instance.instance[i].public_ip]
}

Run Terraform commands

After creating the configuration file, run Terraform commands to create the ECS instance.

1. Initialize Terraform

The terraform init command downloads and installs the Alibaba Cloud provider plugin into the current folder and generates various record files.

Linux

terraform init

Windows

Open the Command Prompt (cmd), navigate to the directory that contains your Terraform configuration files, and then run the terraform init command to initialize.

# The configuration file is in the D:/ecs-quickstart directory.
# Switch to drive D.
d:
# Switch to the directory where the configuration file is located. Replace ecs-quickstart with your actual directory path.
cd ecs-quickstart
# Run the initialization command.
terraform init

The following output indicates that the initialization is successful.

Terraform has been successfully initialized!
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.

2. Preview the execution plan

Run terraform plan to perform the following functions:

  • Verify the syntax of the Terraform code in main.tf.

  • Preview the resources that will be created based on the current Terraform code.

terraform plan

If the output indicates that the Terraform configuration file has no syntax errors, you can run the terraform apply command to create resources. If other error messages appear, modify the Terraform configuration file according to the messages.

...
Plan: 5 to add, 0 to change, 0 to destroy.

3. Apply the configuration

Run terraform apply to automatically create the ECS instance and its dependent resources, and to install Python. When prompted during the creation process, enter yes to allow Terraform to create all the defined resources.

terraform apply

The following output indicates that Terraform has created the resources.

...
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_vpc.vpc: Creating...
alicloud_vpc.vpc: Creation complete after 6s [id=vpc-2vcsghlpznz74XXXXXXXX]
alicloud_security_group.default: Creating...
alicloud_vswitch.vsw: Creating...
alicloud_security_group.default: Creation complete after 1s [id=sg-2vcdz6b8h9c3XXXXXXXX]
alicloud_security_group_rule.allow_tcp_22: Creating...
alicloud_security_group_rule.allow_tcp_22: Creation complete after 0s [id=sg-2vcdz6b8h9c3XXXXXXXX:ingress:tcp:22/22:intranet:0.0.0.0/0:accept:1]
alicloud_vswitch.vsw: Creation complete after 4s [id=vsw-2vc50dknug30bXXXXXXXX]
alicloud_instance.instance: Creating...
alicloud_instance.instance: Still creating... [10s elapsed]
alicloud_instance.instance: Creation complete after 15s [id=i-2vc3rf151bwcXXXXXXXX]
Apply complete! Resources: 5 added, 0 changed, 0 destroyed.
Outputs:
public_ip = [
  "4XX.XXX.XXX.XX7",
]

Connect to the ECS instance

After the instance is created, you can connect to it remotely via SSH using its public IP address. For more information about connection methods, see Connection methods overview.

ssh <username>@<public_ip_address>

Verify the results

Run a Terraform command

You can run the following command to view information about the created ECS instance.

# Format: terraform state show <resource_type>.<resource_name>[index]
terraform state show alicloud_instance.instance[0]

View in the console

You can log on to the ECS console to view the created ECS instance. After you run the Terraform code, an instance named tf-sample is created and is in the Running state on the Instances page. The instance is deployed in Availability Zone A of the China (Chengdu) region. The instance type is ecs.e-c1m2.large (2 vCPUs and 4 GiB of memory), the private IP address is 172.16.0.100, the billing method is pay-as-you-go, and the network type is VPC.

Modify resources

If you need to adjust your configuration, you can modify the resource definitions in the configuration file. For example, you can add a new inbound rule to the security group.

  1. To add a rule to the security group that allows inbound traffic on port 443, add the following code to your configuration file.

    resource "alicloud_security_group_rule" "allow_tcp_443" {
      type              = "ingress"
      ip_protocol       = "tcp"
      nic_type          = "intranet"
      policy            = "accept"
      port_range        = "443/443"
      priority          = 1
      security_group_id = alicloud_security_group.default.id
      cidr_ip           = "0.0.0.0/0"
    }
  2. Run the terraform plan command to preview the changes. The following output indicates that a security group rule will be added to the security group with the ID sg-2vcdz6b8h9c3XXXXXXXX.

    ...
    Terraform will perform the following actions:
      # alicloud_security_group_rule.allow_tcp_443 will be created
      + resource "alicloud_security_group_rule" "allow_tcp_443" {
          + cidr_ip           = "0.0.0.0/0"
          + id                = (known after apply)
          + ip_protocol       = "tcp"
          + nic_type          = "intranet"
          + policy            = "accept"
          + port_range        = "443/443"
          + prefix_list_id    = (known after apply)
          + priority          = 1
          + security_group_id = "sg-2vcdz6b8h9c3XXXXXXXX"
          + type              = "ingress"
        }
    Plan: 1 to add, 0 to change, 0 to destroy.
  3. If the changes are as expected, run the terraform apply command to apply the changes to your infrastructure. When Terraform prompts you to confirm, type yes and press Enter. The following message indicates that a new rule was successfully added to the security group with the ID sg-2vcdz6b8h9c3XXXXXXXX.

    ...
    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_tcp_443: Creating...
    alicloud_security_group_rule.allow_tcp_443: Creation complete after 0s [id=sg-2vcdz6b8h9c3XXXXXXXX:ingress:tcp:443/443:intranet:0.0.0.0/0:accept:1]
    Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Clean up resources

When you no longer need the resources, run the following command to destroy them.

terraform destroy

The following output indicates that the resources are destroyed.

...
Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.
  Enter a value: yes
alicloud_security_group_rule.allow_tcp_443: Destroying... [id=sg-2vcdz6b8h9c3XXXXXXXX:ingress:tcp:443/443:intranet:0.0.0.0/0:accept:1]
alicloud_security_group_rule.allow_tcp_22: Destroying... [id=sg-2vcdz6b8h9c3XXXXXXXX:ingress:tcp:22/22:intranet:0.0.0.0/0:accept:1]
alicloud_instance.instance: Destroying... [id=i-2vc3rf151bwcXXXXXXXX]
alicloud_security_group_rule.allow_tcp_22: Destruction complete after 0s
alicloud_security_group_rule.allow_tcp_443: Destruction complete after 0s
alicloud_instance.instance: Still destroying... [id=i-2vc3rf151bwcXXXXXXXX, 10s elapsed]
alicloud_instance.instance: Destruction complete after 10s
alicloud_security_group.default: Destroying... [id=sg-2vcdz6b8h9c3XXXXXXXX]
alicloud_vswitch.vsw: Destroying... [id=vsw-2vc50dknug30bXXXXXXXX]
alicloud_security_group.default: Destruction complete after 1s
alicloud_vswitch.vsw: Destruction complete after 8s
alicloud_vpc.vpc: Destroying... [id=vpc-2vcsghlpznz74XXXXXXXX]
alicloud_vpc.vpc: Destruction complete after 6s
Destroy complete! Resources: 6 destroyed.

References