English

Share with friends

Note

Welcome to the Terraform Cheatsheet! This concise reference guide will help you navigate the world of Terraform and quickly find the commands and concepts you need.

Terraform Cheat Sheet: 36 Terraform CLI Commands with Examples cover image

Whether you're a beginner or an experienced user, this Terraform cheat sheet will be your go-to resource for Terraform development and operations.

Let's get started.

Get Help: 'terraform --help'

The --help flag displays the help documentation for Terraform, providing information on available commands, flags, and usage examples.

It serves as a handy reference when you need to explore different options and understand how to use Terraform effectively.

To get help for a specific Terraform command:

terraform <command> --help

Replace <command> with the specific command for which you need help.

Let's say you want to learn more about the terraform init command and its available options. Here's how to use the --help flag to seek help for 'terraform init'.

terraform init --help

To display the help option for the fmt command.

terraform fmt --help 

Also Read: Differences between Terraform and Pulumi

Show your Terraform Version: 'terraform version'

The terraform version command displays the version of Terraform installed on your system.

It provides information about the Terraform binary's version number, as well as additional details such as the Git commit hash and any other relevant build information.

For example, running the command terraform version will display the version information.

terraform version

The output of the above command will be:

terraform v1.0.3
on darwin_amd64
+ provider registry.terraform.io/hashicorp/aws v3.45.0

Format your Terraform Code: 'terraform fmt'

To format your Terraform code, you can use the terraform fmt command. It automatically rewrites your Terraform configuration files (.tf files) in a standardized and consistent format.

Here's the syntax of the 'terraform fmt' command.

terraform fmt [options] [DIR]

The terraform fmt command formats your Terraform configuration files according to a consistent style. It updates the files in place, modifying the original files with the formatted version.

  • [DIR]: Specifies the directory or path where the Terraform files are located. If not provided, it formats all .tf files in the current directory and its subdirectories.

  • --recursive: If specified, the formatting is applied recursively to all subdirectories under the specified directory.

Here is how an example of the 'terraform fmt' command.

terraform fmt

The above command formats all .tf files in the current directory.

Here's another example of the 'terraform fmt' command.

terraform fmt /path/to/directory

Use the above command to format all .tf files in a specific directory.

Let's look at another example.

terraform fmt -recursive /path/to/directory

The above command formats all .tf files in a specific directory and its subdirectories.

Here's another one.

terraform fmt -diff 

Use this command to display the differences between the original configuration files and formatting changes.

To ensure the configuration files are formatted correctly, use the command mentioned below.

terraform fmt -check 

If not formatted correctly, the exit status will be non-zero. If files are formatted correctly, the exit status will be 0.

Also Read: What is Infrastructure as Code (and top IaC Tools)

Initialize your Directory: 'terraform init'

The terraform init command in Terraform has several flags that provide additional functionality.

terraform init

The terraform init command initializes a Terraform working directory by setting up the environment, downloading necessary dependencies, and configuring the backend.

Here are the most commonly used flags with their descriptions:

  • -backend-config="path/to/backend.tfvars": Specifies the path to a backend configuration file. This file contains the configuration settings for the backend storage.
  • -get-plugins=true: Downloads and installs provider plugins but skips module installation.
  • -get-modules=false: Skips downloading and installing modules.
  • -verify-plugins=true: Verifies the authenticity of provider plugins before installation.
  • -reconfigure: Forces reconfiguration of the backend, even if it was already initialized.
  • -upgrade=true: Checks for available updates to provider plugins and installs them if found.
  • -input=true: It asks for the input for variables if not set directly.
  • -lock: Locks the state file when locking is supported by the backend.
  • -lock-timeout="5m": Sets the duration to wait for acquiring a state lock before timing out.
  • -no-color: Disables output colorization.
  • -from-module="MODULE_SOURCE": Initializes the working directory from a specific module source.

Here's an example of the 'terraform init' command.

terraform init -backend-config="path/to/backend.tfvars" -get=true -upgrade=true

Also Read: What are Init Containers - Features & Use Cases

Download and Install Modules: 'terraform get'

The command for downloading and installing modules specified in the Terraform configuration files is terraform get.

Here is its syntax.

terraform get [options] PATH
  • 'terraform get -update': To update installed modules.

  • '-no-color': Disable text coloring in the output.

Tip: The terraform get command is automatically executed during terraform init. You can use terraform get separately when you want to update or install modules without re-initializing the Terraform project.

Validate your Terraform Code: 'terraform validate'

