Terraform Commands

更新时间:
复制 MD 格式

Run Terraform commands from the directory that contains your root module. This topic covers the five commands you use most often:

  • terraform init: Downloads and installs the required provider plugin to initialize the working directory.

  • terraform plan: Previews what Terraform will create, modify, or destroy before you run terraform apply.

  • terraform apply: Creates or updates infrastructure resources.

  • terraform destroy: Destroys all managed infrastructure resources.

  • terraform fmt: Reformats configuration files to the canonical style.

image

Init

terraform init is the first command to run after writing a new Terraform configuration. It downloads and installs the Alibaba Cloud provider plugin and other supporting files into a hidden .terraform subdirectory in the current working directory.

Declare the required provider in your configuration:

terraform {
  required_providers {
    alicloud = {
      source = "aliyun/alicloud"
      version = "1.225.0"
    }
  }
}

The source attribute tells Terraform where to download the provider plugin.

Terraform uses a plugin-based architecture: each provider is a standalone binary, distributed independently from Terraform itself. terraform init automatically downloads and installs the provider binaries declared in your configuration — in this example, the alicloud provider.

During initialization, Terraform prints an "Initializing provider plugins" message as it locates and downloads the specified provider version:

$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding aliyun/alicloud versions matching "1.225.0"...
- Reusing previous version of hashicorp/alicloud from the dependency lock file
- Installing aliyun/alicloud v1.225.0...
- Installed aliyun/alicloud v1.225.0 (verified checksum)
...
Terraform has been successfully initialized!

The output confirms the installed provider version — 1.225.0 in this example. terraform init is idempotent and safe to re-run at any time.

Plan

terraform plan creates an execution plan that previews what Terraform will create, modify, or destroy when you run terraform apply.

When you run terraform plan, Terraform:

  1. Reads the current state of any existing remote resources to ensure the Terraform state is up-to-date.

  2. Compares the current configuration against the prior state and identifies differences.

  3. Proposes an execution plan to bring the infrastructure in line with the configuration.

Use terraform plan to verify expected behavior before committing your configuration to version control.

After you run terraform plan, the values specified in your configuration file — such as vpc_id, cidr_block, zone_id, and vswitch_name — appear as attributes in the execution plan output:

resource "alicloud_vswitch" "main_vswitch" {
  vpc_id       = "vpc-2zekfrr69r6qmotbmru1m"
  cidr_block   = "10.0.1.0/24"
  zone_id      = "cn-hangzhou-k"
  vswitch_name = "main-vswitch"
}

The symbol next to each resource indicates the action Terraform will take:

  • Plus sign (+)

    Terraform will create the resource. The plan lists the attributes that will be set.

  • Minus/plus sign (-/+)

    Terraform will destroy and recreate the resource rather than update it in place.

  • Tilde (~)

    Terraform will update the resource attributes in place.

  • Minus sign (-)

    Terraform will destroy the resource.

To save the plan to a file and apply it later, use the -out=<filename> flag:

$ terraform plan -out=tf.tfplan

Pass the saved plan file to terraform apply to execute it without prompting for confirmation.

Apply

terraform apply executes a plan and provisions the infrastructure. It creates resources and establishes the dependencies between them.

There are two ways to run terraform apply:

  1. Apply a saved plan file. Save a plan with terraform plan -out=tf.tfplan, then pass the file to terraform apply. Terraform applies the plan immediately, without prompting for confirmation:

$ terraform apply tf.tfplan
  1. Generate and apply a new plan. Run terraform apply without arguments. Terraform generates a plan, displays the proposed changes, and waits for your confirmation before proceeding.

If anything in the plan looks incorrect or unsafe, enter anything other than yes to abort — your infrastructure remains unchanged.

