CertifyDeck
All cheat sheets
Terraform Associate (004) · CHEAT SHEET

HashiCorp Certified: Terraform Associate (004)

Key concepts grouped by official exam weight.

Download as PDF (free, no sign-up)

1. Infrastructure as Code (IaC) with Terraform

1a Explain what IaC is

  • Infrastructure as code (IaC) manages infrastructure with configuration files instead of a graphical interface, so it can be versioned, reused and shared. Terraform is declarative: you describe the end state and it works out the steps, it calls each platform's API through providers and uses the state file as the source of truth. It is not a configuration management tool.

1b Describe the advantages of IaC patterns

  • IaC patterns let teams review changes in version control like code, reuse modules that codify standards, create and destroy disposable environments and inspect a plan before it runs. A remote backend such as HCP Terraform shares state without race conditions, and policies such as Sentinel replace ticket-based reviews.

1c Explain how Terraform manages multi-cloud, hybrid cloud, and service-agnostic workflows

  • Terraform uses the same language and workflow with any provider, so one configuration can combine several clouds, on-premises platforms with an API and SaaS services such as DNS or CDN, and it handles dependencies between them. Each provider brings its own resource types; there are no universal resources. Deploying across clouds increases fault tolerance.

2. Terraform fundamentals

2a Install and version Terraform providers

  • Providers are declared in required_providers with a source and a version, and terraform init installs them in .terraform/providers. The .terraform.lock.hcl file records the selected version and its checksums (not modules), is committed to Git and reused on every init; terraform init -upgrade looks for newer versions. Reusable modules set only a minimum (>=) and the root module uses ~>.

2b Describe how Terraform uses providers

  • Providers are Go plugins that Terraform Core runs as separate processes over RPC; they authenticate with the platform and define its resources and data sources. Each has a source address and a local name and is configured in a provider block; alias allows several configurations of one provider, selected with provider = NAME.ALIAS.

2c Write Terraform configuration using multiple providers

  • A configuration can combine several providers declared in required_providers with unique local names; when two share a type name, use compound names. For several configurations of one provider, repeat the provider block with alias and select it with provider = NAME.ALIAS. Child modules inherit only the default configuration; aliased ones are passed with the providers map and declared with configuration_aliases.

2d Explain how Terraform uses and manages state

  • State binds each resource instance to its remote object, keeps metadata such as the latest dependencies (to destroy removed resources in order) and a cache of attributes that -refresh=false treats as the record of truth. It is plaintext JSON that can hold secrets: do not edit it by hand or commit it to Git; external tools should use terraform show -json. Remote state lets a team work on the same data.

3. Core Terraform workflow

3a Describe the Terraform workflow

  • The core Terraform workflow has three stages repeated as a loop: Write (author the configuration, with frequent plans as feedback), Plan (preview changes without touching infrastructure) and Apply (make the changes after approving the plan). Teams review speculative plans on pull requests and, after merging, the final plan against the latest state, which can differ.

3b Initialize a Terraform working directory

  • terraform init prepares the working directory: it initializes the backend, downloads modules, installs providers into .terraform and creates or updates .terraform.lock.hcl, which you commit (but not .terraform). It is idempotent and must be rerun after changing providers, modules or the backend. Key options: -upgrade, -migrate-state, -reconfigure, -backend-config for partial configuration and -plugin-dir.

3c Validate a Terraform configuration

  • terraform validate checks that the configuration is syntactically valid and internally consistent (attribute names, value types, references, cycles) without reading remote state or calling provider APIs. It needs an initialized directory; terraform init -backend=false prepares one without touching the backend. To check the configuration with real variables and state, use terraform plan.

3d Generate and review an execution plan for Terraform

  • terraform plan reads the current state of remote objects, compares the configuration with the prior state and proposes the actions needed without carrying them out. With -out it saves a plan that terraform apply executes later; without -out the plan is speculative. It offers the -destroy and -refresh-only modes and options such as -target, -replace, -var, -var-file and -detailed-exitcode, and terraform show reviews a saved plan.

3e Apply changes to infrastructure with Terraform

  • Without a saved plan, terraform apply creates a new plan, asks for approval (or skips it with -auto-approve) and performs the actions; with a saved plan it applies it without prompting and accepts no further planning options. During apply it locks the state, creates independent objects in parallel and updates the state. If it fails, it records what was done and rolls nothing back: fix the cause and apply again.

