Create resources with Terraform
Terraform is an open source infrastructure as code (IaC) tool that you can use to manage the full lifecycle of Alibaba Cloud resources by using declarative configuration files. Get started quickly with either a visual interface or the command line to create your first Alibaba Cloud resource.
Choose a method
Terraform offers two methods: visual and command-line. Choose the one that fits your needs.
|
Method |
Scenarios |
Advantages |
Limits |
|
First-time use, unfamiliar with parameters, quick debugging |
Configure resources using a graphical form. No coding required. |
Supports only single-resource operations. |
|
|
Quick evaluation, production environments, complex orchestration |
Supports multi-resource orchestration and state management. |
Requires a CLI environment. |
If you choose the CLI method, prepare your environment using either Cloud Shell or local installation.
Use Terraform Explorer
Terraform Explorer is Alibaba Cloud's online debugging tool built on Terraform. It generates Terraform configuration files from forms and runs them in the cloud. For more information, see Explorer overview.
The following example creates a Virtual Private Cloud (VPC) to demonstrate two ways to use Terraform Explorer: custom parameters and sample templates.
Create resources using custom parameters
To configure parameters based on your needs, follow these steps:
-
Log on to Terraform Explorer. Select a Product and a Resource Type. Fill in the parameters by using the Resource Documentation, and then click Initiate.
The main parameters for creating a VPC are listed below. For more parameter details, see alicloud_vpc.
Parameter Name
Description
Example value
vpc_name
VPC name
tf-test-vpc
cidr_block
Private CIDR block for the VPC
192.168.0.0/16
description
Description of the VPC
The VPC was created using Terraform.
-
On the Template Details tab, confirm that the parameters are correct, and then click Plan to view the execution plan.
terraform { required_providers { alicloud = { source = "aliyun/alicloud" version = "1.231.0" } } } provider "alicloud" { region = "cn-beijing" } resource "alicloud_vpc" "default" { cidr_block = "192.168.0.0/16" description = "The VPC was created using Terraform." vpc_name = "tf-test-vpc" } -
On the Details tab, review the information about the resources to be created, and then click Execute.
The preview result shows a Success status and the message
Plan: 1 to add, 0 to change, 0 to destroy. This indicates that thealicloud_vpc.defaultresource will be created. Thecidr_blockis192.168.0.0/16, and thedescriptionisThe VPC was created using Terraform.. Terraform generates other attributes after execution. -
On the Execution Details tab, view the result. A successful execution displays the message "
Apply complete! Resources: 1 added, 0 changed, 0 destroyed." If the execution fails, modify the parameters based on the error message and try again. -
On the Resource Details tab, view information about the created resource.
The resource address is
alicloud_vpc.default. The page displays various attributes of the VPC, including:-
cidr_block:
192.168.0.0/16 -
name:
tf-test-vpc -
description:
The VPC was created using Terraform. -
create_time: The time when the VPC was created.
-
Network configurations such as classic_link_enabled and enable_ipv6.
-
Associated resource information such as resource_group_id, route_table_id, and router_id.
-
-
(Optional) Modify the resource: Adjust the parameters and click Plan & Apply, then repeat steps 2 through 4. A successful update displays the message "
Apply complete! Resources: 0 added, 1 changed, 0 destroyed.". -
(Optional) Destroy the resource: On the Execution Details tab, click Destroy Resources. Then, on the Details tab, click Execute.
When the operation is complete, the Execution Details tab shows a Success status with the message
Apply complete! Resources: 0 added, 0 changed, 1 destroyed, confirming that one VPC resource was destroyed.
Create resources using a sample template
If you are unfamiliar with resource parameters or want a quick start, use a sample template from Terraform Explorer.
-
Log on to Terraform Explorer. Select the corresponding Product, Resource Type, and Sample Template, and then click Initiate. You can view the template details on the Sample Template tab on the right.
In the Input Parameters area on the left, you can view and modify the parameters required by the template. For example, you can set the name parameter to
terraform-example. You can also click Add Parameter to add more parameters. -
On the Template Details tab, click Plan & Apply.
This sample template is in the Terraform format. It defines an
alicloud_vpcresource with parameters such asipv6_ispset to BGP,cidr_blockset to10.0.0.0/8, andenable_ipv6set to true. -
On the Execution Details tab, you can view the execution result.
-
(Optional) To destroy the created resource, click Destroy Resources on the Execution Details tab. Then, on the Details tab, click Execute.
You can also perform operations such as Continue and Destroy Resources from the Call History.
Use Terraform CLI
To use Terraform from the command line, prepare a CLI environment, write a configuration file, and then run commands to create resources. Choose one of the following methods to set up your CLI environment:
-
Cloud Shell (recommended): No installation needed. Ideal for quick evaluation and learning.
-
Local installation: Best for production environments, continuous integration, and long-term use.
Cloud Shell
Alibaba Cloud Cloud Shell is a free operations tool that comes pre-installed with Terraform and pre-configured with identity credentials, so you can run Terraform commands immediately.
Log on to Cloud Shell
Open your browser and go to Cloud Shell. For more information, see Use Cloud Shell.
Log on as a RAM user. To ensure the security of your Alibaba Cloud account, avoid using your Alibaba Cloud account to access cloud resources unless necessary.
Switch Terraform versions
The default Terraform version in Cloud Shell may be outdated. Switch to version 1.2 or later to ensure all features work correctly.
-
Check your current Terraform version:
terraform versionshell@Alicloud:~$ terraform version Terraform v0.12.31 Your version of Terraform is out of date! The latest version is 1.12.2. You can update by downloading from https://www.terraform.io/downloads.html -
List available Terraform versions in Cloud Shell:
tfenv listshell@Alicloud:~$ tfenv list 1.9.5 1.5.7 1.3.7 0.13.7 * 0.12.31 (set by /usr/local/tfenv/version) -
Switch to a specific version (for example, 1.9.5):
tfenv use 1.9.5shell@Alicloud:~$ tfenv use 1.9.5 Switching default version to v1.9.5 Switching completed
Local installation
Best for production environments and complex orchestration. Install Terraform and configure identity credentials first.
Install using a package manager (recommended)
macOS
Install using Homebrew:
# Add HashiCorp's tap to define where packages are located in Homebrew
brew tap hashicorp/tap
# Install Terraform
brew install hashicorp/tap/terraform
Update to the latest version:
# Update Homebrew
brew update
# Upgrade Terraform
brew upgrade hashicorp/tap/terraform
Windows
Install using Chocolatey:
choco install terraform
Linux
For example, using the yum package manager:
yum install -y dnf-plugin-releasever-adapter
yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
yum install terraform
Manual installation
If a package manager is unavailable, install manually.
Use a precompiled binary
-
Download the ZIP file for your operating system from the Terraform website. Extract the archive.
-
Move the
terraformbinary file to a directory in your systemPATH:-
macOS or Linux
mv ~/Downloads/terraform /usr/local/bin/ -
Windows
-
Open Control Panel > System > System Settings > Environment Variables.
-
In System Variables, find PATH and click Edit.
-
Add the path to your Terraform directory. Separate it from other entries with a semicolon (for example,
c:\path;c:\path2). -
Open a new command-line window for the change to take effect.
-
-
Compile from source
You must first install the Go development environment.
-
Clone the Terraform source repository:
git clone https://github.com/hashicorp/terraform.git -
Navigate to the directory, and then compile and install the software.
cd terraform go installAfter compilation, the binary is placed in the
$GOPATH/bin/directory. -
Ensure
$GOPATH/binis added to your system PATH. Use the same steps as in Use a precompiled binary, step 2.
Verify the installation
Run this command to confirm Terraform is installed correctly:
terraform version
If the command runs successfully and displays the version number, the installation is complete.
Example: Create an ECS instance
This example walks through the full Terraform orchestration workflow by creating an ECS instance: VPC → vSwitch → security group → ECS instance.
-
Create a working directory and write the Terraform configuration file
main.tf:mkdir tf-demo && cd tf-demo vim main.tfCopy the following code into
main.tf:provider "alicloud" { region = var.region } # Region for resource creation variable "region" { default = "cn-beijing" } # ECS instance name variable "instance_name" { default = "tf-cloudshell-test" } # ECS instance type variable "instance_type" { default = "ecs.n2.small" } # Outbound public bandwidth. A value of 0 means no public network access. variable "internet_bandwidth" { default = 10 } # ECS OS image variable "image_id" { default = "ubuntu_18_04_64_20G_alibase_20190624.vhd" } # ECS system disk type variable "disk_category" { default = "cloud_efficiency" } # ECS instance logon password variable "password" { default = "TF-test@1234" } # Create a VPC resource "alicloud_vpc" "vpc" { vpc_name = "tf_test_foo" cidr_block = "172.16.0.0/12" } # Query for availability zones based on the instance type and disk category data "alicloud_zones" "default" { available_disk_category = var.disk_category available_resource_creation = "VSwitch" available_instance_type = var.instance_type } # 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 } # Create a security group resource "alicloud_security_group" "default" { security_group_name = "default" vpc_id = alicloud_vpc.vpc.id } # Create an inbound security group rule 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.default.id cidr_ip = "0.0.0.0/0" } resource "alicloud_instance" "instance" { # Attach the security group security_groups = alicloud_security_group.default.*.id instance_type = var.instance_type system_disk_category = var.disk_category image_id = var.image_id instance_name = var.instance_name # Specify the vSwitch vswitch_id = alicloud_vswitch.vsw.id internet_max_bandwidth_out = var.internet_bandwidth password = var.password }ImportantThe security group rule in this example opens all TCP ports (1–65535) and allows traffic from any IP address (0.0.0.0/0). Use this only in test environments. In production, restrict ports and source IP addresses as needed.
-
Initialize the Terraform working directory:
terraform init -
Preview the execution plan to confirm which resources will be created:
terraform planshell@Alicloud:~/tf-demo$ terraform plan data.alicloud_zones.default: Reading... data.alicloud_zones.default: Read complete after 1s [id=1373912221] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # alicloud_instance.instance will be created + resource "alicloud_instance" "instance" { + availability_zone = (known after apply) + cpu = (known after apply) + create_time = (known after apply) + credit_specification = (known after apply) + deployment_set_group_no = (known after apply) + description = (known after apply) + dry_run = false + enable_jumbo_frame = (known after apply) + expired_time = (known after apply) + host_name = (known after apply) + http_endpoint = (known after apply) + http_put_response_hop_limit = (known after apply) + http_tokens = (known after apply) + id = (known after apply) + image_id = "ubuntu_18_04_64_20G_alibase_20190624.vhd" + instance_charge_type = (known after apply) + instance_name = "tf-cloudshell-test" + instance_type = "ecs.n2.small" + internet_charge_type = (known after apply) + internet_max_bandwidth_in = (known after apply) + internet_max_bandwidth_out = 10 + io_optimized = (known after apply) + ipv6_address_count = (known after apply) + ipv6_addresses = (known after apply) + key_name = (known after apply) + maintenance_action = (known after apply) + memory = (known after apply) + network_interface_id = (known after apply) + network_interface_traffic_mode = (known after apply) + os_name = (known after apply) + os_type = (known after apply) + password = (sensitive value) + period = (known after apply) + primary_ip_address = (known after apply) -
Create the resources. The output "
Apply complete!" means success:terraform applyApply complete! Resources: 5 added, 0 changed, 0 destroyed. -
To release these resources, run:
terraform destroy