Terraform reference
Terraform is an open source infrastructure as code (IaC) tool that allows developers to define and manage infrastructure configurations using a declarative language. Terraform provides a simple way to create, modify, or delete Elastic Compute Service (ECS) resources. This approach reduces the complexity and errors of manual operations and improves the manageability and maintainability of your infrastructure. This topic describes how to install and configure Terraform and use it to create an ECS instance.
Basic features of Terraform
Terraform is an IT infrastructure automation and orchestration tool. It lets you use code to manage and maintain IT resources. For more information, see What is Terraform?.
The Terraform command-line interface (CLI) provides a simple way to deploy configuration files to Alibaba Cloud or other supported clouds and manage their versions. You can define your infrastructure, such as virtual machines, storage accounts, and network interfaces, in configuration files that describe your cloud resource topology.
Terraform supports new infrastructure through providers. This lets you easily define, preview, and deploy cloud infrastructure on Alibaba Cloud using a simple template language.
You can use Terraform to create, modify, and delete the resources of multiple Alibaba Cloud services.
For more information about the integration of Alibaba Cloud and Terraform, see Alibaba Cloud Provider.
Install Terraform
Cloud Shell
Alibaba Cloud Shell is a free operations and maintenance (O&M) product that comes pre-installed with Terraform. You can run Terraform commands directly in Cloud Shell.
First, make sure that you have a valid Alibaba Cloud account with the required permissions.
Next, open your browser and go to the Cloud Shell URL: https://shell.aliyun.com.
After you log on, run the following command.
terraformThe output shows that Terraform is built into Cloud Shell and ready to use.

For more information about how to use Cloud Shell, see Use Cloud Shell.
Manual installation
Use a precompiled package
Go to the Terraform official website. Find and download the ZIP package for your operating system.
After the download is complete, decompress the package to /usr/local/bin. After the copy is complete, you can delete the other files without affecting how Terraform runs.
Finally, make sure that the Terraform directory is added to the `PATH` environment variable. This process varies depending on your operating system.
Windows
Go to Control Panel > System > Advanced system settings > Environment Variables.
In System variables, scroll down until you find PATH.
Click Edit and make your changes.
Make sure to add a semicolon to separate entries. For example: `c:\path;c:\path2`
Start a new console for the changes to take effect.
For more information, see Define a global path in Windows.
macOS or Linux
Print your `PATH` configuration.
echo $PATHMove the Terraform binary file to one of the listed locations. This command assumes that the binary file is in your Downloads folder and your PATH includes /usr/local/bin. Customize the directories in the command if your locations are different.
mv ~/Downloads/terraform /usr/local/bin/For more information, see:
Use the source code
If you want to compile the binary file from source code, clone the HashiCorp Terraform repository.
git clone https://github.com/hashicorp/terraform.gitYou will see progress information. Wait for the process to complete.

After the command runs, a new directory named `terraform` is created in your current directory. Use the `cd` command to enter this directory.
cd terraformThen, run the install command to compile the directory and move the compiled package to the $GOPATH/bin/terraform directory.
go installThe following information indicates that the compilation is in progress. Wait for the process to finish before you continue.

Note: If the message "zsh: command not found: go" appears, you need to install the Go environment.
Finally, ensure the Terraform directory is in your system's PATH. The method for setting the PATH depends on your operating system.
macOS or Linux
Print the PATH configuration
echo $PATHMove the Terraform binary file to a directory in your PATH. The following command assumes the binary file is in your Downloads folder and that your PATH includes /usr/local/bin. If your configuration is different, customize the directories in the command.
mv ~/Downloads/terraform /usr/local/bin/For more information, see:
Windows
Navigate to Control Panel > System > System Settings > Environment Variables.
In the System variables section, scroll down to find the PATH variable.
Click Edit and make your changes.
Use a semicolon to separate entries, such as c:\path;c:\path2
Open a new console for the changes to take effect.
For more information, see Define a global path in Windows.
macOS Homebrew
Homebrew is a popular package installation tool for macOS. You can use Homebrew to install Terraform with simple commands.
Step 1. Install the HashiCorp tap, which is a repository for all HashiCorp Homebrew packages.
brew tap hashicorp/tapStep 2. Run the `install` command to install Terraform.
brew install hashicorp/tap/terraformThe `install` command indexes and installs the latest version. If you want to update to the latest version later, you can run the `upgrade` command.
To update to the latest version of Terraform, you must first update Homebrew.
brew updateThen, run the `upgrade` command to update to the latest version.
brew upgrade hashicorp/tap/terraformLinux
Alibaba Cloud Linux
yum install -y dnf-plugin-releasever-adapter
yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
yum install terraform

