Terraform Associate 004 Cheatsheet
HashiCorp Certified: Terraform Associate (004)
Download free PDFInfrastructure as code and providers
Declarative infrastructure
- **Infrastructure as code (IaC)** expresses infrastructure in reusable, version-controlled files. Teams can review proposed changes, share modules and automate repeatable provisioning.
- **Declarative configuration** describes the desired result. Terraform compares configuration, recorded state and provider observations to plan the actions needed to reach it.
- **Immutable infrastructure** replaces components with newly configured instances rather than repeatedly modifying them in place. This reduces accumulated differences and makes replacement more predictable.
- **Review and automation** reduce drift and mistakes; they do not guarantee correct configuration, zero downtime, lower cost or automatic scaling. Keep secrets outside the configuration repository.
Core and provider responsibilities
- **Terraform Core** evaluates configuration and dependencies. Separate **provider plugins** implement resource and data-source operations through service APIs; they are not built into the core binary.
- **Providers** cover public clouds, on-premises systems and SaaS APIs. The CLI workflow stays the same across providers; resource types and provider settings vary.
- In **resource "aws_vpc" "main"**, aws_vpc is the resource type, main is the local resource name, and aws is the conventional provider local name. The full resource address is **aws_vpc.main**.
- **Custom providers** can support proprietary APIs. Hosting a service in a cloud does not automatically make that service manageable by the cloud provider's Terraform plugin.
Provider selection and aliases
- **required_providers** declares provider source addresses and version constraints. A **provider** block configures access, such as region and authentication; configurations normally refer to provider local names.
- **terraform init** installs required official, partner and community providers. Configured installation mirrors and plugin caches can supply packages without a fresh public-internet download; raw source code is not a runnable plugin.
- **alias = "west"** creates an additional configuration of the same provider. A resource selects it with **provider = aws.west**; the unaliased configuration is the default.
- **.terraform.lock.hcl** records selected provider versions and checksums. Commit it for consistent installations; **terraform init -upgrade** selects newer versions allowed by the constraints.
Terraform CLI workflow
Initialize the working directory
- **Write → init → plan → apply** is the core workflow. Initialize a new checkout before planning or applying; initialization does not create a starter main.tf or provision infrastructure.
- **terraform init** initializes the backend, installs providers and retrieves referenced modules. Run it again after changing backend settings or module/provider requirements; it is safe to repeat.
- **.terraform/** holds downloaded providers, modules and working-directory metadata, including backend information. Default local resource state is **terraform.tfstate**, outside that directory.
- **terraform init -upgrade** updates eligible dependency selections within constraints. It does not override an exact version pin or supply required input variable values.
Format, validate and inspect
- **terraform fmt** rewrites configuration to canonical style in the current directory. Use **-check** to report formatting differences without writing and **-recursive** to include subdirectories.
- **terraform validate** checks syntax and internal consistency, including undeclared references and duplicate resource addresses. It needs installed dependencies but does not test remote API permissions or deployed infrastructure.
- **terraform console** evaluates expressions interactively. **terraform show** displays state or a saved plan; **terraform output** reads declared root-module outputs.
- **TF_LOG** enables diagnostic logging, with levels such as DEBUG and TRACE. **TF_LOG_PATH** selects a log file; it does not enable logging by itself. Treat diagnostic logs as potentially sensitive.
Plan and apply changes
- **terraform plan** previews creates, updates, replacements and destroys. It normally refreshes observations from provider APIs but does not apply infrastructure changes or commit that refreshed snapshot to state.
- **terraform plan -out=tfplan** saves an executable plan; **terraform apply tfplan** applies it without another approval prompt. A saved plan can contain sensitive values and must be protected.
- **terraform apply** without a saved plan creates a fresh plan and requests approval. A prior standalone plan is not reused, so intervening changes can alter the proposed actions.
- **Stale saved plans** must be regenerated when another operation has changed the state. Disabling locking cannot make an outdated plan valid. Applying changes updates infrastructure and recorded state, not the configuration files.
Dependencies and controlled changes
- **References** create implicit dependencies. Terraform builds a graph from configuration and state and can operate on independent objects in parallel; file order does not control creation order.
- **depends_on** declares hidden dependencies when no value reference captures the relationship. Put it on the object that must wait, naming the prerequisite resource or module.
- **-replace=ADDRESS** requests replacement of a specific managed object. **-target=ADDRESS** limits planning to a selected object and its dependencies; reserve targeting for exceptional recovery or troubleshooting.
- **terraform destroy** plans removal of resources managed in the current state and asks for approval by default. Removing a resource block and applying also normally destroys its tracked object; unrelated objects in the same cloud account are outside that state.
Configuration language and conditions
Blocks, addresses and values
- **resource** declares an object to manage; **data** reads information without managing the queried object's lifecycle. Read attributes as **aws_instance.web.id** and **data.aws_ami.web.id** respectively.
- **All .tf files in one directory** form a single module. Splitting main.tf into files in the same directory does not change resource addresses; subdirectories are separate modules unless explicitly called.
- **var.name** reads an input; **local.name** reads a local value. Locals name reusable expressions and can reference other locals, provided there is no dependency cycle.
- **String templates** embed expressions: **"${data.azurerm_resource_group.example.name}-vnet"**. A local can combine a variable with **random_id.suffix.hex** once and reuse the result.
Input variables and types
- **variable** blocks can declare type, description, default and sensitivity. A variable without a default requires a caller-supplied value; providing a default makes the input optional.
- **string**, **number** and **bool** are primitive types. **list(T)** is ordered, **set(T)** contains unique unordered values, and **map(T)** associates string keys with values of one type.
- **object({...})** describes named attributes with individual types; **tuple([...])** describes positional element types. **map(string)** suits string-valued tags. **optional(T)** applies to object attributes, not a standalone variable type.
- **Indices start at zero**: var.sizes[1] selects the second list element. Use descriptive variable names; module meta-argument names such as source, version, count and for_each are reserved.
- **TF_VAR_name**, variable files and **-var** can supply root inputs. Keep secret-bearing files out of version control; command-line secrets can appear in history. A child module receives inputs as arguments in its module block.
Collections and repetition
- **count** creates indexed instances, such as **aws_instance.web[1]** for the second instance. **count.index** is the current zero-based index.
- **for_each** creates instances keyed by a map or set of strings, such as **aws_instance.web["api"]**. Keys should be stable and known before apply; count and for_each cannot be combined on one block.
- **var.servers[*].id** and **[for server in var.servers : server.id]** collect id attributes. Wrapping an existing splat expression in another pair of brackets creates an extra nesting level.
- **dynamic** blocks generate repeated nested configuration blocks from a collection. They do not create independent resource instances or generate lifecycle meta-arguments.
- **max(18, 3, 7)** returns the largest number; expand a list with **max(var.numcpus...)**. **join("-", ["team", "vnet"])** combines strings; **concat** combines lists.
Validation and lifecycle rules
- **validation** inside a variable block checks input requirements using a condition and error_message. A failed validation stops the operation when the condition can be evaluated.
- **precondition** and **postcondition** blocks enforce assumptions and guarantees. Failed preconditions prevent the associated action; failed postconditions stop downstream dependent actions. Unknown values defer evaluation until enough data is available.
- **count and for_each** are expanded before resource preconditions are evaluated, so conditions can refer to count.index or each.key. A resource can have both preconditions and postconditions.
- **check** blocks report failed assertions as warnings and allow the operation to continue. Use them for ongoing health observations rather than mandatory deployment gates.
- **create_before_destroy** requests the replacement first when possible. **prevent_destroy** rejects destructive plans while configured. **ignore_changes** allows selected externally managed attributes; none guarantees uptime or protects against direct cloud deletion.
Reusable modules and outputs
Module boundaries and interfaces
- **Root module** means the configuration being executed; **child modules** are called with module blocks. A module groups resources and exposes a deliberate input/output interface.
- **source** identifies the child module. Pass a literal with **servers = 3**, or forward a root input with **servers = var.num_servers**. Parent variables and locals are not automatically visible inside the child.
- **output** blocks require a value expression. Description and sensitive are optional; outputs do not have a default argument. A child output can expose one of its locals or resource attributes.
- **module.production.hostnames** reads the hostnames output of the module call named production. To print a child output with apply or output, declare a root output whose value references it.
Module sources and version control
- **Module sources** include local paths, public or private registries and VCS repositories. Private Git sources require suitable credentials; registry listings document inputs, defaults and outputs.
- **version = "3.1.4"** pins a registry module exactly. **~> 3.1.4** permits patch releases below 3.2.0; **~> 3.1** permits releases below 4.0.0. A registry version constraint is optional but recommended.
- **version** applies to registry sources. Git sources select a revision with **?ref=TAG_OR_COMMIT**. The provider dependency lock file does not lock remote module versions.
- **terraform init** retrieves a newly referenced module or changed version requirement; **init -upgrade** reevaluates allowed upgrades. Registry availability is not proof that HashiCorp maintains or tests a module; review ownership and implementation.
State, backends and resource identity
What state records
- **State** maps Terraform resource addresses to real object identities and records attributes, metadata and outputs. Configuration describes intent; state records Terraform's knowledge of managed objects.
- **The local backend** stores state on disk by default as terraform.tfstate. State is not the Terraform binary, a provider cache or a saved execution plan.
- **Sensitive data** can appear in resource attributes, data-source results and outputs. Marking a variable or output **sensitive = true** redacts normal display; it neither encrypts the value nor excludes it from state.
- **Ephemeral values and resources**, and provider-supported **write-only arguments**, omit their values from state and plan files. Ephemeral values are restricted to compatible contexts; ordinary sensitive outputs remain stored.
Remote storage and locking
- **Remote backends** centralize state access for collaboration. Choose storage with appropriate access controls, encryption, backups and supported locking; remote state does not remove provider credential requirements or prevent drift.
- **backend** inside the terraform block selects state storage. A **cloud** block connects to HCP Terraform or Terraform Enterprise. Use one cloud configuration or backend configuration, not both or multiple cloud blocks.
- **terraform init -migrate-state** copies existing state after a backend change, including a move from local storage after the first apply. **-reconfigure** accepts backend configuration without migrating existing state.
- **State locking** prevents concurrent operations from modifying the same state. Support depends on the backend; locking is separate from encryption, authentication and backup.
- **terraform force-unlock LOCK_ID** clears an abandoned lock when automatic release has failed. Confirm the owning operation is no longer active; bypassing locks risks concurrent writes and state corruption.
Refresh and drift reconciliation
- **Drift** is a change outside Terraform. Normal plans and applies refresh managed-object observations by default; explicitly running refresh-only before every operation is unnecessary.
- **terraform plan -refresh-only** previews state and output changes without modifying remote objects or committing state. **terraform apply -refresh-only** records observed changes after approval without changing infrastructure.
- **A deleted managed object** is normally recreated on the next regular apply if its resource configuration still exists. To accept an intentional removal, update the configuration as well as reconciling state.
- **terraform state list** lists tracked addresses; **terraform state show ADDRESS** displays a tracked object's attributes. Use these to inspect an IP address when no output was declared; output cannot invent an undeclared output.
Import, move and forget objects
- **import** associates an existing object with a managed resource address. A basic import block declares **to = aws_instance.web** and a provider-specific **id**; add the corresponding resource configuration and review the plan.
- **Import does not create a new object** or make every object in an account managed. Reconcile configuration with the imported object to avoid unintended changes on the next apply; bind each object to one address.
- **moved** blocks declare address changes, such as renaming a resource or moving it into a child module. **from** and **to** preserve its identity instead of treating the refactor as destroy-and-create.
- **terraform state rm ADDRESS** forgets the binding without deleting the remote object. Also remove or adjust the corresponding configuration; otherwise a later plan may propose creating it again. Forgetting and destroying are different actions.
HCP Terraform collaboration and governance
Workspaces and shared execution
- **HCP Terraform workspaces** organize configuration, variables, state, run history and execution settings. They support remote runs, UI/API/CLI access and VCS integration.
- **CLI workspaces** select separate state instances for one working directory. An HCP workspace is a broader unit with its own configuration and permissions; the two meanings are not interchangeable.
- **VCS-driven workflow** uses pull requests for review and queues runs from configured repository events. Remote state storage alone, such as an S3 backend, does not provide HCP's remote execution workflow.
- **Projects** group related workspaces. Assign **teams** project or workspace permissions to separate ownership and control who may plan or apply; repository access alone is not a substitute for HCP permissions.
Variables and workspace dependencies
- **Variable sets** reuse Terraform or environment variables across selected workspaces. Mark secrets sensitive and restrict access; prefer short-lived dynamic provider credentials where supported.
- **Secret managers**, protected runtime environment variables and sensitive HCP variables keep credentials outside committed configuration. The sensitive flag does not remove a hardcoded secret or guarantee it cannot reach state.
- **tfe_outputs** reads published outputs from another authorized HCP workspace. **terraform_remote_state** also exposes root outputs, but its credentials can grant access to the full state snapshot; grant access deliberately.
- **Run triggers** are configured on the downstream workspace and queue a run after a successful upstream apply. Output sharing supplies data; triggers supply sequencing. Automatic apply depends on the downstream trigger auto-apply setting and run gates.
Policy and health assessments
- **Sentinel policies** evaluate planned changes before apply and can enforce controls such as private, encrypted storage. Policy enforcement levels determine whether a failure blocks or permits an override.
- **Run tasks** integrate external checks into the run workflow. **Cost estimation** estimates planned infrastructure cost; it is separate from health assessment and policy enforcement.
- **Health assessments** combine drift detection with continuous validation of configured conditions, including check blocks. They report health without automatically changing infrastructure or updating state.
- **Continuous validation** observes requirements after deployment. **Input validation and pre/postconditions** enforce configuration requirements during operations; **policy checks** govern runs across teams.