This 'terraform validate' command is used to validate the syntax and configurations of Terraform files in your project. It ensures that the Terraform code is correctly written and follows the expected format.

By running terraform validate, you can catch potential errors or misconfigurations in your Terraform code early in the development process.

Let's look at a few examples of the 'terraform validate' command.

terraform validate -no-color

Use the above command to validate code and disable color output.

Here's another example.

terraform validate -json

The above command produces output in machine-readable JSON format, appropriate for integration with text editors and other automated applications. Color is always turned off.

Also Read: CI/CD Best Practices to Follow

Plan your Infrastructure: 'terraform plan'

The terraform plan command is used to create an execution plan for your infrastructure. It analyzes the Terraform configuration, reads the current state, and determines the actions needed to achieve the desired state.

The plan command is helpful for reviewing and validating your infrastructure changes before applying them, ensuring that the intended changes align with your expectations.

Let's look at some commonly used flags with the terraform plancommand.

  • -out=path: This flag allows you to save the execution plan to a specific file path for later reference or use with the terraform apply command. It generates a binary plan file that can be used to apply the exact changes described in the plan.

  • -detailed-exitcode: This flag returns an exit code that indicates the success or failure of the plan. A return code of 0 means the plan succeeded with no changes, 1 means there were changes, and 2 means there was an error.

Now, let's look at a few examples.

terraform plan

Use this command to display a summary of changes without saving the plan to a file.

Here's another example.

terraform plan -out=plan.binary

This command saves the plan to a specific file path.

Here's another example of the 'terraform plan' command.

terraform plan -detailed-exitcode

Use this command to get a detailed exit code indicating the success or failure of the plan.

Also Read: What is Helm?

Deploy your Infrastructure: 'terraform apply'

The terraform apply command is used to apply the changes defined in your Terraform configuration files to your infrastructure. It reads the configuration, creates an execution plan, and then prompts for confirmation before making any changes.

Let's look at some examples of the 'terraform apply' command, starting with the most standard form.

terraform apply

The above command applies changes with manual confirmation.

Here is the next example.

terraform apply -auto-approve

Use the above command to automatically approve changes without confirmation.

Let's look at another example.

terraform apply -var="region=us-west-1" -var="instance_type=t2.micro"

This command sets variable values from the command line.

Let's look at the next example.

terraform apply -var-file="variables.tfvars"

Use the above command to load variable values from a file.

And, here's one last example of this Terraform command.

terraform apply -state="path/to/state.tfstate"

This command performs operations on a specific state file.

Note

The terraform apply command should be used with caution, as it can make changes to your infrastructure. Always review the execution plan before applying changes, and ensure you have a backup of your Terraform state file for recovery purposes.

Destroy your Infrastructure: 'terraform destroy'

The terraform destroy command is used to destroy the infrastructure created by Terraform based on the defined configuration. It is a powerful command that should be used with caution, as it irreversibly destroys resources.

Here's the syntax of the above command.

terraform destroy [options]

Let's look at a few examples of the 'terraform destroy' command.

terraform apply -destroy

This above command is simply an alias for the 'terraform destroy' command.

Here's another example.

terraform plan -destroy

By running this command, you can preview the resources that will be destroyed when you eventually run 'terraform destroy'.

Note

The terraform apply -destroy option is only available in Terraform v0.15.2 and later. To acquire the effect of terraform apply -destroy in earlier versions, use terraform destroy.

Taint your Resources: 'terraform taint'

The terraform taint command is used to manually mark a specific resource managed by Terraform as tainted. Tainting a resource indicates that it needs to be destroyed and recreated on the next terraform apply run, regardless of its current state.

Use the following syntax while running the 'terraform taint' command.

terraform taint [options] <resource_address>

Here are a few flags that you can use.

  • -allow-missing: This option allows Terraform to taint a resource that is not found in the current state.

  • -lock-timeout: This option sets the lock timeout duration for acquiring a lock on the state file. It specifies the maximum amount of time to wait for the lock before timing out.

Now, let's look at a few example.

terraform taint aws_instance.example[0]

In this example, the aws_instance.example[0] resource is manually marked as tainted.

On the next terraform apply, Terraform will destroy and recreate this instance, applying any changes to its configuration or dependencies.

Here's another example of the 'terraform taint' command.

terraform taint -allow-missing -lock-timeout=5m aws_instance.example

In the above example, the aws_instance.example resource is manually marked as tainted, even if it is missing from the current state.

