HashiCorp Certified: Terraform Associate (004) Quick Review

Quick Review for the HashiCorp Certified: Terraform Associate (004): Terraform workflow, HCL, providers, modules, state, and HCP Terraform.

This Quick Review is an IT Mastery study companion for candidates preparing for the HashiCorp Certified: Terraform Associate (004) exam from HashiCorp, exam code 004. Use it to refresh high-yield Terraform concepts before moving into topic drills, mock exams, original practice questions, and detailed explanations.

High-yield exam mindset

The Terraform Associate exam rewards practical understanding more than memorization. You should be able to look at a small Terraform configuration, predict what Terraform will do, choose the correct CLI command, and identify how state, providers, variables, modules, and HCP Terraform fit together.

What to prioritize first

PriorityKnow how to answer
Terraform workflowWhat init, fmt, validate, plan, apply, and destroy do — and what they do not do
StateWhy state exists, where it is stored, what locking protects, and why state may contain sensitive values
ProvidersHow provider plugins are selected, installed, versioned, configured, and aliased
HCL configurationBlocks, arguments, expressions, references, variables, locals, outputs, data sources, and resources
ModulesRoot vs child modules, module inputs/outputs, sources, versions, and provider inheritance
DependenciesImplicit references, explicit depends_on, lifecycle rules, count, and for_each
HCP TerraformRemote runs, state storage, VCS workflows, variables, private registry, policy features, and collaboration

Terraform’s purpose in one page

Terraform is an infrastructure as code tool. You write declarative configuration that describes desired infrastructure, and Terraform uses provider plugins to interact with external APIs.

ConceptTerraform meaningCommon trap
Declarative configurationYou describe the desired end stateYou do not normally write step-by-step imperative API calls
ProviderPlugin that knows how to manage a target platform or serviceThe provider is not the same as the cloud account itself
ResourceManaged infrastructure objectTerraform may create, update, replace, or destroy it
Data sourceRead-only lookup of existing informationData sources do not manage lifecycle
StateTerraform’s record mapping configuration to real objectsState can include sensitive values
PlanProposed change setA plan is not a guarantee that apply will succeed
ApplyExecutes a plan or creates and executes a new planApplying without a saved plan can produce a different plan than an earlier review

Terraform is commonly compared with configuration management tools. The key distinction: Terraform primarily manages infrastructure lifecycle through APIs. It is not a continuous configuration enforcement agent by default.

Core Terraform workflow

    flowchart LR
	    A[Write configuration] --> B[terraform fmt]
	    B --> C[terraform init]
	    C --> D[terraform validate]
	    D --> E[terraform plan]
	    E --> F{Review changes}
	    F -->|Accept| G[terraform apply]
	    F -->|Revise| A
	    G --> H[State updated]

Essential CLI commands

CommandPrimary purposeExam trap
terraform fmtRewrites configuration to canonical formattingDoes not check whether the infrastructure is valid
terraform initInitializes working directory, backend, providers, and modulesRequired before most other commands in a new or changed working directory
terraform validateChecks syntax and internal configuration validityDoes not fully verify cloud-side permissions, quotas, or runtime success
terraform planShows proposed actionsMay refresh state first; does not modify infrastructure
terraform applyApplies changesWithout a saved plan, Terraform creates a new plan
terraform destroyPlans and applies destruction of managed objectsActs on resources in state for the current configuration/workspace context
terraform showDisplays state or plan file in human-readable formUseful for inspecting saved plans and current state
terraform outputReads root module output valuesSensitive outputs may be redacted in CLI display
terraform stateAdvanced state inspection and modificationDoes not directly change real infrastructure unless paired with later plan/apply effects
terraform importAssociates existing infrastructure with Terraform stateImporting alone does not mean the configuration is complete or correct
terraform workspaceManages named state instances for one configurationWorkspaces are not a complete environment strategy by themselves
terraform consoleEvaluates Terraform expressions interactivelyHelpful for testing functions, types, and references

Saved plan decision rule

Use a saved plan when you need to guarantee that the reviewed plan is the exact plan applied:

  1. Run terraform plan -out=tfplan.
  2. Review the saved plan.
  3. Run terraform apply tfplan.

If you run terraform apply without the saved plan file, Terraform performs a fresh plan.

Terraform configuration structure

Terraform configuration is written in the Terraform language, commonly stored in .tf files.

