Cheatsheets

Terraform Cheatsheet

Terraform Cheatsheet

Practical Terraform cheatsheet covering essential CLI commands, state management, import, workspaces, and key HCL patterns for variables, locals, outputs, dynamic blocks, and more. Perfect for daily IaC workflows.

7 Categories 12 Sections 28 Examples
Terraform HCL state management IaC variables modules

Core CLI Commands

Essential Terraform commands for initialization, validation, planning, applying, and destroying infrastructure.

Initialization & Validation

Commands to set up your Terraform workspace and check configuration validity.

Initializes the working directory, downloads providers and modules.

Code
Terminal window
terraform init
Output
Terraform has been successfully initialized!

Checks whether the configuration is valid (run after init).

Code
Terminal window
terraform validate
Output
Success! The configuration is valid.

Upgrades modules and providers to the latest allowed versions.

Code
Terminal window
terraform init -upgrade

Plan & Apply

Preview and execute infrastructure changes safely.

Shows what Terraform will create, change, or destroy.

Code
Terminal window
terraform plan

Saves the plan to a file for later apply.

Code
Terminal window
terraform plan -out=plan.tfplan

Applies a saved plan without prompting.

Code
Terminal window
terraform apply plan.tfplan

Applies changes without confirmation (use in CI/CD).

Code
Terminal window
terraform apply -auto-approve

Destroy

Safely remove all managed infrastructure.

Destroys all resources managed by Terraform.

Code
Terminal window
terraform destroy

Destroys only the targeted resource.

Code
Terminal window
terraform destroy -target=aws_instance.example

State Management

Commands for inspecting, manipulating, and synchronizing Terraform state.

State Commands

Core operations on the Terraform state file.

Lists all resources currently tracked in state.

Code
Terminal window
terraform state list

Shows detailed attributes of a specific resource in state.

Code
Terminal window
terraform state show aws_instance.example

Moves or renames a resource in state without recreating it.

Code
Terminal window
terraform state mv aws_instance.old aws_instance.new

Removes a resource from state (does not delete the actual infrastructure).

Code
Terminal window
terraform state rm aws_instance.example

Import & Taint

Bring existing resources under management and force recreation.

Imports an existing EC2 instance into Terraform state.

Code
Terminal window
terraform import aws_instance.example i-1234567890abcdef0

Replaces (recreates) a resource on the next apply (preferred over taint).

Code
Terminal window
terraform apply -replace=aws_instance.example

State Pull & Push

Synchronize local and remote state files.

Downloads the current remote state.

Code
Terminal window
terraform state pull

Uploads a local state file to the remote backend.

Code
Terminal window
terraform state push state.tfstate

Workspaces

Manage multiple isolated state environments (dev, staging, prod) with the same code.

Workspace Commands

Create, switch, list, and delete workspaces.

Creates and switches to a new workspace named 'dev'.

Code
Terminal window
terraform workspace new dev

Lists all workspaces (* indicates current).

Code
Terminal window
terraform workspace list

Switches to the 'prod' workspace.

Code
Terminal window
terraform workspace select prod

Deletes the 'dev' workspace (must not be current).

Code
Terminal window
terraform workspace delete dev

HCL Essentials

Core HashiCorp Configuration Language patterns used in every Terraform project.

Variables, Locals & Outputs

Input variables, computed locals, and exposed outputs.

Defines a variable with default, a local for reuse, and an output.

Code
Terminal window
variable "region" {
type = string
default = "us-east-1"
}
locals {
common_tags = {
Environment = var.environment
ManagedBy = "Terraform"
}
}
output "vpc_id" {
value = aws_vpc.main.id
description = "The ID of the VPC"
}

Data Sources

Read-only queries for external data.

Fetches the latest Ubuntu AMI for use in resources.

Code
Terminal window
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
}

Dynamic Blocks & for_each

Advanced HCL patterns for repeatable configuration.

for_each & Dynamic Blocks

Create multiple resource instances and nested blocks dynamically.

Creates one IAM user per item in the set using for_each.

Code
Terminal window
resource "aws_iam_user" "users" {
for_each = toset(["alice", "bob"])
name = each.key
}

Generates multiple ingress blocks dynamically from a list/map.

Code
Terminal window
resource "aws_security_group" "example" {
name = "example"
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
}
}
}

Provider Configuration

Common patterns for configuring Terraform providers.

Provider Patterns

Declaring and configuring providers, including aliases.

Required providers block and basic + aliased configuration.

Code
Terminal window
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.region
}
# Aliased provider for multi-region
provider "aws" {
alias = "west"
region = "us-west-2"
}

Debugging

Tools and techniques for troubleshooting Terraform issues.

Logging & Terraform Console

Enable detailed logs and test expressions interactively.

Enables the most verbose logging (TRACE, DEBUG, INFO, WARN, ERROR).

Code
Terminal window
TF_LOG=TRACE terraform plan

Interactive REPL to test expressions and functions.

Code
Terminal window
terraform console
Output
> join(", ", ["a", "b"])
"a, b"
Related Posts

You might also enjoy

Check out some of our other posts on similar topics

Docker Swarm

Docker Swarm Cheatsheet This cheatsheet provides a comprehensive reference for managing Docker Swarm clusters, services, and stacks. It covers essential commands and best practices for scaling, upd

Docker

Docker Docker is a containerization platform that packages applications with their dependencies into isolated, portable environments called containers. It enables developers to build, ship, and run

Helm

Helm Helm is the package manager for Kubernetes that simplifies the deployment, management, and upgrade of applications. It uses charts templated Kubernetes manifests to enable reusable, configurab

Kubernetes

Kubernetes Kubernetes is the de facto standard for container orchestration. It automates deployment, scaling, and management of containerized applications across clusters of machines, providing dec

YAML

YAML YAML (YAML Ain't Markup Language) is a human-friendly data serialization language widely used for configuration files, data exchange, and infrastructure-as-code. It emphasizes readability and

Chef

Chef Quick Reference Cheatsheet Chef is a powerful Infrastructure as Code platform for automating infrastructure configuration, deployment, and management. This cheatsheet provides comprehensive re

6 related posts