3f Destroy Terraform-managed infrastructure

  • terraform destroy removes every object the configuration manages and is an alias of terraform apply -destroy; it asks you to confirm with yes and leaves an empty state. terraform plan -destroy shows the effect without executing it and, with -out, creates a plan you run with terraform apply. Dependents are destroyed before their dependencies, and prevent_destroy rejects any plan that destroys the resource while the block remains in the configuration.

3g Apply formatting and style adjustments to a configuration

  • terraform fmt rewrites files to the canonical format (two-space indentation, aligned equals signs) and offers no customization. By default it only processes the current directory; -recursive adds subdirectories, -check fails without writing when files are not formatted, -diff shows the changes and -write=false prevents overwriting. The style guide adds conventions such as meta-arguments first and # comments.

4. Terraform configuration

4a Use and differentiate resource and data blocks

  • A resource block declares an infrastructure object that Terraform creates, updates and destroys, tracked in state at the TYPE.NAME address. A data block only reads data through a provider and is referenced as data.TYPE.NAME.ATTRIBUTE; Terraform reads it before planning unless it depends on values known only at apply, and it supports count, for_each, depends_on, provider and conditions.

4b Refer to resource attributes and create cross-resource references

  • An attribute is referenced as TYPE.NAME.ATTRIBUTE; with count the resource is a list of instances (aws_instance.x[0].id or [*].id) and with for_each a map by key (aws_instance.x["a"].id or values(...)[*].id). Child module outputs are read as module.NAME.OUTPUT, and every cross-resource reference creates an implicit dependency; values unknown until apply show as (known after apply).

4c Use variables and outputs

  • Input variables (var.NAME) parameterize a module: without a default they are required, and their value comes, from highest to lowest precedence, from -var and -var-file, *.auto.tfvars, terraform.tfvars.json, terraform.tfvars, TF_VAR_ environment variables and the default. Output blocks, with a required value, expose data to the parent module, the CLI and terraform_remote_state; terraform output -raw and -json serve scripts.

4d Understand and use complex types

  • Complex types are collections (list, map and set, with one element type) and structural types (object and tuple, with a type per attribute or position). Terraform converts between similar types: a list becomes a set losing duplicates and order, and an object drops attributes it does not declare. A set cannot be indexed without tolist, and optional(type, default) applies the default even when null arrives.

4e Write dynamic configuration using expressions and functions

  • for expressions transform collections: brackets produce a tuple, braces with => produce an object, and an if clause filters elements. Splat expressions ([*]) work only on lists, sets and tuples, and dynamic blocks generate repeated nested blocks, never lifecycle. Built-in functions such as merge, coalesce, flatten and file can be tried in terraform console and do not take part in the dependency graph.

4f Define resource dependencies in configuration

  • Terraform infers implicit dependencies when an argument references another object, and it creates, updates and destroys along that graph, in parallel where possible. depends_on declares hidden dependencies with a list of static references and should be a last resort. By default a replacement destroys first and then creates; create_before_destroy reverses that order and propagates to dependencies.

4g Validate configuration using custom conditions

  • Variable validation runs before the plan; preconditions check assumptions before a resource, data source or output is created, and postconditions check guarantees afterwards using self. All of them stop the operation when they fail. check blocks run at the end of plan and apply and only warn, and their nested data sources are scoped to the block. HCP Terraform can re-run them through continuous validation.

4h Understand best practices for managing sensitive data, including secrets management with Vault

  • sensitive = true hides values in CLI output and in HCP Terraform, but they are still stored in state and plan files. Ephemeral variables and outputs, ephemeral blocks and write-only arguments are never stored. Secrets read by a Vault provider data source end up in state, while its ephemeral resource avoids that. Protect state by keeping it remote, encrypted and access controlled.

5. Terraform modules

5a Explain how Terraform sources modules

  • The source argument of a module block is a literal string that says where the code comes from: local paths with ./ or ../, the public registry (NAMESPACE/NAME/PROVIDER), the HCP Terraform private registry (app.terraform.io/ORG/NAME/PROVIDER), Git with ref and // subdirectories, HTTP URLs and archives. terraform init downloads remote modules into .terraform.

5b Describe variable scope within modules

  • Each module has its own scope: a child module sees only its own input variables, which the parent passes as module block arguments, and its local values are not visible outside it. -var, TF_VAR_ and tfvars files assign root module variables only. To return data, the child declares outputs that the parent reads with module.NAME.OUTPUT.