Block typeExample formPurpose
terraformterraform { required_providers { ... } }Terraform settings, provider requirements, backend/cloud settings
providerprovider "aws" { region = "us-east-1" }Configures a provider instance
resourceresource "type" "name" { ... }Manages an object
datadata "type" "name" { ... }Reads existing information
variablevariable "region" { type = string }Declares an input variable
localslocals { name = "app" }Defines reusable local expressions
outputoutput "id" { value = resource.x.id }Exposes values from a module
modulemodule "network" { source = "./network" }Calls another module
movedmoved { from = ... to = ... }Records resource address refactoring
importimport { to = ... id = ... }Declares import of existing objects, where supported by provider/resource behavior

Blocks, arguments, and expressions

A common exam-style mistake is confusing the syntax elements.

Syntax itemMeaning
BlockContainer with a type, optional labels, and body
ArgumentAssigns a value to a name inside a block
ExpressionCalculates or references a value
ReferencePoints to another object, such as aws_instance.web.id
Meta-argumentSpecial Terraform argument like count, for_each, depends_on, provider, or lifecycle

Example resource address pattern:

resource_type.local_name.attribute

For a resource declared as resource "aws_instance" "web", the address is aws_instance.web.

Providers

Providers are plugins Terraform uses to interact with APIs. HashiCorp Terraform downloads required providers during terraform init based on configuration and dependency lock selections.

Provider requirements vs provider configuration

ItemLocationPurpose
required_providersInside terraform blockDeclares provider source and version constraints
provider blockTop-level blockConfigures provider settings such as region, endpoint, or credentials behavior
.terraform.lock.hclWorking directoryRecords selected provider versions and checksums
Provider plugin cache / .terraform directoryLocal working directory behaviorStores initialized dependencies for that working directory

High-yield distinction:

  • required_providers says which provider and acceptable versions.
  • provider blocks say how to configure provider instances.

Provider version constraints

ConstraintMeaning
>= 1.0.0Version must be at least 1.0.0
< 5.0.0Version must be below 5.0.0
= 4.2.0Exact version only
~> 4.16Compatible with 4.x beginning at 4.16, but not 5.0
~> 4.16.0Compatible patch releases beginning at 4.16.0, but not 4.17.0

Common trap: terraform init -upgrade can select newer provider versions allowed by constraints. Normal initialization respects the lock file unless changes require selection.

Provider aliases

Provider aliases let one configuration use multiple instances of the same provider, such as multiple regions or accounts.

ConceptExample use
Default providerUsed automatically when no alias is specified
Aliased providerUsed by resources with provider = provider_name.alias
Module provider passingChild modules may need explicit provider mapping when aliases are involved

Trap: Defining an aliased provider does not automatically make every resource use it. A resource or module must be associated with the correct provider instance.

Resources and data sources

Resource vs data source

FeatureResourceData source
IntentManage lifecycleRead existing information
Terraform stateTracked as managed objectRead result may be stored/known for planning
Can destroy real object?Yes, if managed and plan requires destroyNo, data sources are read-only
Typical exampleCreate a virtual networkLook up an existing image ID

Decision rule:

  • Use a resource when Terraform should own lifecycle.
  • Use a data source when Terraform should only look something up.

Resource actions in a plan

Terraform plans use action symbols. Know what they imply.

Plan symbolMeaning
+Create
-Destroy
~Update in place
-/+ or +/-Replace
<=Read data source

Replacement can occur when an argument cannot be updated in place according to provider behavior.

Variables, locals, and outputs

Input variables

Variables parameterize modules. Important attributes include:

AttributePurpose
typeConstrains expected value type
defaultMakes the variable optional
descriptionDocuments usage
sensitiveRedacts value in many CLI/UI displays
validationAdds custom validation rules
nullableControls whether null is allowed

Common trap: sensitive = true helps with display redaction, but it does not guarantee the value is absent from state.

Local values

Use locals for reusable computed expressions. They are not user inputs and cannot be overridden at runtime.

Use variable when…Use local when…
The caller should provide or override the valueThe value is derived internally
The value differs by environment or workspaceYou want to avoid repeating an expression
The module needs an input contractYou want a readable intermediate name

Outputs

Outputs expose values from the root module or child modules.

Output contextHow it is used
Root module outputDisplayed by terraform output, available to remote state consumers
Child module outputReferenced as module.module_name.output_name
Sensitive outputRedacted in normal display, but still may be in state

Trap: A child module’s internal resources are not directly part of the calling module’s interface. Use outputs to expose needed values.

Type system and expressions

Terraform has primitive, collection, and structural types.

Type categoryExamples
Primitivestring, number, bool
Collectionlist(string), set(string), map(number)
Structuralobject({ name = string }), tuple([string, number])
Dynamicany