The lock timeout is set to 5 minutes, allowing Terraform to wait for the state lock.

Note

After using terraform taint, you need to run terraform apply to apply the changes and recreate the tainted resource.

Untaint your Resources: 'terraform untaint'

If Terraform currently considers a specific object to be tainted, but you've established that it's working properly and doesn't need to be changed, you can use the 'terraform untaint' command to remove the taint marker from that object.

This command will not change any real remote objects, but it will change the state to remove the tainted status.

Here's how to use this command.

terraform untaint [options] [address]

Let's look at a few examples of the 'terraform untaint' command.

terraform untaint -allow-misssing 

Even if the resource is not present, the command will succeed (exit code 0) if it is supplied.

Here is another example.

terraform untaint -lock=false

During the operation, don't hold a state lock. This is problematic if other people run commands against the same workspace at the same time.

Here's another example.

terraform untaint -lock-timeout=DURATION

Unless locking is disabled with '-lock=false', tells Terraform to retry acquiring a lock for a certain amount of time before throwing an error. The duration syntax is a number followed by a letter representing a time unit, such as "3s" for three seconds.

Refresh the State File: 'terraform refresh'

The syntax of the above command is

terraform refresh [options] 

OR, you can also use the alias,

terraform apply -refresh-only -auto-approve

It supports all of the same settings as 'terraform apply', with the exception that it does not accept a saved plan file, does not allow selecting a planning mode other than "refresh only," and always has -auto-approve enabled.

Also Read: The Only Docker Cheat Sheet You'll Ever Need

View your State File: 'terraform state show'

The terraform state show command is used to show the attributes and current state of a specific resource within the Terraform state.

Here's an example of the 'terraform state show' command.

terraform state show aws_instance.example

This example shows the state of the aws_instance.example resource. Replace aws_instance.example with the resource address you want to inspect.

Here is another example.

terraform state show module.example_module.aws_instance.example

This example shows the state of the aws_instance.example resource within the example_module module. Replace module.example_module.aws_instance.example with the appropriate resource address.

Here's another example.

terraform state show aws_s3_bucket.bucket

This example shows the state of the aws_s3_bucket.bucket resource. Replace aws_s3_bucket.bucket with the desired resource address.

Here's a sample output of the above command.

# aws_instance.example:
resource "aws_instance" "example" {
  ami           = "ami-0123456789"
  instance_type = "t2.micro"
  ...
}

The output displays the attributes and their corresponding values for the specified resource.

Now, look at another example of the 'terraform state' command with state file path.

terraform state show -state=path/to/state.tfstate aws_instance.example

Remember to replace path/to/state.tfstate with the actual path to your Terraform state file.

Here are a few variations of the above command according to different OSs.

For Linux, Mac OS, and UNIX:

terraform state show 'packet_device.worker["example"]'

For PowerShell:

terraform state show 'packet_device.worker["example"]'

For Windows cmd.exe:

terraform state show packet_device.worker["example"]

Also Read: Kubectl Cheat Sheet

Manipulate your State File: 'terraform state list'

The terraform state list command lists all the resource addresses present in the Terraform state. It reads the state file and displays a simple list of all the resources tracked by Terraform.

terraform state list

This command will output a list of resource addresses like:

aws_instance.example
aws_s3_bucket.bucket
module.example_module.aws_instance.example
Note

The terraform state list command requires a valid Terraform state file to be present in the current directory. If your Terraform state file is stored remotely or in a non-default location, you can use the -state flag to specify the path to the state file.

Let's look at this example of the 'terraform state list' command with state file path.

terraform state list -state=path/to/state.tfstate

Remember to replace path/to/state.tfstate with the actual path to your Terraform state file.

Import Existing Infrastructure into Your Terraform State: 'terraform import'

The terraform import command in Terraform is used to import existing resources into the Terraform state. It allows you to take control of resources that were not created by Terraform and include them in your infrastructure management workflow.

Here's how you can use the terraform import command.

Command: terraform import [options] ADDRESS ID

The terraform import command associates an existing resource with a specific address in the Terraform configuration and imports its state into the Terraform state file.

The ADDRESS argument represents the resource address within the Terraform configuration where you want to import the resource. The ID argument is the unique identifier or name of the existing resource you want to import.

Now, let's look at an example of the 'terraform import' command.

terraform import aws_instance.example i-0123456789abcdef0

In this example, an existing AWS EC2 instance with the ID i-0123456789abcdef0 is imported into the aws_instance.example resource in the Terraform state.

