Terraform Commands

Terraform is controlled by using a command-line interface (CLI). Terraform CLI is operated using a single command; terraform and it supports multiple subcommands to manage the lifecycle of infrastructure code. A deltain documentation of Terraform CLI is availbel at terraform.io

CLI Configuration File (.terraformrc)

This file applies per-user settings accross all Terraform projects. This file can be found in user's %APPDATA% directory on Windows with the name terraform.rc and on other operating systems it must be directly placed in the home directory of the user with the name .terraformrc.

Environment Variables

Terraform uses an optional set of environments to customize its behavior.

  • TF_LOG: If this is not set or set to an empty value, logging will be done to stderr, otherwise detail logs will be appear on stderr dependeing on the log level.

  • TF_LOG_PATH: Specify in which location the logs should be persisted.

  • TF_INPUT: This specifies the silent mode execution where it prevents prompts for variables that haven't had their values specified.

  • TF_VAR_name: This allows to set values to variables using Environment Variables.

  • TF_CLI_ARGS: This allows to specify additional arguments to the command line.

  • TF_DATA_DIR: Changes the location where Terraform keeps its per working directory data.

  • TF_IN_AUTOMATION: If set to any non-empty value, Terraform adjusts its output to avoid suggesting specific commands to run next.

  • TF_REGISTRY_DISCOVERY_RETRY: Configures the max number of request retries the remote registry.

  • TF_CLIT_CONFIG_FILE: Specify the location of the Terraform CLI configuration file.

Example

In this note I'm going to try out Terraform CLI to download a NodeJS Docker image from Docker Hub.

Let's start by creating our project,

> mkdir terraform-basics
> cd terraform-basics

First let's create our Terraform program by creating a file with name main.ts,

main.ts

# Download the node:lts-alpine3.9 Docker image
resource "docker_image" "node" {
  name = "node:lts-alpine3.9"
}

Then we can initialize our Terraform project,

> terraform init

Then we can validate our project,

> terraform validate

Terraform keeps it's providers downloaded in .terraform/plugin folder. The providers used in the configuration can be inspected by,

terraform providers

Our program can be organized a bit more by defining a plan,

> terraform plan  -out=tf-node-plan

Some useful flags for the plan command:

  • -out=path: Writes a plan file to the given path. This can be used as input to the "apply" command.

  • -var 'foo=bar': Set a variable in the Terraform configuration. This flag can be set multiple times.

Once we have created a plan, we can apply that to get going,

> terraform apply tf-node-plan

Once the apply went successfully we can start listing the Docker images,

> terraform show

Finally, we can destroy our resources when it is no longer needed,

> terraform destroy

Last updated