Lists, sets, and maps

TypeKey featureCommon trap
listOrdered sequenceIndex-based addressing can cause churn
setUnordered unique valuesDo not rely on stable ordering
mapKey-value collectionKeys are strings
objectNamed attributes with typesGood for structured module inputs

Useful expression patterns

PatternPurpose
Conditional expressioncondition ? true_value : false_value
For expressionTransform collections
Splat expressionExtract attributes from multiple objects
FunctionsTransform strings, collections, files, encodings, dates, and more
nullOmit or unset values in many contexts
try()Return fallback when expression errors
can()Test whether expression can be evaluated

Do not overuse dynamic expressions in exam scenarios. Many questions test whether you know the simpler, clearer Terraform construct.

Dependencies and resource graph

Terraform builds a dependency graph from references.

Implicit vs explicit dependencies

Dependency typeCreated byBest use
ImplicitReferencing another object’s attributePreferred in most cases
Explicitdepends_onOnly when Terraform cannot infer the dependency

Example: If a resource uses aws_vpc.main.id, Terraform knows the VPC must exist first.

Common trap: Adding depends_on everywhere is not a best practice. It can make plans more conservative and harder to understand.

Lifecycle meta-argument

The lifecycle block changes how Terraform handles resource changes.

Lifecycle settingPurposeTrap
create_before_destroyCreate replacement before destroying old objectMay fail if names or unique constraints conflict
prevent_destroyBlocks plans that would destroy the objectCan block legitimate changes until removed
ignore_changesTells Terraform to ignore selected drift/config differencesCan hide unmanaged changes
replace_triggered_byReplaces resource when another object changesUse intentionally; it can force replacements

count and for_each

This is a frequent source of mistakes.

Featurecountfor_each
InputWhole numberMap or set of strings
AddressingIndex-based, such as [0]Key-based, such as ["prod"]
Best forSimple identical resourcesStable resources keyed by meaningful names
Churn riskHigher when list order changesLower when keys remain stable

Decision rule:

  • Use count for simple optional creation or identical repeated resources.
  • Use for_each when each instance has a stable identity.

Common trap: Removing item 1 from a list used with count can shift indexes and cause unintended changes. A map with for_each often avoids that problem.

Modules

A module is a container for Terraform configuration. Every Terraform configuration has a root module. A module called by another module is a child module.

Module basics

ConceptMeaning
Root moduleThe current working configuration where Terraform runs
Child moduleA module called by a module block
Module sourceLocal path, registry address, Git source, or other supported source
Module inputVariable value passed into the module
Module outputValue exposed back to the caller
Module versionVersion constraint for registry modules

Module source examples

Source styleExample meaning
Local pathUse module code from a local directory
Public registryUse a published module from the Terraform Registry
Private registryUse an internal module registry, such as in HCP Terraform
VCS sourceUse module code from a version control repository

Trap: terraform init downloads or installs modules. If you add or change module sources, run terraform init again.

Module input and output decision rule

A child module should not rely on hidden assumptions in the root module. Pass required values as inputs, and expose only needed results as outputs.

Bad exam instinct: trying to directly reference a resource inside a child module from the root module.

Correct pattern: expose a child module output, then reference module.child.output_name.

State

Terraform state is central to how Terraform works. State maps configuration resource addresses to real infrastructure objects and stores metadata needed for planning.

Why state exists

State purposeExplanation
MappingConnects aws_instance.web to the actual remote object ID
PerformanceAvoids querying everything from scratch where possible
Dependency metadataTracks relationships and object details
Drift detectionHelps compare expected state with remote reality
CollaborationShared state enables teams to work on the same infrastructure safely when using remote state and locking

Local vs remote state

State modeCharacteristics
Local stateStored in local files, usually terraform.tfstate
Remote stateStored in a backend or HCP Terraform
State lockingPrevents concurrent state writes when supported by backend
Encryption/access controlDepends on backend or platform configuration

High-yield trap: Do not commit local state files to version control. State may contain secrets, IDs, generated passwords, and sensitive metadata.

Backend concepts

A backend defines where Terraform stores state and how operations interact with it.

Backend factExam relevance
Backend configuration is initialized by terraform initBackend changes usually require reinitialization
Backends are not providersProviders manage infrastructure; backends store state
Some backends support lockingLocking prevents concurrent state modification
HCP Terraform can store state and execute runsRemote execution changes where credentials and variables must be available

State commands

Use terraform state commands carefully.

