CertifyDeck
All cheat sheets
Terraform Infrastructure Engineer Professional (002) · CHEAT SHEET

HashiCorp Certified: Terraform Infrastructure Engineer Professional (002)

Key concepts grouped by official exam weight.

Download as PDF (free, no sign-up)

1. Scalable Terraform Configuration Design

1a Translate business requirements into infrastructure code

  • Translating requirements into code means picking the right construct: typed variables, optional() attributes with defaults and validation for rules that must stop the plan; for_each over a map when each instance has its own settings, and a conditional count to create a resource or not. In shared modules, the name prefix should be an input variable set by the caller.

1b Predictable and secure Terraform configuration

  • A predictable configuration refactors with moved blocks, which are kept because removing them is a breaking change, and keeps provider blocks out of shared modules. The style guide asks for a type and description on every variable, separate state per environment and no state or saved plans in version control; sensitive does not keep a value out of state.

1c Trace input variables, local values, and outputs to identify the source of a configuration issue

  • To find where a wrong value comes from, follow the variable -> local -> output chain: precedence (-var and -var-file, then *.auto.tfvars in lexical order, terraform.tfvars, TF_VAR_ and the default), type conversion (extra object attributes are discarded, list(string) converts numbers and bools) and scope: locals exist only in their module and a parent sees only the child's outputs.

1d Trace dynamic resources created with for_each

  • With for_each, each instance is identified by its map key or set member (resource["key"], or module.name["key"].resource when it is on the module); for a set, each.value equals each.key. Removing a key destroys only that instance, a for_each resource is used as a map of objects, and the keys must be known at plan time.

1e Predict the value of an expression that uses a Terraform function

  • To predict a function result, evaluate from the inside out: merge gives priority to the later argument, keys() and values() follow the lexical order of the keys, zipmap uses the highest index for a repeated key, slice includes the start and excludes the end, element wraps around with modulo, coalesce skips null and "" and try returns the first argument that does not fail.

1f Implement advanced configurations

  • Dynamic blocks generate repeatable nested blocks (never lifecycle or provisioner) and for and splat expressions transform collections; a splat on null yields an empty tuple. Variable validations, preconditions and postconditions stop the operation, while check blocks only warn. replace_triggered_by accepts only managed resources, so terraform_data carries plain values into it.

1g Configure Terraform providers

  • Provider configurations belong in the root module; child modules inherit only default configurations, and aliased ones are passed with the providers argument and declared with configuration_aliases. Each module declares its own required_providers with source and a minimum version, and .terraform.lock.hcl locks providers only; terraform providers lock -platform adds checksums for other platforms.

1h Use the Terraform MCP server to enhance development with AI coding agents

  • The Terraform MCP server is HashiCorp's Model Context Protocol server: it gives AI agents current provider, module and policy documentation from the registry instead of stale training data. The registry-private and terraform toolsets need a valid TFE_TOKEN, and destructive operations also need ENABLE_TF_OPERATIONS=true. It uses stdio locally and streamable HTTP for remote deployments; always review generated code.

2. Terraform State and Backend Operations

2a Create and manage Remote Backend and Remote State Configuration

  • The backend block cannot use variables: dynamic values go through partial configuration and terraform init -backend-config, and credentials preferably through environment variables. When changing backends, -migrate-state copies state and -reconfigure discards it. S3 locking is enabled with use_lockfile = true. terraform_remote_state exposes only root outputs and needs full state access; in HCP Terraform tfe_outputs is recommended.

2b Manage state and remediate drift

  • Drift appears when someone changes infrastructure outside Terraform. terraform plan -refresh-only shows it without changing anything and terraform apply -refresh-only records it in state without touching infrastructure; to keep the change, the configuration must also be updated or the next apply reverts it. New objects are imported, and -refresh=false or -target can hide drift.

2c Identify dependency chains before upgrades

  • Before upgrading, terraform providers shows which module declares each provider requirement and terraform graph shows dependency ordering. Terraform picks the newest version meeting every root and child constraint; the lock file pins only providers, and reusable modules should declare only a minimum. Keeping historical moved blocks preserves the upgrade path.

2d Upgrade Terraform versions across environments

  • required_version in the terraform block constrains only the CLI, accepts only constant values and must be met together with child module constraints, or init fails. A ~> constraint is recommended to pin major and minor versions while accepting patches. Applying with a newer release updates terraform_version in state and, when needed, its format, which cannot be reverted.

2e Inspect Terraform state

  • terraform state list prints addresses and filters by address, by module (including submodules) or by ID with -id; terraform state show displays a single instance and its output is meant for humans. For automation use terraform show -json, which includes only root module outputs and shows sensitive values in plain text; in a plan, scanning actions for "delete" catches deletions and replacements.

3. Infrastructure Lifecycle and Operations

