Use Terraform on Linux

Updated at:
Copy as MD

Install, configure, and run Terraform to provision Alibaba Cloud resources on a Linux system.

Managing your infrastructure as code (IaC) with Terraform involves the following main steps.

  1. Install Terraform.

  2. Configure Terraform. Set up identity authentication for the Alibaba Cloud provider.

  3. Write a Terraform configuration file. Define the resources to create, such as RAM users and policies.

  4. Initialize and create resources. Download the provider plug-in and deploy the declared resources.

  5. View and manage resources. Inspect, modify, or update deployed resources as requirements change.

  6. Destroy resources. Remove resources that are no longer needed.

1. Install Terraform

Terraform is an infrastructure as code (IaC) tool for managing cloud resources through declarative configuration files. Install Terraform before running any Terraform commands. For more information about the installation steps, see Install Terraform.

2. Configure Terraform

Terraform authenticates with Alibaba Cloud through the Alibaba Cloud provider. Multiple authentication methods are supported. For more information, see Terraform authentication.

The following example uses a RAM user AccessKey pair configured in environment variables:

export ALICLOUD_ACCESS_KEY="<yourAccessKeyID>"
export ALICLOUD_SECRET_KEY="<yourAccessKeySecret>"
export ALICLOUD_REGION="cn-beijing"

3. Write a Terraform configuration file

Configuration files define the infrastructure resources to deploy, such as RAM users, ECS instances, and OSS buckets.

  1. Create a working directory named ram and a configuration file named main.tf.

    # Create a working directory and go to the directory.
    mkdir ram && cd ram
    # Create and edit the configuration file.
    touch main.tf && vim main.tf
    

    A separate working directory per project keeps state files isolated and simplifies version control.

  2. Write a Terraform configuration file. This example creates a RAM user and grants the user ECS management permissions.

    The example uses these resources:

    Important

    Avoid enabling both console logon and AccessKey pair access for the same RAM user to keep responsibilities clear and prevent misuse.

    Resource

    Description

    alicloud_ram_user

    Create a RAM user

    alicloud_ram_login_profile

    Allow a RAM user to log on to the console

    alicloud_ram_access_key

    Create an AccessKey pair for a RAM user

    alicloud_ram_policy

    Create an access policy

    alicloud_ram_user_policy_attachment

    Grant permissions to a RAM user

    Copy the following code to main.tf. Press Esc to exit insert mode, type :wq, and press Enter to save.

    variable "user_name" {
      default = "terraform_user_test"
    }
    variable "user_password" {
      default = "!Test@123456"
    }
    variable "user_display_name" {
      default = "TestAccount"
    }
    variable "user_mobile" {
      default = "86-18688888888"
    }
    variable "user_email" {
      default = "example@example.com"
    }
    resource "alicloud_ram_user" "user" {
      name         = var.user_name
      display_name = var.user_display_name
      mobile       = var.user_mobile
      email        = var.user_email
      comments     = "Created by Terraform"
      force        = true                   
    }
    resource "alicloud_ram_login_profile" "profile" {
      user_name = alicloud_ram_user.user.name
      password  = var.user_password
    }
    resource "alicloud_ram_access_key" "ak" {
      user_name   = alicloud_ram_user.user.name
      secret_file = "accesskey.txt"
    }
    resource "alicloud_ram_policy" "policy" {
      policy_name     = "tf-example-policy"
      policy_document = <<EOF
      {
        "Statement": [
          {
            "Action": "ecs:*",
            "Effect": "Allow",
            "Resource":"*"
          }
        ],
          "Version": "1"
      }
      EOF
      description     = "This is a policy test."
    }
    resource "alicloud_ram_user_policy_attachment" "attach" {
      policy_name = alicloud_ram_policy.policy.policy_name
      policy_type = alicloud_ram_policy.policy.type
      user_name   = alicloud_ram_user.user.name
    }

4. Initialize and create resources

Initialize the working directory before creating resources.

4.1 Terraform initialization

Run terraform init to initialize the working directory. terraform init downloads the Alibaba Cloud provider plug-in and must run before any other Terraform command.