Command patternEffect
terraform state listLists resources in state
terraform state show ADDRESSShows details for one state object
terraform state mvMoves/renames an address in state
terraform state rmRemoves an object from state without destroying the real object
terraform importAdds an existing real object to state at a resource address

Trap: Removing something from state does not delete the infrastructure. It only makes Terraform stop tracking it at that address.

Drift and refresh

Drift occurs when real infrastructure changes outside Terraform.

ActionMeaning
Refresh during planTerraform updates state’s view of remote objects before planning, unless disabled
Refresh-only plan/applyUpdates state to match remote objects without proposing normal configuration changes
Drift correctionTerraform may propose changes to bring remote objects back to configuration

Common trap: If someone changes infrastructure manually, Terraform does not magically prevent it. Terraform detects or responds to drift during later operations.

Workspaces

Terraform workspaces allow multiple state instances for the same configuration.

Workspace conceptMeaning
defaultInitial workspace
Named workspaceSeparate state for same configuration
Local workspaceManaged by Terraform CLI locally
Remote/HCP Terraform workspaceManaged in HCP Terraform context

Common traps:

  • Workspaces separate state, not code.
  • Workspaces are not a universal substitute for separate accounts, projects, directories, or environment-specific architecture.
  • The same configuration can behave differently if it uses terraform.workspace in expressions.

Files and directories to recognize

File or directoryPurpose
*.tfTerraform configuration files
*.tf.jsonJSON syntax variant of Terraform configuration
terraform.tfvarsCommon variable values file
*.auto.tfvarsAutomatically loaded variable values
.terraform.lock.hclProvider dependency lock file
.terraform/Local working directory data created by init
terraform.tfstateLocal state file when using local backend
terraform.tfstate.backupLocal backup state file
.terraformignoreExcludes files from upload in certain remote operation contexts

Variable value precedence

For local CLI usage, if the same variable is set in multiple places, later/higher-precedence sources override earlier/lower-precedence sources.

Precedence orderSource
LowerEnvironment variables such as TF_VAR_name
terraform.tfvars
terraform.tfvars.json
*.auto.tfvars and *.auto.tfvars.json, in lexical order
Higher-var and -var-file options, in command-line order

Trap: Variable declarations define the input contract. Variable value files provide values; they do not declare variables.

Provisioners

Provisioners run scripts or commands as part of resource creation or destruction. Terraform supports provisioners such as local-exec and remote-exec.

Exam-safe rule: provisioners are a last resort. Prefer provider-native resources, images, cloud-init, configuration management, or other purpose-built mechanisms when possible.

Provisioner ideaTrap
local-exec runs on the machine running TerraformIn remote execution, that machine is not your laptop
remote-exec runs on a remote resourceRequires connectivity and credentials
Provisioners can failFailures can leave infrastructure partially created
Provisioners are not full lifecycle managementThey are not a substitute for declarative resources

HCP Terraform review

HCP Terraform is HashiCorp’s managed platform for Terraform collaboration, automation, state, and governance capabilities. Terraform Enterprise provides related capabilities for self-managed enterprise environments.

HCP Terraform capabilities to recognize

CapabilityWhat it means for exam scenarios
Remote state storageState is stored centrally rather than only on a local machine
State lockingHelps prevent concurrent runs from corrupting state
Remote runsPlan/apply can execute in HCP Terraform instead of locally
VCS-driven workflowRuns can be triggered by version control changes
CLI-driven workflowCLI can initiate runs connected to HCP Terraform
Variables and variable setsStore and reuse workspace variables
Private registryShare internal modules and providers
Run historyReview prior plans and applies
Team access controlsManage collaboration permissions
Policy and governance featuresApply organizational controls to runs, depending on platform features and configuration

Remote execution trap

If Terraform runs remotely, credentials, environment variables, files, and network access must be available to the remote execution environment. Do not assume your local shell environment is available.

Local CLI executionHCP Terraform remote execution
Uses local machine contextUses remote run environment
Local credentials may be availableWorkspace/platform variables or integrations are needed
Local files are availableOnly uploaded/included workspace files are available
State may be local or remoteState is managed by HCP Terraform workspace

Security and sensitive data

Terraform configurations often touch credentials, generated secrets, and infrastructure identifiers.

Security topicHigh-yield point
Sensitive variablesRedact display but may still be stored in state
Sensitive outputsRedact normal CLI output but may still be in state
State filesProtect them like sensitive data
Version controlDo not commit secrets, local state, or private variable files
Provider credentialsPrefer secure mechanisms supported by the provider/platform
Remote state accessLimit access to people and systems that need it