3a Manage and scale infrastructure projects

  • To scale, split large systems into separate configurations along architectural boundaries, each with its own backend, and reuse modules through thin per-deployment roots instead of CLI workspaces. init installs new modules but leaves installed ones unchanged without -upgrade; version works only for registry sources, and Git sources use ref after the // subdirectory.

3b Plan changes to infrastructure

  • terraform plan without -out creates a speculative plan; with -out it saves an opaque file, holding sensitive values in cleartext, that terraform apply executes as is. Destroy and refresh-only modes are mutually exclusive; -replace forces a replacement, -target also includes the target's dependencies and is for exceptional cases, -refresh=false ignores external changes and -detailed-exitcode returns 0, 1 or 2.

3c Apply changes to infrastructure

  • If an apply fails, Terraform records what it already changed in state, unlocks it and exits without rolling back: fix the cause and apply again. A plan saved with -out is applied as it is, with no new options; -lock-timeout waits for the lock and force-unlock LOCK_ID only releases your own orphaned lock. Provisioners are a last resort, and on_failure and when control their failure handling and timing.

3d Import existing infrastructure to an infrastructure project

  • Configuration-driven import uses import blocks (to, id or identity, for_each and provider) with a destination resource block, and is previewed in a plan before state changes. terraform plan -generate-config-out writes a draft HCL file to a new path that you must review. Include non-default arguments, add relationships by hand and check that the plan does not destroy the imported object.

3e Manage infrastructure lifecycle

  • To stop managing a resource without destroying it, use a removed block with destroy = false; deleting the block destroys the object even with prevent_destroy, because that rule is not kept in state. moved blocks rename or relocate resources without replacing them and should be chained. create_before_destroy propagates to dependencies, ignore_changes shares management, and replace_triggered_by accepts only resources.

3f Manage multiple infrastructure environments

  • CLI workspaces are separate states inside one working directory and backend: good for temporary copies, but they do not isolate environments that need different credentials, where modules plus one root configuration and backend per environment are recommended. terraform.workspace adapts names and sizes; select -or-create and TF_WORKSPACE help in CI, and .tfvars files follow a fixed precedence order.

3g Troubleshoot deployment issues

  • terraform validate catches syntax and consistency errors, such as cycles, unknown each attributes or missing instance keys on for_each resources, without contacting remote services. TF_LOG, TF_LOG_CORE, TF_LOG_PROVIDER and TF_LOG_PATH produce logs to diagnose failures. timeouts blocks extend waits, and state pull and push let you repair state carefully, respecting serial and lineage checks.

3h Input and output data from infrastructure projects

  • terraform_remote_state exposes only root-module outputs and requires access to the whole state snapshot; in HCP Terraform the tfe_outputs data source is recommended and, for other consumers, data can be published to a separate store with a resource and data source pair. Variables follow a fixed precedence order, sensitive outputs remain in state and ephemeral outputs exist only in child modules.

3i Manage provider and module versions

  • The .terraform.lock.hcl file pins providers only: init reuses the recorded version and -upgrade picks the newest allowed one; modules are not locked, so they are pinned with an exact registry version or ?ref= for Git sources. Reusable modules declare only a minimum (>=) while root modules use ~>, and terraform providers lock -platform adds checksums for several platforms.

4. CI/CD and Automation Workflows

4a Manage CI/CD pipeline functionality

  • Automation uses init -input=false, plan -out=tfplan and apply tfplan: the plan file counts as approval, accepts no further options and stores sensitive data in cleartext. -detailed-exitcode returns 0, 1 or 2, TF_IN_AUTOMATION only changes output and TF_CLI_ARGS_name adds flags to one command. With HCP Terraform a saved plan needs local execution mode; remote execution uses speculative plans.

4b Understand deployment strategies

  • For several environments, use one backend with terraform workspace select or TF_WORKSPACE in automation, and -backend-config when backends differ. Keep only one outstanding plan at a time and auto-approve only non-critical infrastructure. State locking is automatic and silent, force-unlock needs the lock ID and only releases your own lock, and -plugin-dir or provider_installation control where providers come from.

4c Manage multiple sets of dynamic provider credentials across teams, projects, and workspaces

  • Dynamic credentials are enabled with TFC_* environment variables that can be shared through project-scoped, global or priority variable sets. Several configurations of the same provider in one workspace use tagged (_TAG) variables, each with its own token, and TFC_DEFAULT_* for shared values. Trust must check at least aud and sub.

4d Overwrite Terraform variables using auto.tfvars / .tfvars

  • Terraform applies variable values by precedence: -var and -var-file in command-line order, then *.auto.tfvars in lexical order, terraform.tfvars.json, terraform.tfvars, TF_VAR_ variables and the default. Only terraform.tfvars(.json) and *.auto.tfvars(.json) load automatically; other files need -var-file. In HCP Terraform, workspace variables overwrite *.auto.tfvars values.

5. Terraform Security and Governance