4.2 Create resources

  1. Run terraform plan to preview the resources that will be created, modified, or destroyed by terraform apply.

    # alicloud_ram_user.user will be created
    + resource "alicloud_ram_user" "user" {
        + comments     = "Created by Terraform"
        + display_name = "TestAccount"
        + email        = "example@example.com"
        + force        = true
        + id           = (known after apply)
        + mobile       = "86-18688888888"
        + name         = "terraform_user_test"
      }
    # alicloud_ram_user_policy_attachment.attach will be created
    + resource "alicloud_ram_user_policy_attachment" "attach" {
        + id          = (known after apply)
        + policy_name = "tf-example-policy"
        + policy_type = (known after apply)
        + user_name   = "terraform_user_test"
      }
    Plan: 5 to add, 0 to change, 0 to destroy.
  2. When you run terraform apply, resources are created based on the execution plan generated by terraform plan. During the creation process, you need to enter yes at the prompt to continue creating the resources. For information about how to pass values to variables, see Variable.

    Plan: 5 to add, 0 to change, 0 to destroy.
    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_ram_user.user: Creating...
    alicloud_ram_policy.policy: Creating...
    alicloud_ram_policy.policy: Creation complete after 0s [id=tf-example-policy]
    alicloud_ram_user.user: Creation complete after 1s [id=20xxx18]
    alicloud_ram_login_profile.profile: Creating...
    alicloud_ram_access_key.ak: Creating...
    alicloud_ram_user_policy_attachment.attach: Creating...
    alicloud_ram_user_policy_attachment.attach: Creation complete after 0s [id=user:tf-example-policy:Custom:terraform_user_test]
    alicloud_ram_login_profile.profile: Creation complete after 0s [id=terraform_user_test]
    alicloud_ram_access_key.ak: Creation complete after 1s [id=LTxxxGr]
    Apply complete! Resources: 5 added, 0 changed, 0 destroyed.

5. View and manage resources

After deployment, manage and maintain your infrastructure.

5.1 View resources

  1. Run terraform show to view resource details.

    [root@iZ2***tZ ram]# terraform show
    # alicloud_ram_access_key.ak:
    resource "alicloud_ram_access_key" "ak" {
        id          = "LTAxxxxxxxxxxxxxxxxxxxiGr"
        secret      = (sensitive value)
        secret_file = "accesskey.txt"
        status      = "Active"
        user_name   = "terraform_user_test"
    }
    # alicloud_ram_login_profile.profile:
    resource "alicloud_ram_login_profile" "profile" {
        id                     = "terraform_user_test"
        mfa_bind_required      = true
        password               = (sensitive value)
        password_reset_required = false
        user_name              = "terraform_user_test"
    }
    # alicloud_ram_policy.policy:
    resource "alicloud_ram_policy" "policy" {
        attachment_count = 0
        default_version  = "v1"
        description      = "This is a policy test."
        document         = <<-EOT
            {
                "Statement": [
                    {
                        "Action": "ecs:*",
                        "Effect": "Allow",
                        "Resource":"*"
                    }
                ],
                "Version": "1"
            }
        EOT
    }
  2. Run terraform state list to list all created resources.

    [root@iZxxxmtZ ram]# terraform state list
    alicloud_ram_access_key.ak
    alicloud_ram_login_profile.profile
    alicloud_ram_policy.policy
    alicloud_ram_user.user
    alicloud_ram_user_policy_attachment.attach
  3. Run terraform state show <resource type>.<resource name> to view details of a specific resource.

    [root@iZxxx          tZ ram]# terraform state show alicloud_ram_user.user
    # alicloud_ram_user.user:
    resource "alicloud_ram_user" "user" {
        comments     = "Created by Terraform"
        display_name = "TestAccount"
        email        = "example@example.com"
        force        = true
        id           = "208475129836212018"
        mobile       = "86-18688888888"
        name         = "terraform_user_test"
    }
  4. Verify the resources in the Alibaba Cloud Management Console.

5.2 Manage resources

Terraform stores resource status and properties in the terraform.tfstate file. Use terraform state commands to manage state. Introduction to the state mechanism.