Common trap: Marking a value sensitive is not encryption by itself. It is primarily a display-handling feature in Terraform.

Common exam traps and corrections

TrapCorrect understanding
terraform fmt validates cloud resourcesfmt only formats configuration
terraform validate proves apply will succeedIt checks configuration validity, not all remote API conditions
A plan always applies successfullyPermissions, quotas, drift, API errors, or changes after planning can cause failure
A data source manages existing infrastructureData sources read; resources manage
State is optionalState is fundamental to Terraform operation
State is always safe to shareState may contain sensitive data
Backends and providers are the same thingBackends store state; providers manage APIs
depends_on should be used everywherePrefer implicit dependencies from references
count is always safer than for_eachfor_each is often safer for stable keyed resources
Child module resources should be referenced directlyUse module outputs
Sensitive values never enter stateThey can still be present in state
Workspaces fully separate environmentsThey separate state for the same configuration
Import creates perfect Terraform codeImport associates state; configuration still must match desired management
Removing from state destroys infrastructureIt only stops tracking the object at that address
apply reuses the last plan automaticallyIt creates a new plan unless given a saved plan file
Provider aliases apply automaticallyResources/modules must use or receive the aliased provider

Quick decision tables

Which Terraform construct should you choose?

NeedUse
Create and manage infrastructureresource
Look up existing infrastructuredata
Parameterize a modulevariable
Reuse an internal computed valuelocals
Return a value from a moduleoutput
Repeat similar resources by numbercount
Repeat resources by stable namesfor_each
Force an otherwise invisible dependencydepends_on
Change create/destroy behaviorlifecycle
Package reusable configurationmodule
Store state remotelyBackend or HCP Terraform
Collaborate with remote runs and shared stateHCP Terraform

Which command should you choose?

ScenarioBest command
New working directory with Terraform filesterraform init
Changed provider constraintsterraform init or terraform init -upgrade when intentionally upgrading
Changed module sourceterraform init
Check formattingterraform fmt -check
Fix formattingterraform fmt
Check configuration syntax/internal validityterraform validate
Preview changesterraform plan
Apply exactly reviewed changesterraform plan -out=... then terraform apply ...
Show outputsterraform output
Inspect state addressesterraform state list
Import existing objectterraform import or an import block workflow where appropriate
Remove object from state onlyterraform state rm
Destroy managed infrastructureterraform destroy

Practice focus for the question bank

When you move from this Quick Review into IT Mastery practice, spend extra time on scenario questions. The exam often feels like “what should Terraform do next?” rather than “define this word.”

Use topic drills and original practice questions to test:

  1. Workflow recognition Identify the correct command for initialization, validation, planning, applying, importing, output inspection, and state inspection.

  2. Configuration reading Read small HCL snippets and predict references, dependencies, variable values, and resource addresses.

  3. State behavior Decide whether a command changes state, changes infrastructure, both, or neither.

  4. Module interfaces Trace inputs into a child module and outputs back to the root module.

  5. Provider setup Distinguish provider requirements, provider configuration, aliases, and lock file behavior.

  6. HCP Terraform scenarios Recognize when a run happens remotely, where variables must live, and how remote state/collaboration changes the workflow.

  7. Common traps Practice questions that contrast resource vs data, count vs for_each, variable vs local, backend vs provider, and local execution vs remote execution.

Final rapid review checklist

Before taking the HashiCorp Certified: Terraform Associate (004) exam, confirm that you can answer these without notes:

  • What does each core CLI command do?
  • What does terraform init install or configure?
  • What is stored in .terraform.lock.hcl?
  • How do provider version constraints work?
  • How are provider aliases used?
  • What is the difference between a resource and a data source?
  • Why does Terraform need state?
  • Why is remote state useful for teams?
  • Why can state be sensitive?
  • When should you use for_each instead of count?
  • How do modules receive inputs and expose outputs?
  • What does depends_on solve, and why should it be used sparingly?
  • What does lifecycle change?
  • What changes when Terraform runs in HCP Terraform instead of your local shell?
  • What does importing infrastructure do — and not do?

Next step: use a question bank with topic drills, original practice questions, mock exams, and detailed explanations to turn this Quick Review into exam-ready decision speed.

Continue in IT Mastery

Use this Quick Review as a final concept map, then move into IT Mastery for focused topic drills, mixed practice sets, timed mock exams, and detailed explanations. The practice questions are original IT Mastery practice items; they are not official HashiCorp questions, copied live-exam content, or exam dumps.