70 questions / 10 random questions
Random questions, instant feedback, and review for missed questions.
View recommended Terraform Associate resources →
A team wants different engineers to reproduce the same cloud environment. What is the most relevant benefit of using Terraform?
Answer: Declarative configuration can be version-controlled as code
Terraform represents desired infrastructure in configuration files that teams can review and version-control.
You reapply the same Terraform configuration after the infrastructure already matches it. What result is normally expected?
Answer: No changes are proposed when there is no difference
Terraform compares configuration, state, and remote objects and reports no changes when they already match.
After cloning a Terraform repository for the first time, which command prepares the required providers and modules?
Answer: terraform init
terraform init initializes the working directory and prepares its backend, providers, and modules.
A team must apply exactly the changes that reviewers approved for production. Which workflow is appropriate?
Answer: Save with terraform plan -out=tfplan, then run terraform apply tfplan
Passing a saved plan to apply executes the same plan that reviewers inspected.
In CI, you want to check Terraform configuration syntax and internal consistency without changing infrastructure. Which command is most appropriate?
Answer: terraform validate
terraform validate checks configuration syntax and internal consistency without modifying remote resources.
An environment variable must accept only dev, stg, or prod, and invalid input should fail early. What should you use?
Answer: A validation block inside the variable block
Input variable validation defines a condition and error message so invalid values fail early.
A computed naming string is reused by several resources but should not be exposed as external input. What should you use?
Answer: A locals block
Local values name reusable expressions inside a configuration without exposing them as caller inputs.
Subnets are keyed by name, and adding another name should preserve stable identity for existing instances. Which meta-argument fits best?
Answer: for_each
for_each identifies instances by map or set keys, providing stable, meaningful resource addresses.
A team shares one configuration and must prevent concurrent state updates from corrupting state. Which approach is most appropriate?
Answer: Use a remote backend that supports state locking
Shared remote state with locking provides one source of truth and prevents conflicting writes.
A resource block is renamed, but the remote object must not be recreated. How can you record this refactor in configuration?
Answer: Add a moved block from the old address to the new address
A moved block maps the old address to the new one so Terraform can update state without recreating the object.
An existing manually created object must be brought under Terraform management. What is the essential first concept?
Answer: Associate the remote object with a resource address in state
Import associates an existing object with a Terraform resource address in state; matching configuration is also needed for ongoing management.
An output is marked sensitive = true. Which statement about this setting is correct?
Answer: It redacts normal CLI display, but state still requires protection
Sensitive marking reduces accidental display, but the value can still exist in state, which needs access control and encryption.
A team must use the same provider source and compatible version range. Where should these requirements be declared?
Answer: required_providers in the terraform block
required_providers declares source addresses and version constraints, while the lock file records selected versions.
The same AWS provider must manage resources in two regions. Which method is appropriate?
Answer: Give one provider configuration an alias and select it on resources
Provider aliases let a configuration define multiple instances of one provider and select or pass them explicitly.
A root module needs the VPC ID created by a child module. What must the child module provide?
Answer: An output that exposes the VPC ID
A child-module output is its public interface and can be referenced as module.name.output_name.
A Registry module is used in production. Which setting best reduces unexpected breaking changes?
Answer: Specify a version constraint in the module block
A Registry module version constraint controls eligible releases so upgrades can be reviewed.
A pull request should trigger a plan in a shared environment for team review. Which HCP Terraform setup is appropriate?
Answer: Use a workspace connected to the VCS repository
A VCS-connected workspace can start remote runs from commits or pull requests and share plans with the team.
Infrastructure changes that violate organization rules must be rejected before apply. Which HCP Terraform concept addresses this?
Answer: Apply policy as code to runs
Policy as code evaluates plans against organization rules and can block or warn on noncompliant runs.
CI must authenticate to a cloud provider without storing long-lived access keys in Terraform variables. Which approach is preferred?
Answer: Use short-lived credentials or workload identity federation with the provider
Short-lived credentials or OIDC-style dynamic authentication reduce storage and exposure of static secrets.
terraform plan reports that an argument is not present in the provider schema. What should you check first?
Answer: The selected provider version and its matching documentation
Provider resource schemas can vary by version, so inspect the lock file, selected version, and matching documentation.
Which best describes Terraform declarative approach?
Answer: You describe the desired end state and Terraform determines how to reach it
You declare the desired state, and Terraform plans and applies the changes needed to converge from the current state.
Which correctly distinguishes terraform plan from apply?
Answer: plan shows the proposed changes and apply actually makes them
plan presents the diff without changing anything; apply executes the plan against real infrastructure.
Which command automatically rewrites configuration files to the canonical style?
Answer: terraform fmt
terraform fmt formats HCL to the canonical style, easing reviews and stabilizing diffs.
To avoid accidentally destroying managed resources, what should you check before destroy?
Answer: The destroy plan output and the target workspace/environment
destroy can remove all managed resources in the target; always confirm the workspace and the destroy plan.
You want to create a replacement before destroying the old one to avoid downtime. Which lifecycle setting fits?
Answer: create_before_destroy = true
create_before_destroy provisions the new resource before deleting the old one during replacement, reducing downtime.
You want to ignore drift on specific attributes to avoid unnecessary changes. Which setting fits?
Answer: ignore_changes in lifecycle
ignore_changes tells Terraform to ignore drift on listed attributes, avoiding needless changes from external updates.
Which is an appropriate measure given that the Terraform state file can contain secrets?
Answer: Use an encrypted remote backend and restrict access
State may hold plaintext secrets, so protect it with an encrypted backend and access controls.
To detect drift between state and real infrastructure without making changes, what do you use?
Answer: terraform plan (which refreshes and shows drift)
plan refreshes against reality and reports drift versus configuration without changing infrastructure.
Which file, generated by terraform init, records the exact selected provider versions for reproducibility?
Answer: .terraform.lock.hcl (dependency lock file)
The lock file pins selected provider versions and hashes so every environment uses the same versions.
Which command intentionally upgrades providers and updates the lock file?
Answer: terraform init -upgrade
init -upgrade updates providers/modules within constraints and refreshes the lock file.
When calling a module, what do you define so callers can pass values in?
Answer: Input variables
Module input variables are the entry point for caller parameters, while outputs are the exit for results.
You want to reuse a common network setup across projects. What is the appropriate Terraform approach?
Answer: Extract a reusable module and call it with a version constraint from each place
Extracting a module and pinning its version improves maintainability and consistency across reuse.
Which is a key benefit of remote runs in HCP Terraform?
Answer: Runs plan/apply in a shared environment with centralized state and run logs
Remote runs execute centrally, unifying state, logs, access, and variables for team operations.
Which is appropriate when receiving a secret value through a variable?
Answer: Mark it sensitive = true and pass it securely without committing tfvars
Mark secret variables sensitive to redact display, pass them via secured tfvars/env/secret stores, and remember the value can persist in state.
An apply fails because it cannot acquire the state lock. What should you check or do first?
Answer: Check whether another run is in progress, and only carefully force-unlock a stale lock
First confirm no concurrent run; only force-unlock a genuinely stale lock, carefully. Deleting state casually is dangerous.
Which command checks whether Terraform configuration syntax and references are valid before creating resources?
Answer: terraform validate
terraform validate checks configuration syntax, arguments, and references. It does not make infrastructure changes through remote APIs.
If an environment variable, terraform.tfvars, and a command-line -var set the same variable, which value has the highest precedence?
Answer: The value specified with command-line -var
Terraform input variables can be assigned in several ways, and command-line -var or -var-file assignments have higher precedence than normal tfvars files and environment variables.
You want to bring an existing manually created cloud resource under Terraform management without deleting it. What is the appropriate operation?
Answer: Use terraform import to associate the existing resource with state
terraform import associates an existing object with a Terraform resource address in state. You normally also write matching configuration and inspect the next plan.
Which statement best describes Terraform workspaces when you want separate dev and test state for the same configuration?
Answer: A mechanism to switch between multiple states in the same configuration directory
A workspace separates state for the same configuration. For larger environment or access separation, directory and workspace design must be chosen carefully.
In HCP Terraform, which approach is most appropriate for stopping plans that violate organizational rules before apply?
Answer: Evaluate plans with policy as code
HCP Terraform can use policy as code to evaluate a plan against organizational rules and warn or block execution when violations are found.
When renaming a resource from aws_instance.old to aws_instance.web, how can you record the address change without recreating the real object?
Answer: Declare the source and destination in a moved block
A moved block tells Terraform that a resource address changed so the same remote object can be tracked at the new address. Confirm with plan that no recreation is proposed.
For troubleshooting, you want to explicitly request replacement of one managed resource on the next apply. Which plan option is appropriate?
Answer: -replace=RESOURCE_ADDRESS
-replace requests a plan that replaces the specified managed object. Reviewing and then applying a saved plan lets you verify the intended change first.
You want subnet_ids to accept only a set of strings. Which type constraint is appropriate?
Answer: set(string)
set(string) represents an unordered collection of unique strings. Choose another type such as list(string) when order or duplicates matter.
Production and development have very different permissions, change rates, and blast radii. Which state design is appropriate?
Answer: Separate state and access controls by environment
Separating state and permissions by environment reduces lock contention and blast radius while limiting production access.
You need resources in both Tokyo and Osaka using the same AWS provider. Which configuration is appropriate?
Answer: Define provider aliases and pass the appropriate provider to each resource or module
Use aliases for multiple configurations of the same provider. Select them with a resource provider meta-argument or a module providers argument.
You want to create keyed instances of the same module for several environments. Which approach is appropriate?
Answer: Set for_each on the module block
A module block can use for_each and pass each.key or each.value into inputs. The keys also become part of module instance addresses.
An output must contain a secret value. What should you set to suppress its normal display?
Answer: sensitive = true
Marking an output sensitive redacts it in CLI and UI display, but does not encrypt it or remove it from state. Secure the state backend with encryption and access controls too.
A dependency cycle error appears during plan. What is the most appropriate response?
Answer: Review mutual references and unnecessary depends_on entries so dependencies flow one way
A cycle occurs when dependencies loop, such as A depending on B while B depends on A. Remove or redesign references and depends_on entries to form an acyclic graph.
You want resource names to include the active CLI workspace. Which expression returns the current workspace name?
Answer: terraform.workspace
terraform.workspace returns the active CLI workspace name. It can help with naming, but workspaces alone do not provide strong access isolation.
In HCP Terraform, which feature applies shared non-secret and secret variables across multiple workspaces?
Answer: A variable set
A variable set can provide shared variables to multiple workspaces. Mark secret values sensitive to restrict viewing and reduce exposure in logs.
Why can Terraform manage AWS, Azure, and SaaS configurations through the same workflow?
Answer: Providers implement API operations for each target while Terraform provides a common declarative workflow
Terraform Core handles configuration, dependency graphs, plans, and state, while providers implement resource types and communication with target APIs. This separation enables a common workflow across services.
An external ordering constraint cannot be inferred from resource expressions. What should you use to declare the dependency explicitly?
Answer: The depends_on meta-argument
depends_on declares a hidden dependency Terraform cannot infer from references. Prefer implicit dependencies through attribute references and use it only when necessary.
Before creating a resource, you must verify that the selected AMI uses x86_64 and stop with a custom message if it does not. What is appropriate?
Answer: A precondition inside lifecycle
A precondition validates assumptions for resources, data sources, or outputs during planning and supports a custom condition and error message.
A short-lived API token is used for provider authentication but must not be stored in plan or state files. Which Terraform 1.12 approach is appropriate?
Answer: Set ephemeral = true on the input variable and also use sensitive = true when appropriate
Ephemeral values are available during a run but omitted from plan and state files. Sensitive redacts display, so secret values may use both settings together.
Which statement correctly describes a provider-supported write-only argument such as password_wo?
Answer: It passes the value to the provider without retaining it in Terraform plan or state
Write-only arguments are provider-implemented and pass values during an operation without persisting them in plan or state. Some implementations use a companion version argument to signal updates.
You want to declaratively import an existing resource and review generated resource configuration. Which approach is appropriate?
Answer: Write an import block and use terraform plan -generate-config-out=generated.tf
An import block declares the destination address and ID in configuration. A plan with generate-config-out can write a proposed resource configuration when it is not already present.
You need detailed Terraform CLI logs on stderr to investigate unexpected behavior. What should you do?
Answer: Set TF_LOG to a log level such as DEBUG or TRACE
TF_LOG enables detailed logs at levels such as TRACE, DEBUG, INFO, WARN, or ERROR. Logs may contain sensitive data, so disable and handle them securely after troubleshooting.
In HCP Terraform, which feature groups many workspaces by application or team and provides a boundary for permissions and policies?
Answer: Projects
HCP Terraform Projects organize related workspaces and provide a grouping for managing team access, policies, and related controls.
After a network workspace applies successfully, you want to automatically queue a run in a dependent application workspace. Which HCP Terraform feature fits?
Answer: A run trigger
A run trigger queues a run in a dependent workspace after a successful apply in a source workspace. Auto-apply for triggered runs is controlled separately from the normal auto-apply setting.
When HCP Terraform runs connect to a cloud provider, which approach reduces stored long-lived access keys?
Answer: Use dynamic provider credentials to obtain short-lived credentials for each run
Dynamic provider credentials use a trust relationship such as OIDC to issue short-lived cloud credentials for a run, reducing exposure from stored long-lived keys.
In Terraform 1.7 or later, you are handing a managed resource to another team. How can you record a reviewable change that relinquishes management without destroying it?
Answer: Use a removed block with destroy = false
Replace the resource declaration with a removed block naming its address and setting lifecycle destroy to false. Review the plan to confirm only management is relinquished. Agree who will manage subsequent changes.
You delete an entire Terraform resource block that contained prevent_destroy = true. With no other protection, does that setting still prevent destruction?
Answer: No, because removing the declaration also removes this guard
prevent_destroy rejects destruction plans while present in configuration. Removing the declaration removes this guard; it is not a permanent external control. Use plan review and appropriate cloud-side protection for critical resources.
In CI, terraform plan -detailed-exitcode exits with code 2 and shows no errors. How should this result be interpreted?
Answer: Treat it as a successful plan with changes for review
With detailed-exitcode, zero means no changes, one means error, and two means successful planning with changes. CI must distinguish these outcomes. A plan has not applied infrastructure changes.
A normal Terraform variable contains a secret and plan -out=tfplan saves the plan. The CLI redacts it as sensitive. How should the saved plan be stored?
Answer: Restrict access and retention because it may contain secrets
CLI redaction does not remove ordinary sensitive values from saved plans. Treat plan artifacts as potentially secret-bearing: control access, retention, and encryption rather than relying on display redaction.
In Terraform 1.6 or later, a terraform test run uses real providers and omits command. Which execution environment is appropriate?
Answer: Use an isolated test environment and check for leftover resources
The default run command is apply, which can create real and billable resources. Use isolated test credentials and check cleanup failures. Explicitly use command = plan for appropriate tests that should not apply changes.
In Terraform 1.5 or later, a check block assertion is false with no unrelated configuration error. What matters when considering it for enforcing a mandatory condition?
Answer: Failure warns, so distinguish it from blocking validation
Failed check assertions warn rather than normally blocking execution. Use variable validation or resource preconditions for suitable mandatory conditions. Observing unhealthy infrastructure differs from prohibiting a change.
A for_each map uses IDs of resources that will be created, so planning fails because its keys are unknown. What change is appropriate?
Answer: Use known logical names as keys and keep generated IDs as values
for_each needs known keys to establish instance addresses during planning. Use stable logical keys and store generated IDs as values. Conversion and dependency declarations do not make unknown values known.
A parent module defines an aliased provider aws.dr, and a child also references aws.dr. How should that configuration be supplied to the child?
Answer: Declare the child alias and map it in the caller's providers argument
Aliased provider configurations are not inherited automatically. Declare aws.dr in the child's configuration_aliases and map it explicitly using providers = { aws.dr = aws.dr } at the call site. Version requirements and configuration wiring are separate.
A shared .terraform.lock.hcl is committed, yet a Registry module with a version range may resolve to a newer release. Why?
Answer: The dependency lock file records provider selections, not modules
The dependency lock file records provider selections and checksums, not remote module versions. Pin an exact module version or use the appropriate immutable reference for its source when strict reproducibility is required.
You change Terraform backends and need to copy existing state to the new backend. After pausing changes and securing a backup, which initialization option performs migration?
Answer: Run terraform init -migrate-state for the changed backend
-migrate-state attempts to copy existing state into the new backend. Verify workspace mapping and review the subsequent plan for unexpected recreation. -reconfigure instead reinitializes backend configuration without migrating existing state.