Cheatsheet - Terraform CLI / OpenTofu CLI
Terraform is an Infrastructure as Code (IaC) tool that lets you define and provision infrastructure using HCL (HashiCorp Configuration Language).
For Terraform and Tofu Configurations, check out Cheatsheet - Terraform page.
1. Initialize Working Directory (terraform init
)
This command prepares your working directory for other Terraform operations. It downloads necessary provider plugins and modules, and sets up the backend for state storage.
- Purpose: Download providers and modules, configure backend.
- Syntax:
terraform init [options]
- Key Options:
-upgrade
: Upgrade modules and provider plugins to their newest available versions.-backend=false
: Do not configure a backend for state storage.-reconfigure
: Forget any existing backend configuration and re-initialize it.-input=false
: Disable interactive prompts for input.
- Example:
terraform init # Initialize the current directory terraform init -upgrade # Initialize and upgrade providers/modules
2. Generate Execution Plan (terraform plan
)
This command creates an execution plan, showing exactly what Terraform will do to achieve the desired state defined in your configuration files. It does not make any changes to real infrastructure.
- Purpose: Preview changes before applying them.
- Syntax:
terraform plan [options]
- Key Options:
-out=tfplan
: Save the generated plan to a file for later execution withterraform apply
.-var 'key=value'
: Set a specific input variable.-var-file=file.tfvars
: Load variable definitions from a.tfvars
file.-destroy
: Create a plan to destroy all resources.-refresh-only
: Only update the state from the remote system without proposing configuration changes.
- Example:
terraform plan # Show a plan terraform plan -out=my_app.tfplan # Save plan to a file terraform plan -var 'region=us-west-2' # Plan with a specific variable terraform plan -var-file=prod.tfvars # Plan using a variable file
3. Apply Changes (terraform apply
)
This command executes the actions proposed in a Terraform plan to provision or modify infrastructure. It will prompt for confirmation unless -auto-approve
is used.
- Purpose: Create, update, or delete infrastructure resources.
- Syntax:
terraform apply [options] [planfile]
- Key Options:
-auto-approve
: Skip interactive approval of the plan. Use with caution in production.-var 'key=value'
: Set a specific input variable.-var-file=file.tfvars
: Load variable definitions from a.tfvars
file.
- Example:
terraform apply # Apply changes (requires confirmation) terraform apply my_app.tfplan # Apply a previously saved plan terraform apply -auto-approve # Apply changes without confirmation
4. Destroy Infrastructure (terraform destroy
)
This command tears down all resources managed by the current Terraform configuration. Use with extreme caution, as it permanently deletes resources. It will prompt for confirmation unless -auto-approve
is used.
- Purpose: Decommission all managed infrastructure.
- Syntax:
terraform destroy [options]
- Key Options:
-auto-approve
: Skip interactive approval.-var 'key=value'
: Set a specific input variable.-var-file=file.tfvars
: Load variable definitions from a.tfvars
file.
- Example:
terraform destroy # Destroy resources (requires confirmation) terraform destroy -auto-approve # Destroy without confirmation
5. State Management (terraform state
)
The terraform state
command family allows you to inspect and modify the Terraform state file, which is a critical component mapping your configuration to real-world resources.
terraform state list
- Purpose: List all resources currently tracked in the state file.
- Example:
terraform state list
terraform state show <address>
- Purpose: Display the attributes of a specific resource instance from the state file.
- Example:
terraform state show aws_instance.web
terraform state mv <source_address> <destination_address>
- Purpose: Move a resource or multiple resource instances to a new address. Useful for refactoring your configuration.
- Example:
terraform state mv 'aws_instance.old_name' 'aws_instance.new_name'
terraform state rm <address>
- Purpose: Remove a resource from the state file. This does not destroy the actual resource in the cloud, only removes Terraform's management of it.
- Example:
terraform state rm 'aws_instance.unmanaged_instance'
terraform state replace-provider <old_provider_address> <new_provider_address>
(Terraform >= 1.7)- Purpose: Safely replace all references to a given provider in the state. Useful when migrating providers (e.g., from HashiCorp's to OpenTofu's registry mirror).
- Example:
terraform state replace-provider 'registry.terraform.io/hashicorp/aws' 'registry.opentofu.org/hashicorp/aws'
6. Workspace Management (terraform workspace
)
Workspaces allow you to manage multiple distinct states for a single Terraform configuration. This is often used for environments like dev
, staging
, prod
.
terraform workspace list
- Purpose: List all existing workspaces.
- Example:
terraform workspace list
terraform workspace show
- Purpose: Display the name of the current workspace.
- Example:
terraform workspace show
terraform workspace new <name>
- Purpose: Create a new workspace and switch to it.
- Example:
terraform workspace new dev
terraform workspace select <name>
- Purpose: Switch to an existing workspace.
- Example:
terraform workspace select prod
terraform workspace delete <name>
- Purpose: Delete an empty workspace.
- Example:
terraform workspace delete old_test_env
7. Validation & Formatting
Commands for maintaining code quality and correctness.
terraform validate
- Purpose: Check configuration files for syntax validity, consistent argument types, and other internal consistency issues.
- Example:
terraform validate
terraform fmt [path]
- Purpose: Rewrite configuration files to a canonical format, improving readability and consistency.
- Key Options:
-check
: Check if files are formatted, but do not rewrite them.-diff
: Display differences between current and canonical format.-recursive
: Recurse into subdirectories.
- Example:
terraform fmt # Format all .tf files in current directory terraform fmt -recursive # Format files in current and subdirectories terraform fmt -check -diff # Check and show diff without applying
8. Inspecting Configuration & Providers
Helpful commands for understanding your configuration and the providers it uses.
terraform graph
- Purpose: Generate a visual graph of your Terraform resources and their dependencies.
- Example:
terraform graph | dot -Tpng > graph.png
(Requiresgraphviz
to be installed for PNG output)
terraform providers schema -json
- Purpose: Print the full schema of all providers used in the current configuration, in JSON format.
- Example:
terraform providers schema -json | jq .
(Requiresjq
for pretty printing)
terraform console
- Purpose: Open an interactive console for evaluating expressions defined in your configuration.
- Example:
terraform console > var.region "us-east-1" > join("-", ["prefix", "suffix"]) "prefix-suffix"
9. General Utility
terraform version
- Purpose: Print the Terraform CLI version and the versions of installed providers.
- Example:
terraform version
terraform output [name]
- Purpose: Display output values from the state file.
- Key Options:
-json
: Output in JSON format.-raw
: Output a single value without formatting.
- Example:
terraform output # List all outputs terraform output instance_ip # Show a specific output terraform output -json # Show all outputs as JSON
terraform refresh
- Purpose: Update the state file with the real-world infrastructure's current attributes. (This is implicitly run by
plan
andapply
by default). - Example:
terraform refresh
- Purpose: Update the state file with the real-world infrastructure's current attributes. (This is implicitly run by
OpenTofu CLI (tofu
)
The OpenTofu CLI is designed to be a drop-in replacement for the Terraform CLI (up to the point of the fork).
- All commands, options, and syntax shown above generally apply directly to
tofu
. - The primary difference lies in the default provider registry: OpenTofu uses
registry.opentofu.org
, whereas Terraform usesregistry.terraform.io
. You might need to adjust yourrequired_providers
blocks or usetofu state replace-provider
when migrating existing configurations.
Example with OpenTofu:
# main.tf (for OpenTofu)
terraform { # Or tofu if supported by a future version
required_providers {
aws = {
source = "registry.opentofu.org/hashicorp/aws"
version = "~> 5.0"
}
}
}
# ... rest of your configuration
Then, you would run:
tofu init
tofu plan
tofu apply