resource "alicloud_vswitch" "main_vswitch" {
  vpc_id        = "vpc-2zekfrr69r6qmotbmru1m"
  cidr_block    = "10.0.1.0/24"
  zone_id       = "cn-hangzhou-k"
  vswitch_name = "main-vswitch"
}
$ terraform apply
Terraform will perform the following actions:
  # alicloud_vswitch.main_vswitch will be created
  + resource "alicloud_vswitch" "main_vswitch" {
    + cidr_block       = "10.0.1.0/24"
      + vpc_id         = "vpc-bp1y88bqtlunfdvvctuuy"
      + vswitch_name   = "main-vswitch"
      + zone_id        = "cn-hangzhou-k"
      + …
    }
Plan: 1 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

If terraform apply fails, read the error message and resolve the issue before re-running the command.

Destroy

terraform destroy removes all resources managed by your Terraform configuration. It is the inverse of terraform apply.

Use terraform destroy with caution: it permanently deletes infrastructure and any associated data. For example, if an OSS bucket contains data, that data cannot be recovered after destruction.

Terraform supports three ways to destroy resources:

  1. Run terraform destroy directly.

    Terraform displays the destruction plan and waits for your confirmation before proceeding. If anything looks incorrect, abort the operation — your infrastructure remains unchanged.

    $ terraform destroy
    Terraform will perform the following actions:
      # alicloud_vswitch.main_vswitch will be destroyed
      - resource "alicloud_vswitch" "main_vswitch" {
          - cidr_block    = "10.0.1.0/24" -> null
          - id            = "vsw-bp1svwz2meo2mqj8c9ewz" -> null
          - vpc_id        = "vpc-bp1y88bqtlunfdvvctuuy" -> null
          - vswitch_name  = "main-vswitch" -> null
          - zone_id       = "cn-hangzhou-k" -> null
          - ...
        }
    Plan: 0 to add, 0 to change, 1 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_vswitch.main_vswitch: Destroying... [id=vsw-bp1svwz2meo2mqj8c9ewz]
    alicloud_vswitch.main_vswitch: Destruction complete after 4s
    Destroy complete! Resources: 1 destroyed.
  2. Generate a destruction plan with terraform plan -destroy.

    Use the -destroy flag to generate a destruction plan, then execute it with terraform apply.

$ terraform plan -destroy -out=tf.tfplan

To destroy a specific resource, add the -target=resource flag.

  1. Remove resource configurations and apply.

    Delete the resource definitions from your Terraform configuration, then run terraform plan and terraform apply to destroy those resources.

Terraform determines the destruction order based on resource dependencies. For example, if a vSwitch contains an ECS instance or an RDS instance, Alibaba Cloud prevents the vSwitch from being deleted directly. Terraform destroys the dependent instances first, then destroys the vSwitch.

Destroying production infrastructure is uncommon, but terraform destroy is particularly useful when managing multiple short-lived environments such as development, test, and pre-release. Use it to clean up temporary resources when those environments are no longer needed.

Format

terraform fmt reformats HCL configuration files to the canonical style, so you do not need to apply formatting rules manually.

Follow these conventions when writing HCL:

  • Place meta-arguments at the beginning or end of a block, separated from other arguments by a blank line.

    Meta-arguments are special arguments in the HashiCorp Configuration Language (HCL), such as count and for_each.

  • Indent arguments two spaces within a block definition.

  • Align equal signs when a block has two or more arguments.

  • Place nested blocks after all other arguments in the block.

  • Separate multiple blocks with blank lines to improve readability.

# Incorrect example
resource "alicloud_instance" "instance" {
  data_disks {    # Nested block is at the top
    size     = 20
    category = "cloud_efficiency"
  }
  count = 10    # Meta-parameter is in the middle
  instance_name="terraform-example"   # Equal signs are not aligned
  …
}
# Correct example
resource "alicloud_instance" "instance" {
  count  = 10    # Meta-parameter is at the top
  instance_name = "terraform-example"   # Equal signs are aligned
  …
  data_disks {    # Nested block is at the bottom
    size     = 20
    category = "cloud_efficiency"
  }
}

Run terraform fmt on your configuration directory before committing changes to keep formatting consistent across your team.