5.3 Modify resources

  1. Edit the resource definition in main.tf. For example, restrict the RAM user permissions to read-only ECS access.

    1. Run the vim main.tf command and press the i key to enter edit mode.

    2. Copy the following code and use it to replace the alicloud_ram_policy section in the main.tf file.

      resource "alicloud_ram_policy" "policy" {
        policy_name     = "tf-example-policy"
        policy_document = <<EOF
        {
          "Statement": [
            {
              "Action": [
                "ecs:Get*",
                "ecs:List*",
                "ecs:Describe*"
              ],
              "Effect": "Allow",
              "Resource":"*"
            }
          ],
            "Version": "1"
        }
        EOF
        description     = "This is a policy test."
      }
    3. Press Esc and enter :wq to save the file.

  2. Run terraform plan to preview the changes.

    Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the follow
      ~ update in-place
    Terraform will perform the following actions:
      # alicloud_ram_policy.policy will be updated in-place
      ~ resource "alicloud_ram_policy" "policy" {
            id                = "tf-example-policy"
            name              = "tf-example-policy"
          ~ policy_document   = <<-EOT
                {
                    "Statement": [
                        {
              -             "Action": "ecs:*",
              +             "Action": [
              +         "ecs:Get*",
              +         "ecs:List*",
              +         "ecs:Describe*"
              +             ],
                            "Effect": "Allow",
                            "Resource":"*"
                        }
                    ],
                        "Version": "1"
                }
            EOT
            # (8 unchanged attributes hidden)
            # (1 unchanged block hidden)
        }
    Plan: 0 to add, 1 to change, 0 to destroy.
  3. If the plan is correct, run terraform apply. When prompted, type yes to apply the changes.

    Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the follow
      ~ update in-place
    Terraform will perform the following actions:
      # alicloud_ram_policy.policy will be updated in-place
      ~ resource "alicloud_ram_policy" "policy" {
            id               = "tf-example-policy"
            name             = "tf-example-policy"
          ~ policy_document  = <<-EOT
                {
                    "Statement": [
                        {
              -             "Action": "ecs:*",
              +             "Action": [
              +   "ecs:Get*",
              +   "ecs:List*",
              +   "ecs:Describe*"
              +             ],
                            "Effect": "Allow",
                            "Resource":"*"
                        }
                    ],
                    "Version": "1"
                }
            EOT
            # (8 unchanged attributes hidden)
            # (1 unchanged block hidden)
        }
    Plan: 0 to add, 1 to change, 0 to destroy.
    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_ram_policy.policy: Modifying... [id-tf-example-policy]
    alicloud_ram_policy.policy: Modifications complete after 0s [id-tf-example-policy]
    Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

6. Destroy resources

Run terraform destroy to remove all resources created in the current working directory.

Important

If a policy has multiple versions, the terraform destroy command cannot delete it directly. Set force to true in alicloud_ram_policy to delete all policy versions. This also removes any associations with RAM users or roles. Use with caution.

Plan: 0 to add, 0 to change, 5 to destroy.
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_ram_access_key.ak: Destroying... [id=LTxxxGr]
alicloud_ram_login_profile.profile: Destroying... [id=terraform_user_test]
alicloud_ram_user_policy_attachment.attach: Destroying... [id=user:tf-example-policy:Custom:terraform_user_test]
alicloud_ram_user_policy_attachment.attach: Destruction complete after 0s
alicloud_ram_policy.policy: Destroying... [id=tf-example-policy]
alicloud_ram_login_profile.profile: Destruction complete after 0s
alicloud_ram_policy.policy: Destruction complete after 1s
alicloud_ram_access_key.ak: Destruction complete after 1s
alicloud_ram_user.user: Destroying... [id=2xxx18]
alicloud_ram_user.user: Destruction complete after 1s

Complete example

The following complete code combines all resources from this tutorial. Copy and run it directly.

variable "user_name" {
  default = "terraform_user_test"
}
variable "user_password" {
  default = "!Test@123456"
}
variable "user_display_name" {
  default = "TestAccount"
}
variable "user_mobile" {
  default = "86-18688888888"
}
variable "user_email" {
  default = "example@example.com"
}
resource "alicloud_ram_user" "user" {
  name         = var.user_name
  display_name = var.user_display_name
  mobile       = var.user_mobile
  email        = var.user_email
  comments     = "Created by Terraform"
  force        = true                   
}
resource "alicloud_ram_login_profile" "profile" {
  user_name = alicloud_ram_user.user.name
  password  = var.user_password
}
resource "alicloud_ram_access_key" "ak" {
  user_name   = alicloud_ram_user.user.name
  secret_file = "accesskey.txt"
}
resource "alicloud_ram_policy" "policy" {
  policy_name     = "tf-example-policy"
  policy_document = <<EOF
  {
    "Statement": [
      {
        "Action": "ecs:*",
        "Effect": "Allow",
        "Resource":"*"
      }
    ],
      "Version": "1"
  }
  EOF
  description     = "This is a policy test."
}
resource "alicloud_ram_user_policy_attachment" "attach" {
  policy_name = alicloud_ram_policy.policy.policy_name
  policy_type = alicloud_ram_policy.policy.type
  user_name   = alicloud_ram_user.user.name
}

References