5c Use modules in configuration

  • A module block calls a child module with source, its input arguments and meta-arguments such as count, for_each, depends_on and providers. Default provider configurations are inherited, while aliased ones are passed with providers. After changing source or version you must run terraform init; moved relocates resources without destroying them, and removed with destroy = false forgets them.

5d Manage module versions

  • The version argument works only for registry modules and accepts constraints such as =, !=, >=, < or ~>; without it, Terraform takes the newest version. The .terraform.lock.hcl file does not record modules, so an exact version is how you pin a third-party module. terraform init leaves installed modules unchanged; terraform init -upgrade updates them within the constraint.

6. Terraform state management

6a Describe the local backend

  • With no backend or cloud block, Terraform uses the local backend: it stores state in terraform.tfstate relative to the root module, locks it with system APIs and runs operations locally. Non-default workspaces go to terraform.tfstate.d (or workspace_dir). The file is plaintext and may hold secrets, so keep it out of Git.

6b Describe state locking

  • If the backend supports it, Terraform locks state automatically and silently on every operation that could write it; if it cannot get the lock, it stops. -lock-timeout retries for a while and -lock=false disables locking (not recommended). terraform force-unlock LOCK_ID releases only your own lock when automatic unlocking failed and does not touch infrastructure.

6c Configure remote state using the backend block

  • The backend block is nested in the terraform block; only one is allowed, it cannot use variables or locals and it cannot coexist with a cloud block. With partial configuration the block stays empty and terraform init -backend-config supplies the rest, overriding the file. Pass credentials as environment variables: -backend-config leaves them in .terraform and in plan files.

6d Manage resource drift and Terraform state

  • To detect drift without changing anything, run terraform plan -refresh-only and, if you accept the external change, terraform apply -refresh-only, which only updates state and outputs; terraform refresh is deprecated because it applies without confirmation. A normal apply reverts drift. -replace recreates degraded objects, moved renames without destroying and removed with destroy = false stops managing without destroying.

7. Maintain infrastructure with Terraform

7a Import existing infrastructure into your Terraform workspace

  • The recommended method is the import block (to and id), reviewed with terraform plan and applied with terraform apply; terraform plan -generate-config-out writes a starting resource block to a new file that you should prune. The terraform import command only writes to state, generates no configuration and runs locally, without access to an HCP Terraform workspace's variables.

7b Use the CLI to inspect state

  • terraform state list prints the addresses of resources in state (filterable by address, module or -id) and terraform state show prints the attributes of a single resource, formatted for humans. terraform show presents the state or a saved plan, with -json for tools; terraform state pull prints the raw state to stdout and terraform output reads root module outputs (-json or -raw).

7c Describe when and how to use verbose logging

  • Detailed logs help you debug unexpected errors and report bugs. TF_LOG turns them on in stderr with the levels TRACE, DEBUG, INFO, WARN or ERROR (JSON gives TRACE in an unstable JSON format); TF_LOG_CORE and TF_LOG_PROVIDER separate Terraform from the providers, and TF_LOG_PATH appends the output to a file, but only when a level is set.

8. HCP Terraform

8a Use HCP Terraform to create infrastructure

  • HCP Terraform performs runs in a workspace through three workflows: VCS (repository webhooks and speculative plans on pull requests), CLI (terraform login, the cloud block and terraform init; plan and apply run remotely with output in the terminal) and API (your tooling uploads the configuration as .tar.gz). In Local execution mode the workspace only stores state.

8b Describe HCP Terraform collaboration and governance features

  • HCP Terraform enforces Sentinel or OPA policy sets on every run: advisory only warns, soft-mandatory and OPA mandatory can be overridden with the right permission, and hard-mandatory cannot unless the set allows it. Teams get additive permissions at organization, project and workspace level; the explorer, change requests and health assessments add visibility and governance.

8c Describe how to organize and use HCP Terraform workspaces and projects

  • An HCP Terraform workspace holds the configuration, variables, state and history of one collection of infrastructure, and every workspace belongs to exactly one project (the Default Project unless you choose another). Projects group workspaces with their own permissions, variable sets and execution mode; run triggers and remote state sharing connect workspaces.

8d Configure and use HCP Terraform integration

  • The cloud block inside the terraform block connects a working directory to HCP Terraform workspaces by name or tags, and terraform login stores the API token. In the CLI-driven workflow, terraform plan starts a remote speculative plan and terraform apply a remote run; VCS-driven and API-driven workflows also exist, and dynamic credentials avoid static secrets.