Terraform will map the existing resource to the specified address and include it in future state management operations.

Note

The terraform import command only imports the existing resource into the state. It does not create or modify the resource itself. You are responsible for defining the resource's configuration in the Terraform configuration file.

Here is an option with the terraform importcommand: `-state=path'. This option allows you to specify a custom path to the Terraform state file if it is stored in a non-default location.

Now let's look at an example.

terraform import -state=path/to/state.tfstate aws_instance.example i-0123456789abcdef0

In this example, the aws_instance.example resource is imported into the state file located at path/to/state.tfstate.

Note

When importing resources, it's important to ensure that the imported resource's configuration in the Terraform state matches the actual resource's configuration. Review and update the Terraform configuration file accordingly to avoid any discrepancies.

Get Provider Information: 'terraform providers'

The terraform providers command is used to display information about the installed providers and their versions in your Terraform environment.

terraform providers

When you run terraform providers, it scans the configuration files and looks for provider blocks, which define the providers used in your Terraform project.

It then displays information such as the provider name, version, and the provider's configuration details.

Here's a sample example of an output of the 'terraform providers' command.

Providers required by configuration:
  - provider "aws" (hashicorp/aws) 3.50.0
Note

The terraform providers command requires a valid Terraform configuration in the current directory. It looks for provider blocks defined in the configuration files (e.g., main.tf, variables.tf, etc.) to determine the installed providers.

Manage your Workshop: 'terraform workspace'

The terraform workspace command is used to manage workspaces in Terraform. Workspaces allow you to organize and isolate your Terraform state and configuration for different environments or deployments.

Here is the first syntax of this command.

terraform workspace new <name>

And an example:

terraform workspace new dev

In this example, a new workspace named "dev" is created, and Terraform switches to that workspace.

Here's another syntax of this command.

terraform workspace select <name>

Here's an example.

terraform workspace select staging

In the above example, Terraform switches to the "staging" workspace, allowing you to manage the state and configuration specific to the staging environment.

Here's another way to use the 'terrform workspace' command.

terraform workspace list

The terraform workspace list command lists all the available workspaces in the current Terraform configuration. It shows the names of the existing workspaces.

The above command will generate the following output.

default
dev
staging
production

To see the current workspace name, use:

terraform workspace show 

Now, here are a few other formats of the 'terraform workspace' command.

  • terraform workspace select <workspace name> - Selects a specified workspace.

  • terraform workspace new <workspace name> - Creates a new workspace with a specified name.

  • terraform workspace delete <workspace name> - Deletes a specified workspace.

These are the basic subcommands of the terraform workspace command. Each workspace has its own separate state and configuration, allowing you to work on them independently.

Note

The default workspace is created automatically when you initialize your Terraform configuration.

View your Outputs: 'terraform output'

The terraform output command is used to display the output values defined in your Terraform configuration.

Output values are used to expose specific information or results from your infrastructure deployment, such as IP addresses, URLs, or configuration values that might be useful to other parts of your system.

Let's look at the command and sample output.

terraform output

Example output:

output_name = output_value

The output shows the name of the output (output_name) and its corresponding value (output_value).

You can also retrieve the value of a specific output by specifying its name as an argument to the command. For example:

terraform output output_name
Note

The terraform output command requires a valid Terraform state file to be present in the current directory. If your Terraform state file is stored remotely or in a non-default location, you can use the -state flag to specify the path to the state file.

Here is an example of the 'terraform output' with state file path:

terraform output -state=path/to/state.tfstate

Remember to replace path/to/state.tfstate with the actual path to your Terraform state file.

Release a Lock on Your Workspace: 'terraform force-unlock'

The terraform force-unlock command is used to remove a Terraform lock on a state file, which may have been left behind due to a previous interrupted or failed Terraform operation.

Use the above command in the syntax shown below.

terraform force-unlock [options] LOCK_ID

To successfully run terraform force-unlock, you need to be sure that no other Terraform process or user is currently working with the locked state.

Removing a lock that is still in use by another Terraform operation can lead to conflicts and data corruption.

Let's look at an example:

terraform force-unlock my-terraform-state/terraform.tfstate.lock

Log in and Log out to a Remote Host (Terraform Cloud)

The terraform login command is used to authenticate and authorize Terraform to access remote services and providers that require authentication.

Here's the syntax to log in to the specified host.

terraform login <hostname>

Now let's break it down.

terraform login 

This collects an API token for the Terraform cloud (app.terraform.io) using a browser.

The terraform logout command is used to remove credentials stored by terraform login. These credentials are API tokens for Terraform Cloud, Terraform Enterprise, or any other host that offers Terraform services.

terraform logout

This command will log you out of Terraform Cloud.

terraform logout <hostname>

This command, however, will log you out of the specified hostname. For example, to log out of Terraform Enterprise, you would use the following command:

terraform logout app.terraform.io

Produce a Dependency Diagram: 'terraform graph'

The terraform graph command in Terraform has some associated flags and options that can be used to modify its behavior and customize the generated resource dependency graph. Here are the commonly used flags and options:

Here is how to use the 'terraform graph' command.

terraform graph [options]

Now, let's look at a few flags and options.

  • -draw-cycles: This flag tells Terraform to draw cycles in the graph as solid lines instead of dashed lines. Cycles occur when there are circular dependencies between resources. By default, cycles are represented with dashed lines in the graph.

  • -module-depth=n: This option limits the depth of modules to be included in the graph. It specifies the number of levels of modules that should be traversed and displayed in the graph. By default, all modules are included in the graph.

  • -plan=path: This option specifies the path to a Terraform plan file. If provided, the graph will include the changes from the plan file, highlighting the added, modified, and destroyed resources.

Let's look at an example.

terraform graph -draw-cycles -module-depth=2 -type-filter=aws_instance

Test your Expressions: 'terraform console'

The terraform console command in Terraform opens an interactive console where you can evaluate expressions and access Terraform-specific functions and variables.

Here's how to use this command.

terraform console [options]
echo 'split(",", "foo,bar,baz")' | terraform console
Note

The 'terraform console' accepts the legacy command line option -state.

Also Read: What is Configuration as Code - Tools & Best Practices

TL;DR: Let's Summarize this Terraform Cheat Sheet

  1. terraform init: Initialize a new or existing Terraform working directory.

  2. terraform plan: Generate and show an execution plan for changes to infrastructure.

  3. terraform apply: Apply the changes required to reach the desired state of the configuration.

  4. terraform destroy: Destroy the Terraform-managed infrastructure.

  5. terraform validate: Validate the configuration files in a directory.

  6. terraform output: Read an output variable from a Terraform state file.

  7. terraform refresh: Update the state file against real resources.

  8. terraform import: Import existing infrastructure into Terraform.

  9. terraform taint: Mark a resource instance as tainted, forcing it to be destroyed and recreated on the next apply.

  10. terraform untaint: Remove the tainted state from a resource instance.

  11. terraform state list: List resources within a Terraform state.

  12. terraform state show: Show the attributes of a single resource in the Terraform state.

  13. terraform state rm: Remove a resource from the Terraform state.

  14. terraform state mv: Move an item within the Terraform state.

  15. terraform fmt: Rewrites Terraform configuration files to a canonical format.

  16. terraform get: Download and install modules for the configuration in the current directory.

  17. terraform graph: Create a visual representation of a Terraform configuration or execution plan.

  18. terraform import: Import existing infrastructure into Terraform.

  19. terraform providers: Prints a tree of the providers used in the configuration.

  20. terraform show: Inspect Terraform state or plan.

  21. terraform force-unlock: Release a stuck lock on the current workspace/state.

  22. terraform workspace: Workspace management.

  23. terraform version: Prints the Terraform version.

  24. terraform console: Interactive console for evaluating Terraform expressions.

  25. terraform debug: Debug output management.

  26. terraform state mv: Move an item within the Terraform state.

  27. terraform state pull: Fetch and output the state from a remote backend.

  28. terraform state push: Update remote state from a local state file.

  29. terraform state replace-provider: Remove provider instances from the terraform.tfstate file.

  30. terraform workspace new: Create a new workspace.

  31. terraform workspace list: List workspaces.

  32. terraform workspace show: Show the current workspace.

  33. terraform workspace select: Select a workspace.

  34. terraform workspace delete: Delete a workspace.

  35. terraform providers: Prints a tree of the providers used in the configuration.

  36. terraform graph: Create a visual representation of a Terraform configuration or execution plan.

Happy Terraforming!

Share with friends

Priyansh Khodiyar's profile

Written by Priyansh Khodiyar

Priyansh is the founder of UnYAML and a software engineer with a passion for writing. He has good experience with writing and working around DevOps tools and technologies, APMs, Kubernetes APIs, etc and loves to share his knowledge with others.

Further Reading

Life is better with cookies 🍪

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt out if you wish. Cookie Policy