Windows Chocolatey
Chocolatey is a popular package manager for Windows. You can use Chocolatey to install Terraform by running simple commands.
choco install terraformAuthenticate Terraform
You can authenticate Terraform by storing access credentials in environment variables. When you run a Terraform command, Terraform attempts to retrieve credentials from these variables if they are not explicitly declared in the configuration template. The following sections describe how to set environment variables.
Windows
On the desktop, right-click This PC and select .
In the System variables or User variables section, click New to create the following environment variables.
Variable name
Variable descriptions
Value
ALICLOUD_ACCESS_KEY
AccessKey ID
yourAccessKeyID
ALICLOUD_SECRET_KEY
AccessKey secret
yourAccessKeySecret
ALICLOUD_SECURITY_TOKEN (Optional)
If you use Security Token Service (STS) credentials, you must configure this variable.
yourSTSToken
Linux
A temporary environment variable configured with the `export` command is valid only for the current session. After you exit the session, the environment variable becomes invalid. To make the environment variable permanent, add the `export` command to the startup configuration file of your operating system.
# AccessKey ID
$ export ALICLOUD_ACCESS_KEY="<your AccessKey ID>"
# AccessKey secret
$ export ALICLOUD_SECRET_KEY="<your AccessKey secret>"
# If you use STS credentials, you must configure security_token.
$ export ALICLOUD_SECURITY_TOKEN="<your access token>"After you set the environment variables, you do not need to declare credentials in the provider block. You can declare only the region.
provider "alicloud" {
region = "cn-hangzhou"
}You can also configure the region using the ALICLOUD_REGION environment variable. If the region is not explicitly declared and this environment variable is not set, the default value is cn-beijing.
Supported resources
A resource is a new object, such as an ECS instance, a virtual machine (VM), or a security group, that is used to define an infrastructure component.
Use Terraform to create and manage ECS resources
This section provides an example of how to create and manage ECS resources with Terraform.
Create a working directory. In the directory, create a configuration file named main.tf. The following code creates an ECS instance and its required VPC, security group, and vSwitch resources. Copy the code into the main.tf file.
# Define a variable "region" with the default value "cn-beijing" to specify the Alibaba Cloud region. variable "region"{ default = "cn-beijing" } # Configure the Alibaba Cloud provider to use the region defined in the "region" variable. provider "alicloud"{ region = var.region } # Define a string variable "instance_type" with the default value "ecs.e-c1m1.large" to specify the ECS instance type. variable "instance_type" { type = string default = "ecs.e-c1m1.large" } # Use a data source to query zone information. Filter the results by the specified instance type, resource creation type (such as VSwitch), and disk category. data "alicloud_zones" "default" { available_instance_type = var.instance_type available_resource_creation = "VSwitch" available_disk_category = "cloud_essd" } # Define a variable "vpc_cidr_block" with the default value "172.16.0.0/16" to specify the CIDR block for the VPC. variable "vpc_cidr_block" { default = "172.16.0.0/16" } # Define a variable "vsw_cidr_block" with the default value "172.16.0.0/24" to specify the CIDR block for the vSwitch. variable "vsw_cidr_block" { default = "172.16.0.0/24" } # Generate a random integer between 10000 and 99999 to ensure the uniqueness of some resource names. resource "random_integer" "default" { min = 10000 max = 99999 } # Create a VPC named "vpc-test" and use the random integer to ensure the name is unique. resource "alicloud_vpc" "vpc" { vpc_name = "vpc-test_${random_integer.default.result}" cidr_block = var.vpc_cidr_block } # Create a security group, include the random integer in the name to ensure uniqueness, and associate it with the VPC created above. resource "alicloud_security_group" "group" { security_group_name = "test_${random_integer.default.result}" # The field name here was replaced. vpc_id = alicloud_vpc.vpc.id } # Create a security group rule to allow all inbound TCP traffic and associate it with the previously created security group. resource "alicloud_security_group_rule" "allow_all_tcp" { type = "ingress" ip_protocol = "tcp" nic_type = "intranet" # Modified here, nic_type is changed to 'intranet'. policy = "accept" port_range = "1/65535" priority = 1 security_group_id = alicloud_security_group.group.id cidr_ip = "0.0.0.0/0" } # Create a vSwitch, include the random integer in the name to ensure uniqueness, and associate it with the VPC and zone. resource "alicloud_vswitch" "vswitch" { vpc_id = alicloud_vpc.vpc.id cidr_block = var.vsw_cidr_block zone_id = data.alicloud_zones.default.zones[0].id vswitch_name = "vswitch-test-${random_integer.default.result}" } # Create an ECS instance. Set multiple parameters such as the zone, security group, and instance type. Use the random integer to ensure the instance name is unique. resource "alicloud_instance" "instance" { availability_zone = data.alicloud_zones.default.zones[0].id security_groups = [alicloud_security_group.group.id] instance_type = var.instance_type system_disk_category = "cloud_essd" system_disk_name = "test_foo_system_disk_${random_integer.default.result}" system_disk_description = "test_foo_system_disk_description" image_id = "aliyun_2_1903_x64_20G_alibase_20240628.vhd" instance_name = "test_ecs_${random_integer.default.result}" vswitch_id = alicloud_vswitch.vswitch.id internet_max_bandwidth_out = 10 password = "Terraform@Example" # Modify the password based on your requirements. }Run the following command to initialize the Terraform runtime environment.
terraform initThe following output indicates that Terraform is initialized successfully.
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.Run the following command to execute the code.
terraform applyDuring the execution, enter
yeswhen prompted and press Enter. Wait for the command to complete. If the following output appears, the code was executed successfully.You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure. 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 Apply complete! Resources: 6 added, 0 changed, 0 destroyed.Verify the results
Run the terraform show command
In the working directory, run the following command to query the details of the resources that were created by Terraform:
terraform show
Log on to the console to view the resources
Log on to the ECS console. In the navigation pane on the left, choose . In the top-left corner, select a region. In this example, select China (Beijing) to view the created ECS instance.

References
For more tutorials, see Terraform Tutorials.
For more information about common Terraform commands, see Common Commands.
If the `terraform init` command times out due to network latency and you cannot download the provider, see Configure an acceleration solution for Terraform Init.
Terraform is available as a managed service in ROS. You can deploy Terraform templates in the ROS console. For more information, see Create a Terraform stack.