Contents


terraform init

Initializes a Terraform workspace. This command:

  • Configures the backend
  • Installs all providers and modules referred to in the configuration
  • Creates a version lock file (.terraform.lock.hcl) if one doesn’t already exist

Provider Resolution Order

When you initialize a workspace, Terraform resolves provider versions in the following order:

  1. Lock file exists — downloads the provider versions specified in .terraform.lock.hcl
  2. No lock file, required_providers exists — uses version constraints to determine the provider version and creates a new lock file
  3. Neither exists — searches for a matching provider and downloads the latest version

.terraform Directory

Terraform creates the .terraform directory to store the project’s providers and modules. These are used by validate, plan, and apply.

.terraform
├── modules
└── providers

Tip

Terraform only updates a remote module when you run terraform init -upgrade or terraform get.

Options

FlagDescription
-input=trueAsk for input if necessary. If false, will error if input was required.
-lock=falseDisable locking of state files during state-related operations.
-lock-timeout=<duration>Override the time Terraform will wait to acquire a state lock. Default is 0s (immediate failure if lock is held).
-no-colorDisable color codes in the command output.
-upgradeUpgrade modules and plugins as part of their respective installation steps.
-jsonEnables machine-readable JSON UI output.

terraform console

Usage: terraform console [options]

Provides an interactive command-line console for evaluating and experimenting with expressions.

Can also be used in non-interactive scripts by piping newline-separated commands to it. Only the output from the final command is printed unless an error occurs earlier.

$ echo 'split(",", "foo,bar,baz")' | terraform console
tolist([
  "foo",
  "bar",
  "baz",
])

terraform fmt

Formats Terraform configuration files to match the canonical format and style.


terraform validate

Validates the configuration files in a directory.

Warning

Does not validate remote services such as remote state or provider APIs.


terraform plan

The terraform plan command creates an execution plan, which lets you preview the changes that Terraform plans to make to your infrastructure.

By default, Terraform performs the following operations when it creates a plan:

  • Reads the current state of any already-existing remote objects to make sure that the Terraform state is up-to-date.
  • Compares the current configuration to the prior state and noting any differences.
  • Proposes a set of change actions that should, if applied, make the remote objects match the configuration.

You can use the optional -out=FILE option to save the generated plan to a file on disk, which you can later execute by passing the file to terraform apply as an extra argument.

Planning Modes

  • Destroy mode: creates a plan whose goal is to destroy all remote objects that currently exist, leaving an empty Terraform state. It is the same as running terraform destroy. Destroy mode can be useful for situations like transient development environments, where the managed objects cease to be useful once the development task is complete.

    Activate destroy mode using the -destroy command line option.

  • Refresh-only mode: creates a plan whose goal is only to update the Terraform state and any root module output values to match changes made to remote objects outside of Terraform. This can be useful if you’ve intentionally changed one or more remote objects outside of the usual workflow (e.g. while responding to an incident) and you now need to reconcile Terraform’s records with those changes.

    Activate refresh-only mode using the -refresh-only command line option.

Saved Plans

Generate a saved plan with the -out flag. You will review and apply this plan later in this tutorial.

$ terraform plan -out "tfplan"
data.aws_ami.ubuntu: Reading...
data.aws_ami.ubuntu: Read complete after 0s [id=ami-055744c75048d8296]
 
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:
 
  # random_pet.instance will be created
+ resource "random_pet" "instance" {
+     id        = (known after apply)
+     length    = 2
+     separator = "-"
  }
 
  # module.ec2-instance.aws_instance.main will be created
+ resource "aws_instance" "main" {
# ...
 
Plan: 4 to add, 0 to change, 0 to destroy.
 
───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 
Saved the plan to: tfplan
 
To perform exactly these actions, run the following command to apply:
    terraform apply "tfplan"

Terraform created a plan and saved it in the tfplan file.

You can apply the saved plan file to execute these changes, but the contents of the plan are not in a human-readable format. Use the terraform show command to print out the saved plan.

$ terraform show "tfplan"
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:
 
  # random_pet.instance will be created
+ resource "random_pet" "instance" {
+     id        = (known after apply)
+     length    = 2
+     separator = "-"
  }
# ...
  # module.hello.random_pet.server will be created
+ resource "random_pet" "server" {
+     id        = (known after apply)
+     keepers   = {
+         "hello"      = (known after apply)
+         "secret_key" = "secret"
      }
+     length    = 2
+     separator = "-"
  }
 
Plan: 4 to add, 0 to change, 0 to destroy.

terraform apply

The terraform apply command executes the operations proposed in a Terraform plan. When you run terraform apply without passing a saved plan file, Terraform automatically creates a new execution plan as if you had run terraform plan, prompts you to approve that plan, and performs the indicated operations.

When you approve the plan and apply this configuration, Terraform will:

  1. Lock your workspace’s state, so that no other instances of Terraform will attempt to modify your state or apply changes to your resources. If Terraform detects an existing lock file (.terraform.tfstate.lock.info), it will report an error and exit.
  2. Create a plan, and wait for you to approve it. Alternatively, you can provide a saved plan created with the terraform plan command, in which case Terraform will not prompt for approval.
  3. Execute the steps defined in the plan using the providers you installed when you initialized your configuration. Terraform executes steps in parallel when possible, and sequentially when one resource depends on another.
  4. Update your workspace’s state with a snapshot of the new state of your resources.
  5. Unlock your workspace’s state.
  6. Report the changes it made, as well as any output values defined in your configuration.

Errors during apply

When Terraform encounters an error during an apply step, it will:

  1. Log the error and report it to the console.
  2. Update the state file with any changes to your resources.
  3. Unlock the state file.
  4. Exit.

terraform destroy

The terraform destroy command deprovisions all objects managed by a Terraform configuration.