Terraform Cheat Sheet
Quick reference for Terraform CLI commands, HCL patterns, state management, and module best practices.
Deep dive: Terraform Section | Terraform State | Terraform Modules
Terraform vs OpenTofu
HashiCorp moved Terraform from MPL 2.0 to the Business Source License in August 2023 (v1.6+); IBM completed its acquisition of HashiCorp in February 2025. OpenTofu is the MPL-licensed fork of Terraform 1.5, hosted by the Linux Foundation / CNCF. The CLI is tofu instead of terraform and nearly everything on this sheet works the same. OpenTofu-only extras include client-side state encryption (1.7), for_each on provider blocks (1.9), early evaluation of variables in backend and module source blocks (1.8), and -exclude (1.9). Newer Terraform-only features (e.g. HCP Terraform Stacks) may not exist in OpenTofu. Pick one per repo: state files and lock files are compatible today, but the two are slowly diverging.
CLI Commands
Core Workflow
| Command | Description |
|---|---|
terraform init | Initialize working directory, download providers |
terraform init -upgrade | Upgrade provider versions |
terraform plan | Preview changes without applying |
terraform plan -out=plan.tfplan | Save plan to file |
terraform apply | Apply changes (interactive approval) |
terraform apply plan.tfplan | Apply saved plan (no prompt) |
terraform apply -auto-approve | Apply without prompting |
terraform destroy | Destroy all managed resources |
terraform destroy -target=aws_s3_bucket.logs | Destroy specific resource |
terraform plan -destroy | Preview a destroy |
terraform plan -replace=aws_instance.web | Plan a forced replacement (replaces taint) |
terraform plan -refresh=false | Skip refreshing state (faster, may miss drift) |
terraform plan -var-file=prod.tfvars -lock-timeout=5m | Wait for a held state lock instead of failing |
terraform apply -parallelism=20 | Concurrent operations (default 10) |
terraform init -backend-config=prod.s3.tfbackend | Supply backend settings from a file (partial config) |
terraform init -reconfigure / -migrate-state | Change backend: ignore old / copy state to new |
Inspection
| Command | Description |
|---|---|
terraform show | Show current state |
terraform show plan.tfplan | Show saved plan details |
terraform output | Show all outputs |
terraform output -json | Outputs as JSON |
terraform output db_endpoint | Specific output |
terraform graph | dot -Tpng > graph.png | Resource dependency graph |
terraform providers | Show required providers |
terraform version | Terraform and provider versions |
terraform show -json plan.tfplan | Machine-readable plan (for policy checks, e.g. OPA/Conftest) |
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 | Record provider checksums for every platform your team uses |
terraform providers schema -json | Full provider schema |
terraform modules | List declared modules (1.10+) |
State Management
| Command | Description |
|---|---|
terraform state list | List all resources in state |
terraform state show aws_s3_bucket.main | Show resource details |
terraform state mv old_name new_name | Rename resource in state (prefer a moved block, below) |
terraform state rm resource | Remove from state (keep real resource; prefer a removed block) |
terraform state pull | Download remote state to stdout |
terraform state push | Upload state (dangerous) |
terraform import aws_s3_bucket.main bucket-name | Import existing resource (prefer an import block, below) |
terraform refresh | Sync state with real infrastructure (deprecated: it writes state without review) |
terraform apply -refresh-only | Review and accept drift into state (replaces terraform refresh) |
terraform plan -generate-config-out=generated.tf | Write HCL for resources in import blocks (1.5+) |
Workspaces
| Command | Description |
|---|---|
terraform workspace list | List workspaces |
terraform workspace new staging | Create workspace |
terraform workspace select staging | Switch workspace |
terraform workspace delete staging | Delete workspace |
terraform workspace show | Current workspace name |
Formatting & Validation
| Command | Description |
|---|---|
terraform fmt | Format files in current directory |
terraform fmt -recursive | Format all files recursively |
terraform fmt -check | Check formatting (CI use) |
terraform validate | Validate configuration syntax |
terraform console | Interactive expression console |
terraform test | Run *.tftest.hcl tests (1.6+) |
terraform test -filter=tests/s3.tftest.hcl | Run one test file |
TF_LOG=DEBUG terraform plan | Debug logging (TF_LOG_PATH=tf.log to write a file) |
HCL Patterns
Variables
# String variable
variable "region" {
type = string
default = "us-east-1"
description = "AWS region"
}
# Number variable
variable "instance_count" {
type = number
default = 3
}
# Boolean variable
variable "enable_monitoring" {
type = bool
default = true
}
# List variable
variable "availability_zones" {
type = list(string)
default = ["us-east-1a", "us-east-1b"]
}
# Map variable
variable "tags" {
type = map(string)
default = {
Environment = "production"
Team = "platform"
}
}
# Object variable
variable "database" {
type = object({
engine = string
instance_class = string
storage_gb = number
multi_az = bool
})
default = {
engine = "postgres"
instance_class = "db.t3.medium"
storage_gb = 100
multi_az = true
}
}
# Validation
variable "environment" {
type = string
validation {
condition = contains(["dev", "staging", "production"], var.environment)
error_message = "Environment must be dev, staging, or production."
}
}
# Sensitive variable
variable "db_password" {
type = string
sensitive = true
}
# Ephemeral variable (1.10+): never written to plan or state files
variable "db_password_ephemeral" {
type = string
sensitive = true
ephemeral = true
}
# Optional object attributes with defaults (1.3+)
variable "service" {
type = object({
name = string
port = optional(number, 8080)
replicas = optional(number) # null if omitted
})
}
# Validation that references other variables (1.9+)
variable "max_size" {
type = number
validation {
condition = var.max_size >= var.min_size
error_message = "max_size must be >= min_size."
}
}
# Reject null when the caller passes it explicitly
variable "vpc_id" {
type = string
nullable = false
}
sensitive = true only hides the value in CLI output; it is still stored in plain text in state. Use ephemeral variables and write-only arguments (below) to keep secrets out of state.
Setting Variables
# Command line
terraform apply -var="region=us-west-2"
# Variable file
terraform apply -var-file="production.tfvars"
# Environment variables
export TF_VAR_region="us-west-2"
# Auto-loaded files (no flag needed)
# terraform.tfvars
# terraform.tfvars.json
# *.auto.tfvars
# *.auto.tfvars.json
Precedence, lowest to highest: default → TF_VAR_* env vars → terraform.tfvars → terraform.tfvars.json → *.auto.tfvars (alphabetical) → -var / -var-file on the command line (in the order given). The last one wins.
Outputs
output "db_endpoint" {
value = aws_db_instance.main.endpoint
description = "Database connection endpoint"
}
output "db_password" {
value = aws_db_instance.main.password
sensitive = true
}
# Read it in a script (sensitive outputs print as <sensitive> otherwise)
# terraform output -raw db_password
# Output from child module
output "vpc_id" {
value = module.vpc.vpc_id
}
Locals
locals {
environment = terraform.workspace
name_prefix = "${var.project}-${local.environment}"
common_tags = {
Project = var.project
Environment = local.environment
ManagedBy = "terraform"
}
# Computed values
is_production = local.environment == "production"
instance_type = local.is_production ? "t3.large" : "t3.small"
}
Resource Patterns
Basic Resource
resource "aws_s3_bucket" "logs" {
bucket = "${local.name_prefix}-logs"
tags = local.common_tags
}
resource "aws_s3_bucket_versioning" "logs" {
bucket = aws_s3_bucket.logs.id
versioning_configuration {
status = "Enabled"
}
}
count (Conditional Creation)
# Create resource only in production
resource "aws_cloudwatch_metric_alarm" "cpu" {
count = var.environment == "production" ? 1 : 0
# ...
}
# Reference count resource
output "alarm_arn" {
value = var.environment == "production" ? aws_cloudwatch_metric_alarm.cpu[0].arn : null
}
for_each (Multiple Similar Resources)
# From a map
variable "buckets" {
default = {
logs = { versioning = true }
backups = { versioning = true }
assets = { versioning = false }
}
}
resource "aws_s3_bucket" "this" {
for_each = var.buckets
bucket = "${local.name_prefix}-${each.key}"
tags = local.common_tags
}
resource "aws_s3_bucket_versioning" "this" {
for_each = { for k, v in var.buckets : k => v if v.versioning }
bucket = aws_s3_bucket.this[each.key].id
versioning_configuration {
status = "Enabled"
}
}
# From a set
resource "aws_iam_user" "this" {
for_each = toset(["alice", "bob", "charlie"])
name = each.value
}
Dynamic Blocks
resource "aws_security_group" "web" {
name = "${local.name_prefix}-web"
vpc_id = var.vpc_id
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.port
to_port = ingress.value.port
protocol = "tcp"
cidr_blocks = ingress.value.cidr_blocks
}
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
Lifecycle Rules
resource "aws_instance" "web" {
ami = var.ami_id
instance_type = var.instance_type
lifecycle {
create_before_destroy = true # New resource before destroying old
prevent_destroy = true # Prevent accidental deletion
ignore_changes = [tags, ami] # Ignore external changes
}
}
# Replacement trigger (terraform_data is built in since 1.4; no null provider needed)
resource "terraform_data" "ami_version" {
input = var.ami_id
}
resource "aws_instance" "web" {
# ...
lifecycle {
replace_triggered_by = [terraform_data.ami_version]
# older style, still works with the hashicorp/null provider:
# replace_triggered_by = [null_resource.trigger.id]
}
}
# Preconditions and postconditions (1.2+)
resource "aws_instance" "app" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
lifecycle {
precondition {
condition = data.aws_ami.ubuntu.architecture == "x86_64"
error_message = "AMI must be x86_64."
}
postcondition {
condition = self.public_ip != ""
error_message = "Instance needs a public IP."
}
}
}
Write-Only Arguments (1.11+)
Write-only arguments (*_wo) are sent to the provider but never stored in plan or state. Pair them with an ephemeral value and bump the version to rotate.
ephemeral "random_password" "db" {
length = 24
}
resource "aws_db_instance" "main" {
# ...
password_wo = ephemeral.random_password.db.result
password_wo_version = 1 # increment to push a new password
}
Ephemeral resources (1.10+) such as ephemeral "aws_secretsmanager_secret_version" fetch secrets at run time without saving them.
Data Sources
# Look up existing resources
data "aws_vpc" "main" {
filter {
name = "tag:Name"
values = ["main-vpc"]
}
}
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-*-22.04-amd64-server-*"]
}
}
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
# Subnets in that VPC (a VPC ID is not a subnet ID)
data "aws_subnets" "private" {
filter {
name = "vpc-id"
values = [data.aws_vpc.main.id]
}
tags = { Tier = "private" }
}
# Use in resources
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
subnet_id = data.aws_subnets.private.ids[0]
instance_type = "t3.micro"
}
Module Patterns
Module Structure
modules/
vpc/
main.tf # Resources
variables.tf # Input variables
outputs.tf # Output values
versions.tf # Required providers
README.md # Usage docs
Module Definition
# modules/vpc/variables.tf
variable "name" { type = string }
variable "cidr" { type = string }
variable "azs" { type = list(string) }
# modules/vpc/main.tf
resource "aws_vpc" "this" {
cidr_block = var.cidr
tags = { Name = var.name }
}
# modules/vpc/outputs.tf
output "vpc_id" { value = aws_vpc.this.id }
output "vpc_cidr" { value = aws_vpc.this.cidr_block }
Module Usage
# Use local module
module "vpc" {
source = "./modules/vpc"
name = "main"
cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b"]
}
# Use registry module (v6 of this module requires AWS provider 6.x)
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 6.0"
name = "main"
cidr = "10.0.0.0/16"
}
# Use Git module
module "vpc" {
source = "git::https://github.com/org/modules.git//vpc?ref=v1.0.0"
}
# Reference module outputs
resource "aws_instance" "web" {
subnet_id = module.vpc.public_subnet_ids[0]
}
# Multiple instances of a module, and passing an aliased provider
module "bucket" {
source = "./modules/bucket"
for_each = toset(["logs", "assets"])
name = each.key
providers = {
aws = aws.us_west
}
}
State Management
Remote Backend (S3)
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/vpc/terraform.tfstate"
region = "us-east-1"
use_lockfile = true # S3-native locking (1.10 experimental, GA in 1.11)
encrypt = true
}
}
State Locking
Since Terraform 1.11 the S3 backend locks with a .tflock object next to the state (use_lockfile = true, needs S3 conditional writes, which all AWS regions support). The dynamodb_table argument is deprecated and will be removed in a future release. To migrate, set both use_lockfile = true and dynamodb_table for one release cycle, then drop DynamoDB. Enable bucket versioning so you can recover old state.
Legacy DynamoDB table for state locking (only needed for Terraform < 1.11, or during migration):
resource "aws_dynamodb_table" "terraform_locks" {
name = "terraform-locks"
billing_mode = "PAY_PER_REQUEST"
hash_key = "LockID"
attribute {
name = "LockID"
type = "S"
}
}
State Operations
# Move resource between state files (-state-out only works with local state files;
# for remote backends, state pull both, mv between the local copies, state push)
terraform state mv -state-out=other.tfstate aws_s3_bucket.old aws_s3_bucket.new
# Import existing resource
terraform import aws_s3_bucket.existing actual-bucket-name
# Remove from state without destroying
terraform state rm aws_s3_bucket.no_longer_managed
# Taint resource to force recreation (deprecated, use -replace)
terraform apply -replace=aws_instance.web
Config-Driven Refactoring: import, moved, removed
These blocks go through normal plan/apply, so the change is reviewed in a PR and works the same in every environment. Prefer them over the terraform import / state mv / state rm commands.
# import block (1.5+): adopt an existing resource
import {
to = aws_s3_bucket.existing
id = "actual-bucket-name"
}
# import with for_each (1.7+)
import {
for_each = var.existing_buckets # map of key => bucket name
to = aws_s3_bucket.this[each.key]
id = each.value
}
# moved block (1.1+): rename or move into a module without destroy/create
moved {
from = aws_instance.web
to = aws_instance.app
}
moved {
from = aws_s3_bucket.logs
to = module.logging.aws_s3_bucket.this
}
moved { # count -> for_each
from = aws_iam_user.this[0]
to = aws_iam_user.this["alice"]
}
# removed block (1.7+): stop managing it, but keep the real resource
removed {
from = aws_s3_bucket.legacy
lifecycle {
destroy = false # true would destroy it instead
}
}
# Let Terraform write the resource HCL for import blocks, then tidy it up
terraform plan -generate-config-out=generated.tf
Keep moved blocks around until every state that used the old address has been applied (forever, for shared modules). import and removed blocks can be deleted after the apply.
Expressions & Functions
String Functions
locals {
upper = upper("hello") # "HELLO"
lower = lower("HELLO") # "hello"
trimmed = trimspace(" hi ") # "hi"
replaced = replace("hello", "l", "r") # "herro"
joined = join(",", ["a", "b"]) # "a,b"
split = split(",", "a,b,c") # ["a", "b", "c"]
formatted = format("Hello, %s!", "world")
substr = substr("hello", 0, 3) # "hel"
regex_match = regex("^[a-z]+$", "hello") # "hello"
}
Collection Functions
locals {
merged = merge(var.tags, { Extra = "tag" })
keys = keys(var.tags)
values = values(var.tags)
looked_up = lookup(var.tags, "Env", "default")
flat = flatten([["a"], ["b", "c"]]) # ["a", "b", "c"]
distinct = distinct(["a", "a", "b"]) # ["a", "b"]
sorted = sort(["c", "a", "b"]) # ["a", "b", "c"]
contains = contains(["a", "b"], "a") # true
length = length(var.list)
elem = element(var.list, 0)
chunked = chunklist(var.list, 2)
zipped = zipmap(["a", "b"], [1, 2]) # { a = 1, b = 2 }
pairs = setproduct(["dev", "prod"], ["us", "eu"])
first_ok = try(var.config.optional_field, "fallback")
safe = coalesce(var.name, "default") # first non-null, non-empty
one_item = one(aws_instance.web[*].id) # value of a 0-or-1 list, or null
}
Encoding, Files and Templates
locals {
cfg = jsondecode(file("${path.module}/config.json"))
yaml_cfg = yamldecode(file("${path.module}/values.yaml"))
policy = jsonencode({ Version = "2012-10-17", Statement = [] })
script = templatefile("${path.module}/init.sh.tftpl", { port = 8080 })
b64 = base64encode("hello")
cidr_sub = cidrsubnet("10.0.0.0/16", 8, 2) # "10.0.2.0/24"
}
Provider-Defined Functions (1.8+)
locals {
arn_parts = provider::aws::arn_parse("arn:aws:s3:::my-bucket")
}
Conditional & Loop Expressions
# Conditional
locals {
instance_type = var.env == "production" ? "t3.large" : "t3.micro"
}
# For expression (transform list)
locals {
upper_names = [for name in var.names : upper(name)]
}
# For expression (transform to map)
locals {
name_map = { for name in var.names : name => upper(name) }
}
# For expression with filter
locals {
production_servers = [for s in var.servers : s if s.env == "production"]
}
# Splat expression
locals {
instance_ids = aws_instance.web[*].id
}
Provider Configuration
terraform {
required_version = ">= 1.5"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0" # 6.0 released June 2025; "~> 5.0" pins you to the 5.x line
}
}
}
# Default provider
provider "aws" {
region = var.region
}
# Aliased provider (multi-region)
provider "aws" {
alias = "us_west"
region = "us-west-2"
}
# Use aliased provider
resource "aws_s3_bucket" "west" {
provider = aws.us_west
bucket = "my-bucket-west"
}
| Constraint | Allows |
|---|---|
= 6.2.0 | Exactly 6.2.0 |
~> 6.2 | >= 6.2, < 7.0 |
~> 6.2.0 | >= 6.2.0, < 6.3.0 |
>= 6.0, < 7.0 | Explicit range |
Commit .terraform.lock.hcl: it pins the exact provider versions and checksums. terraform init -upgrade moves within your constraints and rewrites it.
Check Blocks (1.5+)
Continuous assertions about your infrastructure. A failing check produces a warning, not an error, so it never blocks an apply.
check "api_health" {
data "http" "health" { # scoped data source, read on every plan/apply
url = "https://${aws_lb.api.dns_name}/health"
}
assert {
condition = data.http.health.status_code == 200
error_message = "API health check returned ${data.http.health.status_code}."
}
}
| Mechanism | Fails the run? | Use for |
|---|---|---|
variable validation | Yes (at plan) | Bad input |
precondition / postcondition | Yes | Assumptions about a resource or data source |
check block | No, warning only | Ongoing health / drift checks (HCP Terraform runs them on a schedule) |
Testing: terraform test (1.6+)
Tests live in *.tftest.hcl files (in the root or tests/). Each run block does a plan or apply and checks assertions; resources created by apply runs are destroyed at the end.
# tests/bucket.tftest.hcl
variables {
environment = "dev"
}
run "name_has_prefix" {
command = plan # no real resources
assert {
condition = startswith(aws_s3_bucket.logs.bucket, "myproj-dev")
error_message = "Bucket name must start with the project prefix."
}
}
run "rejects_bad_env" {
command = plan
variables {
environment = "qa"
}
expect_failures = [var.environment] # the validation should fail
}
run "creates_bucket" {
command = apply # real resources in a test account
assert {
condition = aws_s3_bucket.logs.arn != ""
error_message = "Bucket was not created."
}
}
# Mock a provider so tests run with no credentials (1.7+)
mock_provider "aws" {}
run "unit" {
command = apply # computed attributes get fake values
}
terraform test # all tests
terraform test -verbose # print plan/state for each run
terraform test -filter=tests/bucket.tftest.hcl
CI/CD Integration
# CI pipeline commands
terraform init -input=false
terraform validate
terraform fmt -check
terraform plan -input=false -out=plan.tfplan
# CD pipeline commands
terraform apply -input=false plan.tfplan
Plan as PR Comment
# Generate plan and save output
terraform plan -no-color -out=plan.tfplan > plan.txt 2>&1
# Or render the saved plan afterwards (cleaner, no refresh noise)
terraform show -no-color plan.tfplan > plan.txt
# Exit code 0 = no changes, 2 = changes present, 1 = error (useful for drift jobs)
terraform plan -detailed-exitcode
# Post as PR comment (GitHub Actions)
# Use a GitHub Action like hashicorp/setup-terraform
When to Use X vs Y
| Decision | Choice A | Choice B | Use A When | Use B When |
|---|---|---|---|---|
| Iteration | count | for_each | Conditional creation | Named instances, maps |
| Config | Variable | Local | User-provided input | Computed/derived values |
| Lookup | Data source | Hard-coded | Resource may change | Known, fixed value |
| Modules | Local | Registry | Custom logic, private | Standard patterns (VPC, EKS) |
| State | S3 (use_lockfile; DynamoDB on < 1.11) | HCP Terraform (formerly Terraform Cloud) | Self-managed, AWS-only | Multi-cloud, team features |
| Adopt resource | import block | terraform import CLI | Reviewed in PR, repeatable, bulk | One-off from a laptop |
| Rename / move | moved block | terraform state mv | Shared code, many environments | Emergency fix to one state |
| Stop managing | removed block | terraform state rm | Reviewed, works in every workspace | One-off |
| Assertion | check | postcondition | Warn only | Fail the apply |
| Tool | Terraform | OpenTofu | HCP Terraform, Stacks, vendor support | Open-source licence, state encryption |
| Env separation | Workspaces | Directories | Same config, diff vars | Different configs |
Troubleshooting
| Problem | Solution |
|---|---|
| State lock stuck | terraform force-unlock LOCK_ID |
| Provider version conflict | terraform init -upgrade |
| Resource drift | terraform plan to detect, apply to reconcile |
| Circular dependency | Refactor resources, use depends_on explicitly |
| Slow plan | Split into smaller state files, use -target (exceptional use only), -refresh=false |
| Lock held / stuck after crash | -lock-timeout=5m; with use_lockfile, force-unlock deletes the .tflock object |
| "Provider produced inconsistent final plan" | Usually a provider bug; upgrade the provider, or split the apply |
| Checksum mismatch in lock file | terraform providers lock -platform=... for each OS/arch |
| Import fails | Check resource ID format in provider docs |
| Destroy blocked by dependency | Destroy dependent resources first or use -target |
| State file corrupted | Restore from backend versioning (S3 versioning) |
| Module source changed | terraform init -upgrade |
| Provider auth error | Check env vars, AWS profile, credentials |
Test Yourself
-
What command previews infrastructure changes without applying them?
terraform plan -
How do you import an existing AWS S3 bucket into Terraform state?
terraform import aws_s3_bucket.main bucket-name, or (1.5+, preferred) animportblock withto = aws_s3_bucket.mainandid = "bucket-name", followed byplan/apply -
What meta-argument creates multiple similar resources from a map or set?
for_each -
How do you remove a resource from state without destroying the real infrastructure?
terraform state rm resource -
What lifecycle rule prevents accidental deletion of a resource?
prevent_destroy = true -
What command forces recreation of a specific resource (replacing
terraform taint)?terraform apply -replace=aws_instance.web -
How do you set a Terraform variable via an environment variable?
export TF_VAR_region="us-west-2" -
What HCL function merges two maps together?
merge(var.tags, { Extra = "tag" }) -
What is the difference between
countandfor_each?countis for conditional creation (0 or 1) or identical copies;for_eachis for named instances from a map or set. -
How do you unlock a stuck Terraform state lock?
terraform force-unlock LOCK_ID
Common Gotchas
- Forgetting to run
terraform planbeforeapply. Always review the plan. An innocent-looking change can trigger a resource replacement that causes downtime. - Storing secrets in
.tffiles. Usesensitive = truevariables, environment variables, or a secrets manager. Never commit passwords to version control. - Assuming
sensitivekeeps secrets out of state. It only masks CLI output; the state file holds the plain value. Restrict state access, encrypt the bucket, and useephemeralvalues with*_wowrite-only arguments (1.10/1.11+). - Using
terraform destroywithout-target. Without a target, it destroys ALL managed resources. Always double-check which workspace and state you are in. - Not using remote state with locking. Without locking (
use_lockfile = trueon S3 since 1.11, or a DynamoDB lock table on older versions), two people runningapplysimultaneously can corrupt the state file. - Renaming a resource without a
movedblock. Terraform sees a delete and a create, and destroys the real resource. Addmoved { from = ... to = ... }. - Switching
counttofor_each. Every instance gets a new address ([0]→["key"]) and is replaced unless you addmovedblocks. for_eachover values known only after apply. "Invalid for_each argument": keys must be known at plan time. Use static keys (names) and put computed IDs in the values.- Copying pre-1.x syntax.
"${var.x}"around a lone reference,list()/map()functions,terraform 0.12upgradeand-stateflags on remote backends are obsolete; writevar.x,tolist(),tomap().
One-Liner Summary
Terraform lets you define infrastructure as code in HCL, plan changes before applying them, and track everything in state -- master plan, import, for_each, and remote state to manage any cloud.