Terraform reference

Updated at:

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.

terraform

The output shows that Terraform is built into Cloud Shell and ready to use.

image

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

  1. Go to Control Panel > System > Advanced system settings > Environment Variables.

  2. In System variables, scroll down until you find PATH.

  3. Click Edit and make your changes.

  4. Make sure to add a semicolon to separate entries. For example: `c:\path;c:\path2`

  5. 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 $PATH

Move 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.git

You will see progress information. Wait for the process to complete.

image

After the command runs, a new directory named `terraform` is created in your current directory. Use the `cd` command to enter this directory.

cd terraform

Then, run the install command to compile the directory and move the compiled package to the $GOPATH/bin/terraform directory.

go install

The following information indicates that the compilation is in progress. Wait for the process to finish before you continue.

image

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 $PATH

Move 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

  1. Navigate to Control Panel > System > System Settings > Environment Variables.

  2. In the System variables section, scroll down to find the PATH variable.

  3. Click Edit and make your changes.

  4. Use a semicolon to separate entries, such as c:\path;c:\path2

  5. 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/tap

Step 2. Run the `install` command to install Terraform.

brew install hashicorp/tap/terraform
Important

The `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 update

Then, run the `upgrade` command to update to the latest version.

brew upgrade hashicorp/tap/terraform

Linux

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

image

image

Windows Chocolatey

Chocolatey is a popular package manager for Windows. You can use Chocolatey to install Terraform by running simple commands.

choco install terraform

Authenticate 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

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

  2. 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

Important

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

Note

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.

Resource

alicloud_auto_provisioning_group: Provides a resource to create an auto provisioning group for ECS. This group uses spot instances and pay-as-you-go instances to quickly deploy clusters.

alicloud_ecs_disk_attachment: Provides a resource to attach a data disk or system disk to an ECS instance.

alicloud_ecs_activation: Provides a resource to create ECS activation codes. You can configure parameters, such as a description, the maximum number of registered instances, a default instance name prefix, the IP address range of hosts that can use the code, and the code's validity period, to register managed instances in batches.

alicloud_ecs_auto_snapshot_policy: Provides a resource to create an automatic snapshot policy for ECS. You can configure the snapshot creation schedule, such as the days of the week and time of day, and set a retention period. This resource also supports cross-region replication and encryption for snapshots.

alicloud_ecs_auto_snapshot_policy_attachment: Provides a resource to attach an automatic snapshot policy to a specified disk. You can apply a predefined policy to a disk by associating the policy ID with the disk ID.

alicloud_ecs_capacity_reservation: Provides a resource to create a capacity reservation on Alibaba Cloud. You can reserve resources for a specific instance type to ensure that a specified number of instances can be launched when needed.

alicloud_ecs_command: Provides a resource to create a command on an Alibaba Cloud ECS instance. You can execute predefined script commands by specifying parameters such as the Base64-encoded command content, a description, whether to enable custom parameters, a command name, a timeout period, and the command type.

alicloud_ecs_dedicated_host: Provides a resource to create a dedicated host on Alibaba Cloud. You can configure parameters such as the host type, billing method, auto-renewal cycle, hostname, and description.

alicloud_ecs_dedicated_host_cluster: Provides a resource to create a dedicated host cluster on Alibaba Cloud. You can configure parameters such as the cluster name, description, zone, and tags to centrally manage and organize dedicated host resources.

alicloud_ecs_deployment_set: Provides a resource to create a deployment set on Alibaba Cloud. You can manage the distribution of ECS instances by specifying parameters such as the deployment strategy, deployment set name, and description. This helps you achieve specific goals, such as high availability or low latency.

alicloud_ecs_disk: Provides a resource to create a disk (data disk) on Alibaba Cloud. You can configure parameters such as the disk type, size, encryption status, snapshot ID, performance level (PL), and tags to meet the storage needs of different scenarios.

alicloud_ecs_disk_attachment: Provides a resource to attach and detach disks from ECS instances on Alibaba Cloud. You can associate a disk with an instance by specifying the instance ID and disk ID. Options are available to release the disk with the instance and to attach the disk as a system disk.

alicloud_ecs_elasticity_assurance: Provides a resource to create an elasticity assurance on Alibaba Cloud. This ensures that a certain amount of computing resource capacity is reserved for a specified instance type in a specific region.

alicloud_ecs_hpc_cluster: Provides a resource to create a high-performance computing (HPC) cluster on Alibaba Cloud. You can configure the basic information of the cluster by specifying the name and description.

alicloud_ecs_image_component: Provides a resource to create an image component on Alibaba Cloud. You can define the content, type, applicable operating systems, and other metadata for build or test components. This allows the components to be reused when you create custom images.

alicloud_ecs_image_pipeline: Provides a resource to create an image pipeline on Alibaba Cloud. You can automate the creation and management of custom images by specifying the base image, build content, instance type, and other configurations.

alicloud_ecs_image_pipeline_execution: Provides a resource to execute an image pipeline task on Alibaba Cloud. This creates a custom image based on a defined image pipeline. You can trigger an image build task by specifying the image pipeline ID and monitor the task status and results.

alicloud_ecs_invocation: Provides a resource to manage and execute command invocations on ECS instances. You can run a specified command on one or more ECS instances and retrieve the execution results.

alicloud_ecs_key_pair: Provides a resource to manage and create key pairs for ECS instances.

alicloud_ecs_key_pair_attachment: Provides a resource to attach an ECS key pair to a specified ECS instance.

alicloud_ecs_launch_template: Provides a resource to manage ECS launch templates. This helps you quickly create and deploy ECS instances with predefined configurations, which improves efficiency and ensures consistency.

alicloud_ecs_network_interface: Provides a resource to manage ECS network interfaces. This helps you configure and manage instance network connectivity. It supports flexible private IP allocation policies and is suitable for complex network environments and high availability designs.

alicloud_ecs_network_interface_attachment: Provides a resource to attach an Elastic Network Interface (ENI) to an Alibaba Cloud ECS instance. This lets you flexibly extend the instance's network capabilities, such as adding multiple IP addresses or implementing more complex network configurations.

alicloud_ecs_network_interface_permission: Provides an ECS network interface permission resource.

alicloud_ecs_prefix_list: Provides a resource to create and manage a prefix list in Alibaba Cloud ECS.

alicloud_ecs_session_manager_status: Provides a resource to manage and configure the status of Session Manager in Alibaba Cloud ECS. You can enable or disable the session management feature to control access to and management of ECS instances.

alicloud_ecs_snapshot: Provides a resource to create a disk snapshot in Alibaba Cloud. You can back up the data of a specified disk for future recovery or archiving.

alicloud_ecs_snapshot_group: Provides a resource to create a snapshot for a group of disks in Alibaba Cloud.

alicloud_ecs_storage_capacity_unit: Provides a resource to create and manage a storage capacity unit in Alibaba Cloud ECS.

alicloud_image: Provides a resource to create a custom image on Alibaba Cloud from an existing ECS instance.

alicloud_image_copy: Provides a resource to copy a custom image from one region to another.

alicloud_image_export: Provides a resource to export a custom image to an OSS bucket in the same region as the custom image.

alicloud_image_import: Provides a resource to import an ECS image.

alicloud_image_share_permission: Provides a resource to manage image sharing permissions.

alicloud_instance: Provides an ECS instance resource.

alicloud_ecs_key_pair: Provides an ECS key pair resource.

alicloud_ecs_key_pair_attachment: Provides a resource to attach a key pair to multiple ECS instances.

alicloud_ecs_launch_template: Provides an ECS launch template resource.

alicloud_ecs_network_interface: Provides an ECS network interface resource.

alicloud_ecs_network_interface_attachment: Provides an ECS network interface attachment resource.

alicloud_ram_role_attachment: Provides a resource to attach an instance RAM role to multiple ECS instances.

alicloud_reserved_instance: Provides a reserved instance resource.

alicloud_security_group: Provides an ECS security group resource.

alicloud_security_group_rule: Provides a security group rule resource.

alicloud_ecs_snapshot: Provides an ECS snapshot resource.

alicloud_ecs_auto_snapshot_policy: Provides an ECS automatic snapshot policy resource.

Use Terraform to create and manage ECS resources

This section provides an example of how to create and manage ECS resources with Terraform.

  1. 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.
    }
  2. Run the following command to initialize the Terraform runtime environment.

    terraform init

    The 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.
  3. Run the following command to execute the code.

    terraform apply

    During the execution, enter yes when 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.

  4. 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

image

Log on to the console to view the resources

Log on to the ECS console. In the navigation pane on the left, choose Instances & Images > Instances. In the top-left corner, select a region. In this example, select China (Beijing) to view the created ECS instance.

image

References