All cheat sheets
Each module prints on its own page, without navigation.
Cheat Sheet 1: Infrastructure as Code
| Concept | Key point |
|---|---|
| IaC | Infrastructure defined in version-controlled files and applied by a tool |
| Declarative | Describe the end state. Terraform works out the steps. |
| Imperative | Describe the steps, as in scripts and CLIs |
| Idempotent | Re-applying unchanged config produces "No changes" |
| Execution order | Comes from the dependency graph (references), never from file or block order |
| Parallelism | Independent resources are created concurrently, 10 by default |
| Desired vs. actual | Config is desired state. State plus refresh gives actual state. Plan is the difference. |
| Benefits | Version control, review via plan, consistency, reuse via modules, self-documentation, drift detection, automation |
| Immutable infra | Replace rather than modify. Shown as -/+ and # forces replacement in a plan. |
| Providers | Plugins that hold all platform logic. Core is platform-agnostic. |
| Multi-cloud | Many cloud providers, one workflow |
| Hybrid | On-premises (such as vSphere) plus cloud, one workflow |
| Service-agnostic | Non-infrastructure APIs: GitHub, DNS, monitoring, identity, Kubernetes, Vault |
| Not abstracted | Resources are provider-specific. aws_* blocks don't run on Azure. |
| Terraform vs. config management | Terraform provisions. Ansible, Chef, and Puppet configure inside servers. They complement each other. |
| Provisioners | A last resort per HashiCorp docs |
Commands seen so far: terraform version · init · fmt -check · validate · plan · apply · state list · output · destroy
Plan symbols: + create · - destroy · ~ update in place · -/+ replace (destroy, then create) · +/- replace with create first (create_before_destroy) · <= read a data source
Cheat Sheet 2: Terraform Fundamentals
terraform block
terraform {
required_version = "~> 1.12.0" # CLI version
required_providers {
random = { source = "hashicorp/random", version = "~> 3.7" } # provider version
}
}Constraint operators: = (or none) exact · != exclude · > >= < <= compare · , AND
~>: only the rightmost given component may increase.
~> 3.7→ ≥ 3.7, < 4.0~> 3.7.0→ ≥ 3.7.0, < 3.8.0
Pre-releases match only exact constraints. The root module uses upper bounds; reusable modules use >= minimums.
Source address: [hostname/]namespace/type. The hostname defaults to registry.terraform.io.
Registry tiers: Official (HashiCorp) · Partner · Community
Lock file (.terraform.lock.hcl)
- Records selected provider version, constraints, and hashes. Providers only, no modules.
- Written by
terraform init. Commit it. Ignore.terraform/. - A constraint excludes the locked version → init fails → run
terraform init -upgrade. -upgradepicks the newest version allowed (possibly a downgrade) and also upgrades modules.terraform providers lock -platform=...adds hashes for other operating systems and architectures.
Provider configurations
- A
providerblock with no alias is the default. Only one default per provider per module. alias = "west"creates another configuration, referenced asaws.west(not a string).- Choose a configuration per resource with
provider = aws.west. - Child modules inherit default configurations only. Pass aliases with
providers = { aws = aws.west }, and declareconfiguration_aliases = [aws.x]in the child.
State (terraform.tfstate)
- Purpose: mapping, metadata (dependencies, provider configuration), performance, collaboration.
- Contains every attribute and output in plaintext JSON, plus serial and lineage.
sensitive = truehides values in output, but they are still in state.- Refreshed by default on plan and apply. Never hand-edit it.
- Deleting state doesn't delete infrastructure.
Commands: terraform init · init -upgrade · terraform providers · terraform providers lock · terraform version · terraform state show <addr>
Errors to recognize:
Unsupported Terraform Core version→required_versionisn't met- "locked provider … does not match configured version constraint" → run
init -upgrade - Duplicate provider configuration → two un-aliased blocks for the same provider
Cheat Sheet 3: Core Workflow
Workflow: Write → (fmt, init, validate) → Plan → review → Apply → … → Destroy
terraform init: sets up the backend, downloads modules (.terraform/modules) and providers (.terraform/providers), and writes the lock file. Safe to re-run, and never touches infrastructure.
- Re-run after adding or changing a provider, module source or version, or backend or
cloudblock. - Flags:
-upgrade·-backend=false·-backend-config·-migrate-state·-reconfigure·-input=false
terraform validate: checks syntax, schema, references, and types. It requires init, makes no API calls, and doesn't use tfvars values. Use -json for CI.
terraform plan: refreshes, then diffs. Changes nothing, and refreshed values aren't saved.
| Flag | Purpose |
|---|---|
-out=f |
Save the plan. Read it with terraform show f. Treat it as sensitive. |
-refresh-only |
Propose state-only updates to match reality |
-refresh=false |
Skip refresh |
-target=addr |
Limit scope, with a warning. Exceptional use only. |
-replace=addr |
Force replacement. Replaces the deprecated taint. |
-destroy |
Preview destruction |
-var / -var-file |
Supply variable values |
-detailed-exitcode |
0 = no changes · 1 = error · 2 = changes |
Plan symbols: + create · - destroy · ~ update · -/+ replace (destroy first) · +/- replace (create first) · <= read data · # forces replacement
terraform apply
- No plan file: plans and prompts.
-auto-approveskips the prompt. apply planfile: applies exactly, no prompt. Fails if the plan is stale.- No rollback on failure. Completed resources stay in state. Failed creations become tainted and are replaced next run.
-refresh-onlywrites state only.
Destroy
terraform destroy=terraform apply -destroy.plan -destroy= preview only.- Runs in reverse dependency order.
prevent_destroymakes the plan error. - To remove one resource, delete its block and run
apply(preferred), ordestroy -target(exceptional).
terraform fmt: whitespace only, current directory only by default.
-recursivesubdirectories ·-checkCI gate (non-zero exit, no writes) ·-diffshow changes ·-write=falseno writes- It isn't a validator.
Only apply and destroy change real infrastructure. Only apply, apply -refresh-only, destroy, and state commands write state.
Cheat Sheet 4: Terraform Configuration
resource vs. data
resource= Terraform owns the object (create, update, delete).data= read-only, referenced asdata.T.N.- Data sources are read during plan, or deferred to apply (
<=) if their inputs are unknown ordepends_onpoints at pending changes. Results are stored in state. terraform_datais built in and needs no provider. It hasinput/outputandtriggers_replace, and replacesnull_resource.
References: T.N.attr · data.T.N.attr · T.N[0] (count) · T.N["k"] (for_each) · T.N[*].attr (lists and count only) · var.x · local.x · module.m.out · ephemeral.T.N.attr · path.module · terraform.workspace · self (postconditions and provisioners)
Variables: type, default (none → required), description, sensitive, nullable, ephemeral, validation
Precedence (later wins): default < TF_VAR_ < terraform.tfvars < terraform.tfvars.json < *.auto.tfvars (lexical order) < -var/-var-file (last one wins). Other .tfvars names need -var-file.
Outputs: value, description, sensitive (required if derived from a sensitive value), depends_on, precondition. terraform output alone shows <sensitive>; output NAME, -json and -raw show sensitive values in plaintext.
Types: list (ordered) · set (unique, no index) · map (same value type) · object (per-attribute types; optional(T, default)) · tuple (per-position types) · any. tuple→list, object→map, list→set (dedups, loses order).
Expressions
[for x in L : f(x) if c]·{for k, v in M : k => v}·...groups duplicate keyscond ? a : b(types must match) ·L[*].attrdynamic "blk" { for_each = …; content { … blk.key / blk.value } }locals {}→local.x. No user-defined functions. Provider functions:provider::p::f().terraform consoleevaluates against config and state, and holds a state lock.- Key functions:
lookup·merge·concat·flatten·toset·try·can·coalesce·format·join·split·cidrsubnet·jsonencode·templatefile·sensitive·nonsensitive
Meta-arguments
count(index; shifts on removal) vs.for_each(map or set of strings; keys known at plan). Never both on one block.depends_on = [res, module.m]: whole objects, static, last resort. On data sources it defers reads.provider = aws.aliaslifecycle(literal values only):create_before_destroy(+/-)prevent_destroy(errors on destroy; useless once the block is deleted)ignore_changes = [attr]orallreplace_triggered_by = [managed resource or attribute](useterraform_datafor variables)
Custom conditions
| Mechanism | Location | Failure |
|---|---|---|
validation |
variable (can reference other variables since 1.9) | Error |
precondition |
resource, data, or output lifecycle |
Error, before evaluation |
postcondition |
resource or data lifecycle, uses self |
Error, after evaluation |
check + assert (+ scoped data) |
top level | Warning only, every plan and apply |
Sensitive data
sensitive= hidden from display, still in state and plan.ephemeral(1.10+): variables, outputs,ephemeralresources. Never stored. Allowed only in ephemeral contexts, provider blocks, provisioner and connection blocks, and write-only arguments. Must be supplied again when applying a saved plan.- Write-only (1.11+):
*_woarguments plus*_wo_version. Stored as null. Requires provider support. - Classic Vault data sources store the secret in state. Ephemeral Vault resources don't.
- Use dynamic provider credentials (OIDC), never commit secrets, encrypt and restrict state, and treat plan files as sensitive.
Cheat Sheet 5: Terraform Modules
Basics: a module is a directory of .tf files. The root module is the working directory. Child modules are called with module blocks.
Sources (source must be a literal string)
| Type | Form | Pin with |
|---|---|---|
| Local | ./path or ../path (prefix required) |
— (read in place) |
| Public registry | NAMESPACE/NAME/PROVIDER |
version |
| Private registry | HOST/ORG/NAME/PROVIDER |
version |
| GitHub, Bitbucket | github.com/org/repo, bitbucket.org/org/repo |
?ref= |
| Git | git::https://… or git::ssh://… |
?ref= (tag or SHA; ?depth=1 for shallow) |
| Mercurial, HTTP, S3, GCS | hg::, https://…zip, s3::, gcs:: |
— |
Use //subdir to select a subdirectory in a package, for example repo.git//modules/vpc?ref=v1.0.0.
Installation
initdownloads modules to.terraform/modules/and records them inmodules.json.terraform get(-update) fetches modules only.- Re-init after adding a module block or changing
source,version, orref. Editing a local module's code doesn't need init.
Scope
- Parent → child: arguments in the
moduleblock set the child's variables. - Child → parent:
outputblocks, read asmodule.NAME.OUT, ormodule.NAME["key"].OUTwithfor_each. - The child can't see the parent's variables, locals, or resources. The parent can't see the child's resources.
TF_VAR_and.tfvarsset root variables only.
Module meta-arguments: count · for_each · providers = { aws = aws.west } (aliases must be passed; defaults are inherited) · depends_on (the whole module waits). No lifecycle on modules.
Refactoring: moved { from = old_addr to = module.m.new_addr } keeps the object and avoids a destroy and recreate.
Versions
- Same operators as providers.
~> 2.1→ ≥ 2.1.0, < 3.0.0. versionworks on registry sources only. Git uses?ref=.init -upgradere-resolves to the newest allowed version.- The lock file doesn't record modules.
- Pin production code. Never pin a Git source to a moving branch.
Writing modules: main.tf, variables.tf, outputs.tf, versions.tf (>= provider minimums), README.md, examples/, modules/. Don't put provider blocks in reusable modules.
Publishing to the public registry: a public GitHub repo named terraform-<PROVIDER>-<NAME>, semantic version tags, and the standard structure.
Cheat Sheet 6: State Management
Local backend (the default)
- Files:
terraform.tfstate,terraform.tfstate.backup(previous version), andterraform.tfstate.d/<ws>/for CLI workspaces. backend "local" { path = "…" }sets the path explicitly.-state=works for local only.- Locks with OS file locks, on the same machine only. Not suited to teams: no sharing, plaintext secrets on disk, easy to lose. Never commit state.
Locking
- Automatic on any state-writing operation. Backend support varies.
- S3:
use_lockfile = true(DynamoDB locking is deprecated) · azurerm blob lease · gcs · pg advisory locks · consul · kubernetes · http (optional) · HCP Terraform built in. -lock-timeout=60swaits.-lock=falseskips locking (avoid).terraform force-unlock LOCK_IDclears a stuck lock only when nothing is running.
Remote backends
terraform { backend "TYPE" { … } }. One per configuration. Literal values only.- Built-in types: local, remote, azurerm, consul, cos, gcs, http, kubernetes, oss, pg, s3. Use the
cloudblock for HCP Terraform. - Partial configuration:
init -backend-config=file.hclor-backend-config="k=v". Provide credentials through environment variables, because backend settings are stored in.terraform/and in plan files. - Changing backends:
init(prompts) ·-migrate-state(copies; add-force-copyto skip the prompt) ·-reconfigure(no copy). terraform_remote_stateexposes root outputs only at.outputs.NAME, needs full state read access, and takes aworkspaceargument. Alternatives: provider data sources,tfe_outputs.
Drift
- A normal plan refreshes, reports "changed outside of Terraform," and proposes reverting to the configuration.
plan -refresh-onlyreviews drift.apply -refresh-onlywrites state only, so update the code if you want to keep the change.terraform refreshis deprecated (it'sapply -refresh-only -auto-approve, with no review).- An object deleted outside Terraform drops from state on refresh, and the plan recreates it.
ignore_changesis for attributes another system owns.
State changes: prefer config blocks, which are plannable and reviewable
| Need | Block | CLI alternative |
|---|---|---|
| Rename or move | moved { from, to } |
state mv |
| Forget without destroying | removed { from; lifecycle { destroy = false } } (1.7+) |
state rm |
| Adopt an existing object | import { to, id } |
terraform import |
| Recreate | apply -replace=ADDR |
taint (deprecated) |
state rmwith the block still in configuration → the next plan creates a duplicate.- Don't hand-edit state, because of serial and lineage, locking, and the missing audit trail.
state pullandpushare for disaster recovery only.
CLI workspaces
workspace list/show/new/select [-or-create]/delete [-force].defaultcan't be deleted.terraform.workspaceandTF_WORKSPACE.- Multiple states, one configuration, one backend, with no separate credentials or permissions.
- ≠ HCP Terraform workspaces, which have their own state, variables, permissions, runs, and policies.
Cheat Sheet 7: Maintaining Infrastructure
Import: binds an existing object to an address in state. Never creates or changes infrastructure.
CLI terraform import ADDR ID |
import { to = ADDR id = "ID" } |
|
|---|---|---|
| Preview | ✗, immediate state write | ✓, "N to import" in the plan |
| Resource block | Must exist first | Can be generated: plan -generate-config-out=FILE (file must not exist; review it) |
| Bulk | One per command | Multiple blocks, or for_each (1.7+) |
| VCS and HCP Terraform | ✗ | ✓ |
| Provider alias | — | provider = aws.west |
- The ID format is provider-specific. Check the resource docs' "Import" section. Not every resource supports import.
- Post-import changes in the plan mean the configuration is wrong. Fix it until the plan is clean.
- Remove
importblocks after applying, by convention. - 1.12 adds
identityas an alternative toid, for providers that support resource identity.
Inspect (read-only)
state list [prefix] [-id=ID]·state show ADDR(one resource, sensitive values redacted)show(whole state) ·show tfplan·show -jsonoutput(all outputs; sensitive ones shown as<sensitive>) ·output NAME/output -json/-raw NAME(sensitive values in plaintext)graph(DOT;| dot -Tsvg) ·providers·console(holds the lock) ·state pull- Quote addresses with brackets:
'res.x["key"]'.
State-modifying: state mv · state rm · state push · state replace-provider · import
Logging
TF_LOG=TRACE>DEBUG>INFO>WARN>ERROR, orJSON(TRACE as JSON)TF_LOG_PATH= file destination. Requires a level variable to be set as well.TF_LOG_CORE/TF_LOG_PROVIDER= scope logging to core or providers- Logs go to stderr by default. A core panic writes
crash.log. - Logs may contain secrets, so scrub them before sharing. Unset the variables afterwards.
Cheat Sheet 8: HCP Terraform
Editions: Community (free CLI, DIY) · HCP Terraform (SaaS, formerly Terraform Cloud) · Terraform Enterprise (self-hosted HCP Terraform)
Hierarchy: Organization → Project → Workspace. There's a Default Project. Team permissions apply at organization, project, or workspace level. The owners team controls the organization.
HCP Terraform workspace = state with version history and rollback, variables, run history, settings (Terraform version, execution mode, working directory, auto-apply, VCS), permissions, and policies. It isn't a CLI workspace, which only provides an extra state in one backend.
Connecting
terraform login [hostname]saves a token to~/.terraform.d/credentials.tfrc.json. In CI, useTF_TOKEN_app_terraform_io.terraform logoutremoves it.- The
cloud { organization = "…" workspaces { name = "…" } | { tags = [...] } }block replacesbackend, so you can't have both.hostnamedefaults toapp.terraform.io. The legacy alternative isbackend "remote". initmigrates existing state and creates the workspace if needed. The env varsTF_CLOUD_ORGANIZATION,TF_CLOUD_HOSTNAME, andTF_WORKSPACEcan supply settings.
Run workflows
| Workflow | Start | Notes |
|---|---|---|
| VCS-driven | push → plan · PR → speculative plan (never applied) | Apply after Confirm & Apply or auto-apply. CLI apply is blocked. |
| CLI-driven | Local plan or apply uploads the configuration and streams the remote run |
CLI plan produces a speculative plan |
| API-driven | Upload a configuration version tarball and create a run | Custom pipelines |
Execution modes: Remote (default; HCP workers, which can't see local files, environment, or private networks) · Local (your machine; HCP stores state only, and workspace variables aren't used) · Agent (self-hosted agents in your network)
Run pipeline: Plan → Cost estimation → Policy check → Confirm → Apply. Run tasks hook in at pre-plan, post-plan, pre-apply, and post-apply.
Variables
- Two categories: Terraform variables and environment variables. The HCL checkbox allows complex values. Sensitive = write-only, never readable again.
- Variable sets apply to the organization, projects, or workspaces. Workspace variables override a set with the same name unless the set is marked priority.
- Prefer dynamic provider credentials (OIDC, short-lived) for AWS, Azure, GCP, Vault, and Kubernetes.
Governance and collaboration
- Teams: Read · Plan · Write · Admin at workspace level, plus project-level and custom permissions.
- Private registry: modules and providers. Source
app.terraform.io/ORG/NAME/PROVIDERwithversion. Publish from VCS. No-code modules. - Policies: Sentinel or OPA, in policy sets. Run after plan, before apply.
- Sentinel: advisory · soft-mandatory (overridable) · hard-mandatory
- OPA: advisory · mandatory
- Run tasks: third-party checks, advisory or mandatory.
- Health assessments: drift detection plus continuous validation (
checkblocks and conditions). They report problems and don't fix them. - Also: cost estimation · state versions and rollback · notifications · workspace locking · run triggers ·
tfe_outputsfor sharing outputs · audit and SSO (check your plan).