5a Identify best practices for secrets

  • sensitive hides values in the CLI and UI, but Terraform still stores them in state and plan files, and terraform output -json or -raw prints them in clear text. To avoid storing them, use ephemeral variables, ephemeral resources and write-only arguments. Keep state remote, encrypted, access-controlled and audited; HYOK encrypts state and plan with your own key.

5b Use secret rotation and integration with secrets management tools

  • To rotate a write-only argument, increment its version argument, because Terraform neither stores nor compares the value. Ephemeral resources open, renew and close a Vault secret's lease in each run. ignore_changes lets another tool rotate an attribute, terraform_data with replace_triggered_by forces a rotation, and apply -refresh-only syncs state.

5c Secure CI/CD pipeline identities and access

  • Dynamic provider credentials replace static keys: for each plan and apply HCP Terraform issues a signed workload identity token (JWT) that the cloud platform or Vault verifies, matching at least aud and sub including the organization, and returns temporary credentials; plan and apply can use separate roles. A remaining static secret is best kept as a sensitive environment variable or an ephemeral variable.

5d Establish core compliance/policy rules along with Team/Project specific policies

  • Core rules go in a globally enforced policy set (with exclusions by project, workspace or tag) and team rules in sets scoped to projects, workspaces or tags; several sets, even of different frameworks, can apply to the same workspace. Storing policies in VCS with sentinel.hcl adds review and traceability, and hard-mandatory without the set override option always blocks.

5e Identify and mitigate risky infrastructure changes

  • Review plan symbols (-/+ replace, - destroy) and use -detailed-exitcode and plans saved with -out, which hold sensitive values in cleartext. create_before_destroy changes replacement order and propagates to dependencies; prevent_destroy does not protect a deleted block (use removed with destroy = false). -target, -refresh=false and -lock=false are exceptional and risky.

6. Advanced Module Usage and Registry Practices

6a Understand when to refactor a Terraform configuration into a module

  • Write a module when you repeatedly provision the same collection of resources or when several resources form an architectural concept, not to wrap a single resource type. Keep the module tree flat, without provider blocks inside, and when moving resources into a module use moved blocks and terraform init. For versioned reuse, publish it to a registry.

6b Understand the contract of a Terraform module

  • A module's contract is its input variables (required when they have no default, with types and optional object attributes) and its outputs, which the parent reads as module.<NAME>.<OUTPUT>. A reusable module contains no provider blocks: it inherits default configurations, receives aliased ones through the providers argument, and declares configuration_aliases and only a minimum version (>=).

6c Use the Terraform registry to build or update a configuration

  • Public registry modules use <NAMESPACE>/<NAME>/<PROVIDER> and private ones prepend the hostname (app.terraform.io or localterraform.com); // marks a sub-directory. The version argument applies only to registries, and after changing it you run terraform init (-upgrade to move within the constraint): the lock file does not pin modules. In CI the token goes in TF_TOKEN_<host>.

6d Validate modules with Terraform unit tests

  • terraform test runs the .tftest.hcl files in the root directory and in tests/ with in-memory state and destroys what it created at the end. Run blocks default to command = apply; command = plan gives unit-style tests. mock_provider, mock_resource and the override_* blocks generate values without credentials; expect_failures tests conditions that must fail, and test file variables take the highest precedence.

7. HCP Terraform / Enterprise Operations

7a Understand how to operate HCP Terraform

  • A workspace is one root module, one set of inputs and one state, and supports policies, run tasks, run triggers and health assessments; Stacks repeat components across deployments and defer dependent changes. In the API-driven workflow you create a configuration version and upload a tar.gz with the configuration at its root; in VCS-connected workspaces it only allows speculative plans.

7b Track resource usage and cost

  • HCP Terraform counts every instance with mode = managed in all workspaces' state as a managed resource, including count, for_each and module instances, and excludes data sources. Cost estimation is enabled organization-wide and runs as a phase between plan and apply; it is disabled for -target runs and only Sentinel policy checks can read its data.

7c Implement multi-environment configuration

  • Environments are split into workspaces and projects: a project-scoped variable set reaches all current and future workspaces in the project, a workspace variable overrides the set's value, and conflicts between sets are resolved by the lexical order of set names. A priority set beats even -var, but only a policy guarantees compliance.

7d Upgrade Terraform versions across workspaces

  • Each workspace runs the Terraform version in its settings, exact or as a constraint (with ~> it uses the newest matching release). To upgrade: test with a plan-only run on the new version, update required_version and the workspace setting, and start an Allow empty apply run if state must be upgraded without changes. If state is incompatible, apply with a compatible version first.

7e Define Policy as Code in a CI/CD pipeline

  • Policies are published from CI/CD by connecting the policy set to a VCS repository, uploading tar.gz versions through the API, or with the tfe provider. sentinel.hcl must list every policy, and in OPA policies.hcl the default level is advisory. sentinel test validates policies in the pipeline, and pull-request speculative plans show policy results before merging.