Terraform Associate cheat sheet
Terraform Associate · Keep the key ideas within reach.
Infrastructure as Code (IaC) with Terraform
IaC manages infrastructure through machine-readable definition files rather than manual console steps or interactive commands.
Terraform is declarative: configuration states the desired end state, and Terraform computes the API calls needed to reach it.
Idempotency: applying the same configuration to unchanged infrastructure reports no changes and makes no mutating API calls.
Configuration lives in version control, so every infrastructure change is reviewable, diffable, and auditable like application code.
A single Terraform workflow and HCL syntax drives many providers (AWS, Azure, GCP, Kubernetes, SaaS) through plugin binaries.
Imperative tooling specifies how to change things step by step; declarative tooling specifies what the result must be.
Configuration drift is divergence between real infrastructure and recorded state, caused typically by manual changes; plan refresh detects it.
Immutable pattern: prefer replacing resources over mutating them, implemented with create_before_destroy and forced replacement.
Terraform fundamentals
HCL block form: block_type followed by optional quoted labels, then a brace body of key = value arguments and nested blocks.
The terraform block with required_providers pins each provider source address and version constraint; the provider block configures it.
Resource addresses are type.local_name and are referenced as type.local_name, e.g. aws_instance.web.id.
Data sources read objects Terraform does not manage: data.type.name is declared in a data block and referenced as data.type.name.attr.
variable blocks are inputs, output blocks expose values to the caller, and locals compute intermediate expressions.
Version constraint operators: =, !=, >, >=, <, <=, and ~>, where ~> allows only the rightmost component to increase.
The Terraform Registry distributes providers and modules; module source may be a local path, Git or HTTP URL, registry address, or bucket.
Provisioners local-exec and remote-exec run scripts during create or destroy; they are a fallback, not routine configuration management.
Core Terraform workflow
terraform init downloads providers and modules, creates .terraform/, writes .terraform.lock.hcl, and initializes the configured backend.
terraform validate checks syntax, argument names, and internal references only; it does not call provider APIs or read remote state.
terraform fmt rewrites files to canonical HCL; -check exits non-zero when files need formatting and -recursive descends into subdirectories.
terraform plan refreshes state, diffs configuration against real infrastructure, and prints the proposed actions; -out saves the plan.
terraform apply FILE applies a saved plan exactly as previewed; without a saved plan, apply re-plans and requires interactive approval.
Plan symbols: + create, - destroy, ~ update in place, -/+ replace (destroy then create), <= read a data source.
terraform destroy removes every object tracked in state; it is equivalent to terraform apply -destroy.
terraform show -json FILE renders a plan or state as machine-readable JSON for CI checks or policy evaluation.
Terraform configuration
Meta-arguments available to resources: count, for_each, depends_on, provider, and the lifecycle block.
count produces instances indexed by number via count.index; for_each takes a map or set of strings and keys instances by string, giving stable identity.
for expressions transform collections: [for s in var.list : upper(s)] returns a tuple; {for k, v in var.map : k => v} returns a map.
String templates use ${ } interpolation and %{ if } / %{ for } directives for conditional and repeated content.
Common functions: lookup, merge, try, can, coalesce, length, jsonencode, file, templatefile, and cidrsubnet.
lifecycle arguments: create_before_destroy, prevent_destroy, ignore_changes, and replace_triggered_by.
depends_on adds explicit ordering for dependencies Terraform cannot infer from attribute references.
A variable validation block pairs a condition expression with an error_message; sensitive = true redacts the value from CLI output.
Type constraints include string, number, bool, list(), set(), map(), object(), tuple(), and any.
Terraform modules
A module is any directory of .tf files; the root module is the working directory, and child modules are invoked with module blocks.
Module call syntax: module "name" { source = ... ; version = ... ; inputs }; outputs are read as module.name.output_name.
source accepts local paths such as ./modules/network, registry addresses namespace/name/provider, Git or HTTP URLs, and object storage buckets.
The version argument constrains registry modules and some remote sources; local path sources cannot be version-constrained this way.
Child modules declare inputs with variable blocks and expose results with output blocks, keeping the interface explicit.
terraform init installs modules automatically; terraform get fetches them separately, and -upgrade re-resolves newer allowed versions.
count and for_each on a module block create multiple instances addressed as module.name[0] or module.name["key"].
Providers are configured in the root module and passed down with the providers meta-argument; a child may declare configuration_aliases.
A published module is referenced by registry address and pinned with version, so upgrades require an explicit constraint change.
Terraform state management
State maps resource addresses to real remote object IDs and caches attributes; plan and apply require it to know what exists.
The default local backend writes terraform.tfstate in the working directory; remote backends (S3, azurerm, gcs, HCP Terraform) centralize it.
State locking blocks concurrent writes that could corrupt state; HCP Terraform locks natively, the S3 backend uses a DynamoDB table.
terraform state list prints tracked addresses; terraform state show ADDRESS prints the cached attributes of one object.
terraform state mv SOURCE DEST renames or moves an object within state without destroying or recreating the real infrastructure.
terraform state rm ADDRESS drops an object from state while leaving the real infrastructure untouched and unmanaged.
terraform import ADDRESS ID adopts existing infrastructure into state but does not generate matching configuration.
State stores attribute values including secrets in plaintext, so the backend must be encrypted and access-controlled and never committed to VCS.
terraform state pull and terraform state push read and write the raw remote state, useful for backup or migration.
Maintain infrastructure with Terraform
terraform taint ADDRESS marks an object for replacement on the next apply; plan -replace=ADDRESS is the current equivalent.
plan -refresh-only and apply -refresh-only reconcile state with real infrastructure without changing any managed objects.
moved blocks record resource renames or module moves so refactoring updates state instead of destroying and recreating objects.
removed blocks drop a resource from state in configuration, optionally destroying the real object with the destroy lifecycle argument.
terraform providers prints provider requirements; terraform providers lock writes checksums into the dependency lock file for chosen platforms.
terraform graph emits the dependency graph in DOT format, showing ordering between resources, data sources, and variables.
terraform output -json exposes output values to scripts, and terraform console evaluates expressions against current state interactively.
Upgrade path: raise required_version or a provider constraint, run terraform init -upgrade, then review the plan before applying.
TF_LOG accepts TRACE, DEBUG, INFO, WARN, or ERROR for verbose core and provider logging to stderr; TF_LOG_PATH redirects it to a file.
HCP Terraform
HCP Terraform is the managed platform providing remote state, remote runs, VCS integration, policy enforcement, and a private registry.
Workspace types are CLI-driven, VCS-driven, and API-driven; each workspace holds its own state, variables, and run history.
Remote runs execute plan and apply on HCP infrastructure; the CLI authenticates with terraform login and then uses the cloud block.
The cloud block sets organization and workspaces (by name or tags), replacing the older remote backend configuration.
Variable sets are reusable groups of Terraform or environment variables applied to many workspaces; individual variables can be marked sensitive.
Sentinel and OPA policies are evaluated between plan and apply, and failing policies hold the run; run tasks add external pre-apply checks.
Run states progress plan queued, planning, planned, apply queued, applying, applied; policy or confirmation needs surface as needs attention.
Team permissions (read, plan, write, admin) govern workspace access; user, team, and organization API tokens authenticate automation.
The private registry hosts modules and providers published from VCS repositories tagged with semantic versions such as v1.0.0.