Courseiva

HashiCorp Terraform Associate TF-004 (TF-004) — Questions 226300

428 questions total · 6pages · All types, answers revealed

Page 3

Page 4 of 6

Page 5
226
Matchingmedium

Match each Terraform feature to its description.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Maps real-world resources to configuration

Plugin to interact with a specific cloud or service API

Container for multiple resources used together

Defines where state snapshots are stored

Executes scripts on local or remote machine during creation/destruction

Why these pairings

Terraform State tracks resource states, Providers enable API interactions, Modules bundle resources for reuse, and Workspaces manage environments. Common confusions include swapping State with Provider or Provider with Module.

227
Drag & Dropmedium

Drag and drop the steps to set up remote state with Terraform Cloud in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

The correct order is to first create the workspace in Terraform Cloud, then add the cloud block to your Terraform configuration referencing that workspace, and finally run terraform init which detects the cloud block and migrates the state from local to the remote workspace. Other orders fail because the workspace must exist before the cloud block is configured or init is run without proper backend configuration.

228
MCQeasy

A user runs `terraform apply` and receives an error: 'Error acquiring the state lock'. What is the most likely cause?

A.Another user is running a Terraform command that modifies state.
B.The state file is missing.
C.The backend configuration is invalid.
D.The Terraform provider is incompatible.
AnswerA

When multiple Terraform operations attempt to modify the state file concurrently, Terraform employs a state locking mechanism to prevent corruption. If one user initiates a command like `terraform apply` or `terraform destroy` that acquires the state lock, any subsequent operation attempting to modify the state will encounter an "error acquiring state lock" message. This ensures data integrity by serializing state-modifying actions, preventing race conditions and inconsistent infrastructure deployments.

Why this answer

The error 'Error acquiring the state lock' means that another operation currently holds the lock on the state file. Option A is correct because if another user is running a Terraform command that modifies state (such as apply or destroy), the lock will be acquired and subsequent operations will fail. Option B is incorrect because a missing state file would produce a different error (e.g., 'No state file found').

Option C is incorrect because invalid backend configuration is caught during 'terraform init', not during 'apply'. Option D is incorrect because provider incompatibility typically leads to plugin-related errors, not state lock errors.

229
MCQmedium

An organization wants to use Terraform to manage resources across multiple accounts and regions, with different team members responsible for different environments. Which Terraform feature helps separate state and configuration for each environment?

A.Providers
B.Modules
C.Workspaces
D.Backends
AnswerC

Create separate state files for each environment.

Why this answer

Workspaces in Terraform allow you to manage multiple distinct sets of infrastructure resources (state files) within the same configuration. By using separate workspaces for each environment (e.g., dev, staging, prod), you can isolate state and configuration without duplicating code, making it the correct feature for this multi-environment scenario.

Exam trap

Terraform certification exams often test the misconception that backends alone provide environment isolation, but backends only define the storage location; without workspaces or manual state file separation, all environments would share the same state, leading to conflicts.

How to eliminate wrong answers

Option A is wrong because providers are used to define and configure the cloud provider (e.g., AWS, Azure) and its authentication, not to separate state or configuration per environment. Option B is wrong because modules are reusable configuration packages that encapsulate resource definitions, but they do not inherently provide state isolation across environments; multiple modules still share the same state file unless combined with workspaces or separate backends. Option D is wrong because backends define where state is stored (e.g., S3, Terraform Cloud), but they do not inherently separate state per environment; you would need to configure separate backend instances or use workspaces to achieve that isolation.

230
Multi-Selectmedium

Which TWO tasks are better suited for configuration management tools than Terraform?

Select 2 answers
A.Installing software packages
B.Managing network ACLs
C.Provisioning a VPC
D.Creating IAM roles
E.Configuring web server settings
AnswersA, E

Installing software packages on a server is a classic use case for configuration management tools such as Ansible, Chef, or Puppet. These tools excel at defining the desired state of an operating system, including which packages should be present, their versions, and ensuring they are installed idempotently. While Terraform provisions the underlying virtual machine, it does not typically manage the granular, post-provisioning software lifecycle within the guest OS.

Why this answer

Installing software packages and configuring web server settings are typical tasks for configuration management tools like Ansible or Puppet, as they operate on existing servers. Terraform, by contrast, is designed for provisioning infrastructure resources such as VPCs, IAM roles, and network ACLs. Therefore, options A and E are correct.

231
Multi-Selectmedium

Which TWO statements about Terraform state locking are correct?

Select 2 answers
A.State locking prevents concurrent modifications to the same state file.
B.State locking is enabled by default when using a local state backend.
C.State locking is not supported in Terraform Cloud.
D.State locking is only necessary when multiple team members are running terraform apply simultaneously.
E.State locking requires a backend that supports locking, such as S3 with DynamoDB table.
AnswersA, E

State locking is a critical mechanism that serializes access to the Terraform state file, ensuring that only one operation can modify it at any given time. This prevents race conditions and data corruption that could occur if multiple `terraform apply` or `terraform plan` operations attempted to write to the state simultaneously. By enforcing exclusive access, it maintains the integrity and consistency of the infrastructure's recorded state, which is essential for reliable infrastructure management.

Why this answer

State locking prevents concurrent modifications to the same state file, ensuring consistency. Option E is correct because state locking relies on backend support; for example, S3 requires a DynamoDB table to enable locking. Option B is false because local state backends do not support locking; it is not enabled by default.

Option C is false because Terraform Cloud fully supports state locking automatically. Option D is false because state locking is necessary for any operation that modifies state, even with a single user, to prevent corruption.

232
MCQeasy

After applying a module that creates a VPC, a user wants to use the VPC ID in another resource within the root configuration. How should they reference the output from the module?

A.vpc_id = module.vpc.vpc_id
B.vpc_id = module_vpc.vpc_id
C.vpc_id = data.module.vpc.vpc_id
D.vpc_id = local.vpc_id
AnswerA

This syntax, `module.<NAME>.<OUTPUT_NAME>`, is the canonical and correct way to reference an output value exported by a child module in Terraform. Here, `module.vpc` refers to the specific instance of the module named 'vpc' as defined in the calling configuration's `main.tf` or similar file. The `.vpc_id` then accesses the output variable explicitly defined within that `vpc` module, making its value available for use in other resources or outputs within the parent configuration. This pattern ensures clear and explicit data flow between module boundaries.

Why this answer

In Terraform, module outputs are accessed using the syntax `module.<module_name>.<output_name>`. Since the module is named `vpc` and it exposes an output called `vpc_id`, the correct reference is `module.vpc.vpc_id`. This allows the root configuration to consume the VPC ID created by the module.

Exam trap

The TF-003 exam often tests the exact syntax for referencing module outputs, and the trap here is that candidates confuse module output references with data source references (`data.`) or local values (`local.`), or they incorrectly use underscores instead of dots in the module path.

How to eliminate wrong answers

Option B is wrong because it uses an underscore (`module_vpc.vpc_id`) instead of the required dot notation (`module.vpc.vpc_id`); Terraform uses dots to separate the module keyword, module name, and output name. Option C is wrong because `data.` is used to reference data sources, not module outputs; module outputs are always accessed via `module.<NAME>.<OUTPUT>`. Option D is wrong because `local.vpc_id` would only be valid if a local value had been explicitly defined in the root configuration; it does not automatically capture module outputs.

233
MCQhard

An organization uses Terraform Cloud with a VCS-backed workspace connected to a GitHub repository. They want to trigger a speculative plan without creating a run (i.e., without costing compute resources or being displayed in the workspace). Which approach is appropriate?

A.Push a new commit to the GitHub repository with a 'plan' label.
B.Use the 'plan -out' flag with a special path to avoid creating a run.
C.Use the Terraform Cloud API to queue a plan with 'auto-apply' disabled.
D.Run 'terraform plan' from a local CLI configured with the same workspace and a remote backend.
AnswerD

When the local Terraform CLI is configured with a remote backend (like Terraform Cloud) and targets a specific workspace, executing `terraform plan` by default performs the plan operation locally. It fetches the remote state and configuration but executes the planning logic on the local machine without initiating a formal "run" in Terraform Cloud's UI or run history. This allows for quick, iterative validation of changes without consuming Terraform Cloud run credits or cluttering the run history.

Why this answer

Running 'terraform plan' from a local CLI configured with the same workspace and a remote backend triggers a speculative plan that is computed on Terraform Cloud but does not create a run record or consume run credits. This allows the user to preview changes without affecting the workspace's run history or incurring costs.

Exam trap

The trap here is that candidates confuse 'speculative plans' with regular runs, assuming any plan triggered from a local CLI will create a run record, when in fact the remote backend distinguishes between speculative and non-speculative plans based on the command context.

How to eliminate wrong answers

Option A is wrong because pushing a commit with a 'plan' label would trigger a VCS-driven run in Terraform Cloud, which creates a full run record and consumes compute resources. Option B is wrong because the 'plan -out' flag generates a plan file locally or in the remote backend, but it still creates a run in Terraform Cloud when used with a remote backend, and there is no special path to avoid run creation. Option C is wrong because using the Terraform Cloud API to queue a plan with 'auto-apply' disabled still creates a run object in the workspace, which is displayed and consumes compute resources.

234
Multi-Selectmedium

Which three of the following are required steps in the core Terraform workflow for managing infrastructure? (Choose three.)

Select 3 answers
.Write Terraform configuration files that define the desired state of resources.
.Run terraform init to initialize the working directory and download provider plugins.
.Run terraform plan to review the execution plan before applying changes.
.Run terraform destroy to remove all managed resources after every apply.
.Run terraform fmt to automatically fix formatting issues in configuration files.
.Run terraform validate to check configuration syntax before initializing the backend.

Why this answer

The core Terraform workflow consists of three essential steps: writing configuration files to define the desired state, running `terraform init` to initialize the working directory and download provider plugins, and running `terraform plan` to review the execution plan before applying changes. These steps form the fundamental 'write, plan, apply' cycle that Terraform uses to manage infrastructure declaratively. Without these, you cannot safely or correctly provision resources.

Exam trap

HashiCorp often tests the distinction between mandatory workflow steps and optional auxiliary commands, so the trap here is that candidates confuse helpful but non-essential commands like `terraform fmt` or `terraform validate` with the core required steps of write, init, and plan.

235
MCQhard

A team of five engineers uses Terraform with a remote backend in AWS S3 with DynamoDB state locking. One engineer runs 'terraform apply' but it hangs at 'Acquiring state lock'. What is the most likely cause?

A.Another engineer has an active lock from a previous run that was not released.
B.The S3 bucket policy denies the request.
C.A recent 'terraform init' was run without the proper backend configuration.
D.The DynamoDB table is in a different AWS region.
AnswerA

When Terraform attempts to acquire a state lock, it checks for an existing lock held by another operation on the remote backend. If a lock is found, Terraform will wait for a configurable timeout period, continuously retrying to acquire the lock. This mechanism prevents concurrent state modifications, ensuring state consistency in collaborative environments. An unreleased lock from a previous, possibly failed, run will cause subsequent operations to indefinitely wait or timeout until the lock is manually released or expires.

Why this answer

The most likely cause is that another engineer has an active lock from a previous run that was not released. Terraform uses DynamoDB state locking to prevent concurrent modifications to the state file. When `terraform apply` hangs at 'Acquiring state lock', it indicates that the lock item in the DynamoDB table is still present, meaning a prior operation either crashed, was interrupted, or the lock was not explicitly released via `force-unlock`.

Exam trap

HashiCorp often tests the distinction between a hang (lock contention) and a hard failure (access denied, region mismatch, or backend misconfiguration), so the trap here is that candidates may confuse a permission or configuration error with a lock acquisition timeout.

How to eliminate wrong answers

Option B is wrong because if the S3 bucket policy denied the request, Terraform would fail with an access denied error, not hang indefinitely at the lock acquisition phase. Option C is wrong because a recent `terraform init` without proper backend configuration would cause a backend initialization error or state mismatch, not a hang at the lock step. Option D is wrong because the DynamoDB table being in a different AWS region would cause a connectivity or access error, not a hang; Terraform would fail quickly with a timeout or region mismatch error.

236
MCQhard

A developer is troubleshooting a Terraform configuration that fails during `terraform plan` with the error: "Error: Invalid reference". The error points to a line that references `var.environment` in a module block. What is the most likely cause?

A.The Terraform version does not support module variables
B.The variable `var.environment` is not defined in the root module's variables.tf
C.The variable `environment` is not defined in the child module's variables.tf
D.The module source path is invalid
AnswerC

When a child module receives input values, it must explicitly declare those inputs as variables within its own scope, typically in a `variables.tf` file inside the module's directory. If the root module attempts to pass a value like `environment = var.environment` to a child module, the child module must have a corresponding `variable "environment" {}` block defined to accept that input. Without this declaration, the child module will report an error indicating an undefined variable when it tries to use `var.environment` internally, as it does not recognize `environment` as a valid input.

Why this answer

When a Terraform module block references a variable like `var.environment`, that variable must be defined in the child module's `variables.tf` file. The error 'Invalid reference' indicates Terraform cannot resolve the variable within the module's scope, meaning the child module does not declare an input variable named `environment`. Without this declaration, the module cannot accept the value passed from the root module.

Exam trap

HashiCorp often tests the distinction between root module variables and child module input variables, trapping candidates who assume `var.environment` must be defined in the root module's `variables.tf` rather than in the child module's `variables.tf`.

How to eliminate wrong answers

Option A is wrong because Terraform has supported module variables since version 0.10, and the error is not related to version compatibility. Option B is wrong because `var.environment` in a module block refers to a variable passed to the child module, not a root module variable; the root module's `variables.tf` is irrelevant here. Option D is wrong because an invalid module source path would produce a different error, such as 'Error: Failed to download module' or 'Error: Unreadable module directory', not an 'Invalid reference' error.

237
MCQhard

A team is using a remote backend for Terraform state. After merging a pull request that modifies the configuration, the pipeline runs `terraform plan` and sees an unexpected diff for a resource that was not changed in the code. The state file is up-to-date with the infrastructure. What is the most likely cause?

A.The provider version has been updated and includes a change to the resource schema
B.A previous `terraform state rm` command removed the resource from state
C.The state file is stale and needs to be refreshed
D.The actual infrastructure was modified outside of Terraform
AnswerD

When infrastructure resources are modified directly through the cloud provider's console, API, or CLI, these changes are not automatically recorded in Terraform's state file. This discrepancy between Terraform's desired state (from configuration and state file) and the actual state of the infrastructure is known as configuration drift. Running `terraform plan` will detect this drift by comparing the actual infrastructure with the state file and configuration, proposing actions to bring the infrastructure back into alignment with the Terraform configuration.

Why this answer

When infrastructure is modified outside of Terraform (e.g., via the cloud console, CLI, or another tool), the next `terraform plan` will detect a drift between the actual infrastructure state and the desired configuration in the code. Since the state file is up-to-date with the infrastructure, the unexpected diff indicates that the remote state accurately reflects the live environment, but the configuration no longer matches due to external changes. This is a classic case of configuration drift, which Terraform surfaces as a plan diff even when no code changes were made.

Exam trap

HashiCorp often tests the misconception that a stale state file is the default cause of unexpected diffs, but the key detail here is that the state is explicitly up-to-date, forcing candidates to recognize external modification as the root cause.

How to eliminate wrong answers

Option A is wrong because a provider version update that changes a resource schema would typically cause a diff for all resources of that type, not just one, and the scenario specifies only a single resource shows an unexpected diff. Option B is wrong because `terraform state rm` removes a resource from the state entirely, causing Terraform to see it as missing and attempt to create it, not produce a diff on an existing resource. Option C is wrong because the state file is explicitly stated to be up-to-date with the infrastructure, meaning it does not need a refresh; a stale state would show a diff due to missing or outdated data, but here the state matches the live infrastructure.

238
Matchingmedium

Match each Terraform provisioner to its typical use case.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Copy files to the remote resource

Run a script on the machine running Terraform

Run a script on the remote resource

Configure resource using Chef

Configure resource using Puppet

Why these pairings

The correct matches are: file provisioner for copying files to the remote machine, remote-exec for running commands on the remote machine, and local-exec for running commands locally. Common confusions include swapping the roles of file and remote-exec.

239
MCQmedium

An organization uses Terraform to provision infrastructure and then Ansible to configure it. They want to pass dynamic IP addresses from Terraform to Ansible. What is a recommended approach?

A.Use environment variables in the pipeline to pass IP addresses.
B.Use the terraform_remote_state data source in a dummy Terraform configuration.
C.Store outputs in Consul KV store and have Ansible read from there.
D.Use terraform output -json and parse it in Ansible as an inventory.
AnswerD

The terraform output -json command provides a structured, machine-readable JSON representation of all defined Terraform outputs. Ansible can natively consume dynamic inventories in JSON format, making this a highly efficient and idiomatic integration method. This approach directly leverages Terraform's output capabilities and Ansible's inventory system without requiring intermediate tools or complex parsing logic.

Why this answer

`terraform output -json` produces JSON output that can be parsed by Ansible to dynamically build an inventory. This approach is simple, directly uses Terraform's built-in output, and avoids additional infrastructure. Option A is incorrect: while environment variables can pass simple strings, they are less suitable for structured data like multiple IP addresses and are not the recommended pattern.

Option B is incorrect: `terraform_remote_state` is designed for fetching outputs from other Terraform configurations, not for exposing data to external tools like Ansible. Option C is incorrect: using Consul KV store introduces unnecessary complexity and external dependencies; the direct `terraform output` approach is simpler and more maintainable.

240
MCQhard

A DevOps team manages infrastructure for a large e-commerce platform using Terraform with a remote backend in an S3 bucket with DynamoDB state locking. Recently, a team member ran `terraform apply` from their local machine but the command failed with the error: 'Error acquiring the state lock: ConditionalCheckFailedException: The conditional request failed'. The state file is not locked according to the DynamoDB table. After investigation, the team finds that the DynamoDB table has a TTL attribute enabled on the 'LockID' field, and old lock records are automatically deleted after a few minutes. The team suspects that another engineer's `terraform plan` process from a CI/CD pipeline might have created a lock that was subsequently deleted by TTL before it was released, causing the conflict. Which action should the team take to prevent this issue from recurring?

A.Switch to using local state files to avoid the locking issue entirely.
B.Disable the TTL attribute on the DynamoDB table that stores lock information.
C.Increase the TTL value to 24 hours to ensure locks are not deleted during normal operations.
D.Use `terraform force-unlock` before each `terraform apply` to clear any stale locks.
AnswerB

Disabling the Time-To-Live (TTL) attribute on the DynamoDB table used for Terraform state locking is the correct solution. TTL automatically deletes items after a specified period, which can prematurely remove an active lock if a `terraform apply` operation takes longer than the TTL duration. This premature deletion would allow another concurrent operation to acquire a lock, leading to potential state corruption or resource conflicts. Ensuring locks persist until explicitly released by Terraform prevents such race conditions.

Why this answer

The error occurs because the DynamoDB table has a TTL attribute that automatically deletes lock records before the lock is released. Disabling TTL on the DynamoDB table ensures lock records persist until the lock is intentionally released, preventing false lock conflicts. Option A is incorrect because local state eliminates locking and central management.

Option C is incorrect because increasing TTL only delays deletion but does not guarantee the lock won't be deleted during a long-running operation. Option D is incorrect because force-unlock is a manual recovery step, not a preventive measure.

241
MCQhard

A Terraform configuration includes a resource block with a 'lifecycle' block that has 'create_before_destroy = true'. During an apply, the create step succeeds but the destroy step fails. What is the resulting state?

A.Only the new resource remains in state, old resource is destroyed.
B.The state is empty for that resource address.
C.Only the old resource remains in state.
D.Both the old and new resources are in state.
AnswerD

This option is correct. When a Terraform configuration is modified in a way that causes Terraform to perceive a new resource (e.g., changing a resource's logical name, or modifying `count`/`for_each` indices) while the original resource is not explicitly destroyed or its destruction fails, both resources will be tracked in the state file. The state reflects the current reality of the managed infrastructure, including any resources that were created but not yet removed.

Why this answer

When `create_before_destroy = true` is set, Terraform creates the new resource first, then destroys the old one. If the destroy step fails after the new resource is created, both resources exist in the state file because Terraform does not remove the old resource from state until the destroy operation completes successfully. The state retains both resource instances at the same address, which is why option D is correct.

Exam trap

HashiCorp often tests the misconception that a failed destroy step automatically removes the old resource from state or that Terraform rolls back the entire operation, but in reality, Terraform only removes a resource from state after a successful destroy.

How to eliminate wrong answers

Option A is wrong because the old resource is not destroyed when the destroy step fails, so it remains in state alongside the new resource. Option B is wrong because the state is not empty; the new resource was successfully created and added to state, and the old resource is still present due to the failed destroy. Option C is wrong because the new resource was created and added to state before the destroy attempt, so both resources are recorded, not just the old one.

242
MCQhard

A Terraform state file is stored in an S3 bucket with versioning enabled. During a deployment, the state file becomes corrupted due to a network error. What is the best way to recover?

A.Use `terraform state pull` to overwrite the corrupted state.
B.Run `terraform import` to import all resources.
C.Restore the previous version of the state file from S3 versioning.
D.Delete the state file and run `terraform apply` to recreate all resources.
AnswerC

S3 versioning, when enabled on the bucket storing the Terraform state file, automatically retains multiple historical versions of the state object. In the event of state file corruption, an administrator can directly access the S3 bucket, locate the corrupted state file, and restore a previous, known-good version of that file. This action effectively rolls back the Terraform state to a functional point, allowing operations to resume without data loss or manual reconciliation.

Why this answer

S3 versioning preserves previous versions of objects, including Terraform state files. When the current state file becomes corrupted, you can restore a prior, uncorrupted version directly from the S3 bucket without data loss or manual re-creation of resources. This is the safest and most efficient recovery method.

Exam trap

A common trap is assuming that `terraform state pull` can fix corruption, but it only retrieves the current state; the real recovery mechanism is S3 versioning.

How to eliminate wrong answers

Option A is wrong because `terraform state pull` retrieves the current state from the configured backend (S3), but if the state file is already corrupted, pulling it will only fetch the corrupted data, not fix it. Option B is wrong because `terraform import` is used to bring existing infrastructure under Terraform management, not to recover a corrupted state file; it would require manually importing every resource, which is error-prone and time-consuming. Option D is wrong because deleting the state file and running `terraform apply` would cause Terraform to attempt to create new resources, potentially leading to duplicate infrastructure or conflicts with existing resources, and it does not recover the previous state.

243
MCQmedium

An organization stores state files in an S3 backend with encryption. However, some resource attributes (e.g., database passwords) are stored in plaintext within the state. What is the recommended approach to avoid storing sensitive values in state?

A.Use a secrets backend like Vault to retrieve secrets at runtime and store only references in state
B.Set the `sensitive` parameter on all resources
C.Enable state encryption with a stronger algorithm
D.Use the `terraform state rm` command after apply to remove sensitive attributes
AnswerA

Integrating Terraform with a dedicated secrets backend, such as HashiCorp Vault, allows sensitive values to be retrieved dynamically at runtime using data sources. This approach ensures that the actual secret values are never directly written into the Terraform state file. Instead, the state only contains non-sensitive references or identifiers, significantly reducing the risk of exposure if the state file is ever compromised, even if encrypted. This method adheres to the principle of least privilege by keeping secrets out of persistent storage.

Why this answer

Terraform can mark outputs as sensitive to hide them from display, but they may still be stored in state. Option A is a common practice to avoid storing secrets directly.

244
MCQhard

You are managing a Terraform configuration that uses a public module from the registry to deploy an AWS VPC. The module is defined with a version constraint of '~> 3.0'. After running 'terraform init', you run 'terraform plan' and notice that the plan output indicates the module will be updated from version 3.18.0 to 3.20.1. However, you are concerned because the module's changelog shows that version 3.19.0 introduced a breaking change: it removed the 'enable_dns_hostnames' variable and replaced it with 'enable_dns_support'. Your configuration currently uses the 'enable_dns_hostnames' variable. You want to avoid any breaking changes in the production environment while still receiving non-breaking updates. What should you do?

A.Fork the module repository and maintain a custom version that retains the 'enable_dns_hostnames' variable.
B.Change the version constraint to ">= 3.0.0, < 3.19.0" and run 'terraform init -upgrade'.
C.Change the version constraint to "~> 3.18.0" to stay within the 3.18.x releases.
D.Update the configuration to use the new 'enable_dns_support' variable and update the module to version 3.20.1.
AnswerC

This pins to the 3.18.x range, avoiding the breaking change in 3.19.0 while still getting patch updates.

Why this answer

The version constraint '~> 3.18.0' restricts updates to only patch versions within the 3.18.x series (e.g., 3.18.1, 3.18.2), which will never include the breaking change introduced in 3.19.0. This allows you to receive non-breaking bug fixes and security patches while avoiding the removal of the 'enable_dns_hostnames' variable. The pessimistic version constraint operator (~>) in Terraform locks the major and minor version when specified with three segments, ensuring no unexpected breaking changes from higher minor versions.

Exam trap

HashiCorp often tests the nuance of the pessimistic version constraint operator (~>) in Terraform, specifically that '~> 3.0' and '~> 3.18.0' have very different behaviors, and candidates mistakenly assume both only allow patch updates.

How to eliminate wrong answers

Option A is wrong because forking the module and maintaining a custom version introduces unnecessary overhead and defeats the purpose of using a public module; it also bypasses the version constraint mechanism entirely. Option B is wrong because the constraint '>= 3.0.0, < 3.19.0' would still allow Terraform to upgrade to any version from 3.0.0 up to 3.18.x, but running 'terraform init -upgrade' would upgrade to the latest allowed version (3.18.x), which is safe, but the constraint is overly broad and does not leverage the pessimistic operator for precise control; more importantly, it would not prevent a future upgrade to 3.19.0 if the upper bound were accidentally removed. Option D is wrong because updating the configuration to use 'enable_dns_support' and upgrading to 3.20.1 would require rewriting your code to adapt to the breaking change, which contradicts the goal of avoiding breaking changes in production.

245
MCQeasy

A developer wants to use a module from the Terraform Registry in their configuration. Which block is required in the root module?

A.module "my-module" { source = "..." }
B.resource "my-module" { ... }
C.provider "my-module" { source = "..." }
D.data "my-module" { ... }
AnswerA

The `module` block is the correct and exclusive construct for calling a reusable collection of Terraform configurations. It encapsulates a set of resources, data sources, and other modules, promoting reusability and organization within your infrastructure code. The mandatory `source` argument specifies the module's origin, which can be the Terraform Registry, a local path, or a remote Git repository, enabling Terraform to fetch and utilize its defined infrastructure components.

Why this answer

To use a module from the Terraform Registry, you must declare a `module` block in your root configuration. The `source` argument inside that block specifies the module's location (e.g., a registry path like `hashicorp/consul/aws`). This is the only way Terraform knows to fetch, version, and instantiate the module's resources.

Exam trap

A common trap in Terraform is confusing the `module` block with a `resource` block. Some candidates incorrectly think modules are declared as resources or data sources, but the correct syntax is `module "<name>" { source = "..." }`. The `source` argument is required to locate the module, and without it Terraform cannot fetch and instantiate the module's resources.

How to eliminate wrong answers

Option B is wrong because `resource` blocks define infrastructure objects (e.g., `aws_instance`), not external modules; a module is not a resource type. Option C is wrong because `provider` blocks configure providers (e.g., `aws`), not modules; the `source` argument is invalid in a provider block. Option D is wrong because `data` blocks fetch read-only information from existing resources, not from modules; modules can contain data sources, but the block itself cannot reference a module.

246
Multi-Selecteasy

Which TWO statements about Terraform modules are correct?

Select 2 answers
A.The count meta-argument is not supported on module blocks.
B.Module outputs are automatically available as inputs to other modules in the same configuration.
C.Module sources must include a version constraint to ensure reproducibility.
D.A module can be called multiple times in the same configuration with different input variables.
E.The source attribute of a module can be a Git repository URL with a specific commit SHA.
AnswersD, E

This statement is correct. One of the primary benefits of Terraform modules is their reusability, allowing a single module definition to be invoked multiple times within the same root configuration. Each invocation can be given a unique local name and supplied with different input variables, enabling the deployment of distinct instances of similar infrastructure components. This pattern promotes DRY (Don't Repeat Yourself) principles and simplifies managing complex, multi-environment, or multi-tenant infrastructure.

Why this answer

Terraform modules can be called multiple times with different input variables, enabling reuse. Option E is correct because module sources can be Git repository URLs with a specific commit SHA (e.g., using `?ref=<sha>`). Option A is incorrect because the `count` meta-argument is supported on module blocks in Terraform 0.13 and later.

Option B is incorrect because module outputs are not automatically available; they must be referenced explicitly as `module.<module_name>.<output_name>`. Option C is incorrect because version constraints are optional for reproducibility; they are recommended but not mandatory.

247
MCQmedium

During a terraform apply, the process crashes mid-way. The state file may be in an inconsistent state. What is the first recommended step to recover?

A.Run terraform force-unlock.
B.Run terraform apply with -auto-approve.
C.Run terraform plan.
D.Run terraform destroy.
AnswerC

Running terraform plan is the most appropriate first step after a terraform apply crash. This command safely reads the current Terraform state, compares it against the desired configuration, and then queries the actual remote infrastructure to detect any drift or incomplete changes. The resulting detailed execution plan provides crucial visibility into the current perceived state of resources and precisely what Terraform intends to do, allowing the operator to assess the situation, identify inconsistencies, and formulate a recovery strategy without making any further modifications.

Why this answer

Terraform plan will show the current state and pending changes, allowing you to diagnose the situation. Option A is wrong because force-unlock is only for lock issues, not state inconsistency. Option B is wrong because re-running apply may fail again or cause further issues.

Option D is wrong because terraform destroy would remove all resources, not just the half-created ones.

248
MCQeasy

A team is migrating from using local state to a remote backend for collaboration. They want to ensure that team members cannot overwrite each other's changes. Which feature should they enable?

A.State locking (e.g., DynamoDB)
B.S3 bucket versioning
C.Force unlock command
D.Workspace isolation
AnswerA

When migrating to a remote backend, state locking is essential to prevent concurrent Terraform operations from corrupting the shared state file. This mechanism ensures that only one `terraform apply` or `terraform plan` operation can modify the state at any given time. Backends like S3, when configured with DynamoDB for locking, acquire an exclusive lock before modifying the state, releasing it upon completion. This critical feature maintains state integrity in collaborative environments.

Why this answer

State locking prevents concurrent modifications by ensuring that only one operation can modify the Terraform state at a time. When using a remote backend like S3 with DynamoDB, Terraform acquires a lock before writing to the state file and releases it after completion, preventing race conditions and state corruption.

Exam trap

HashiCorp often tests the distinction between state locking (preventing concurrent writes) and state versioning (enabling rollback), causing candidates to confuse S3 versioning as a solution for overwrite prevention.

How to eliminate wrong answers

Option B is wrong because S3 bucket versioning tracks changes and allows recovery of previous state versions, but does not prevent concurrent writes or overwrites. Option C is wrong because the force unlock command is a manual override to release a stuck lock, not a feature to prevent overwrites. Option D is wrong because workspace isolation separates state files for different environments but does not coordinate access within the same workspace.

249
MCQmedium

During 'terraform apply', a user receives an error: 'Error: Error creating resource: Resource already exists'. The resource does not appear in the Terraform state. What is the most likely cause?

A.The state file was migrated from a different backend and the resource is duplicated.
B.The resource was removed from the configuration but not from state.
C.The user forgot to run terraform refresh before apply.
D.The resource was manually created outside of Terraform before the apply.
AnswerD

When Terraform executes `terraform apply`, it compares the desired state defined in the configuration with the known state recorded in its state file. If a resource is defined in the configuration but is entirely absent from the state file, Terraform assumes this resource needs to be provisioned. If an identical resource, perhaps with the same unique name or identifier, was previously created directly within the cloud provider environment, the cloud API will reject Terraform's creation request, resulting in an 'already exists' error.

Why this answer

The error 'Resource already exists' indicates that the resource was created outside of Terraform's management (e.g., manually via the cloud console or CLI). Since the resource does not appear in the Terraform state, Terraform attempts to create it during 'terraform apply', but the underlying API rejects the request because the resource already exists in the cloud provider. This is a common state drift scenario where the real-world infrastructure is out of sync with the Terraform state.

Exam trap

HashiCorp often tests the misconception that 'terraform refresh' can fix state drift issues like this, but refresh only updates existing state attributes—it does not import unmanaged resources into the state, so the apply will still fail.

How to eliminate wrong answers

Option A is wrong because migrating a state file from a different backend would not cause a 'Resource already exists' error during apply; it would either succeed or fail with state-related conflicts, not an API-level duplicate resource error. Option B is wrong because if a resource was removed from configuration but not from state, 'terraform apply' would not attempt to create it—it would simply leave the resource in state and unmanaged, not trigger a creation error. Option C is wrong because 'terraform refresh' updates the state file to match real-world resources, but it does not prevent the 'Resource already exists' error; the error occurs because Terraform tries to create a resource that already exists, and refresh alone does not import that resource into state.

250
MCQmedium

During development, a Terraform user wants to check that their configuration is syntactically valid and internally consistent before running 'terraform plan'. Which command should they use?

A.terraform init
B.terraform refresh
C.terraform validate
D.terraform fmt
AnswerC

The `terraform validate` command performs a static analysis of the Terraform configuration files in the current directory, checking for syntax errors, argument type mismatches, and internal consistency. It ensures that the configuration is syntactically correct and semantically valid according to Terraform's language rules, without requiring any backend or provider initialization. This command is crucial for catching configuration issues early, before attempting to interact with any remote infrastructure or state.

Why this answer

The `terraform validate` command checks that a Terraform configuration is syntactically valid and internally consistent, such as verifying that resource names are unique and that references to other resources or data sources are correctly formed. It runs without requiring any cloud provider credentials or state, making it ideal for early-stage validation before `terraform plan`.

Exam trap

HashiCorp often tests the distinction between validation and formatting, so the trap here is that candidates confuse `terraform fmt` (which only fixes code style) with `terraform validate` (which checks for actual errors in the configuration).

How to eliminate wrong answers

Option A is wrong because `terraform init` initializes the working directory by downloading provider plugins and modules, but it does not validate the configuration's syntax or internal consistency. Option B is wrong because `terraform refresh` updates the state file with real-world infrastructure, which requires existing state and credentials, and it does not perform configuration validation. Option D is wrong because `terraform fmt` rewrites configuration files to a canonical format and style, but it does not check for syntactic or semantic validity.

251
Multi-Selectmedium

Which three of the following are valid methods for reading, generating, or modifying Terraform configuration? (Choose three.)

Select 3 answers
.Using the `terraform fmt` command to automatically update configuration files to a canonical format and style.
.Using the `templatefile` function to render a template from a file, substituting variables at runtime.
.Using `terraform console` to interactively evaluate expressions and inspect resource attributes.
.Using the `terraform state push` command to directly edit the state file and then reflect those changes back into the configuration.
.Using the `merge` function to combine multiple map values, but only when the source maps are defined in separate Terraform modules.
.Using the `terraform plan -generate-config-out` flag to automatically create configuration from existing infrastructure.

Why this answer

The `terraform fmt` command rewrites configuration files to a canonical format and style, which is a valid method for modifying configuration. The `templatefile` function reads a template file and renders it with supplied variables, enabling dynamic configuration generation. The `terraform console` command provides an interactive shell for evaluating expressions and inspecting resource attributes, which is a valid way to read and test configuration logic.

Exam trap

HashiCorp often tests the distinction between state manipulation commands and configuration generation commands, leading candidates to confuse `terraform state push` (a state management operation) with a method to modify configuration, or to incorrectly assume `terraform plan` has a `-generate-config-out` flag when it is actually `terraform import` that supports this feature.

252
MCQeasy

A team is using a module from the Terraform Registry and wants to ensure they always get the latest patch version of the 3.2.x series. Which version constraint should they use?

A.~> 3.2
B.3.2.*
C.~> 3.2.0
D.>= 3.2, < 4.0
AnswerC

This allows only patch-level increments within 3.2.x (e.g., 3.2.0 to 3.2.1).

Why this answer

The `~>` (pessimistic constraint) operator in Terraform allows only the rightmost version component to increment. For `~> 3.2.0`, this means any version >= 3.2.0 and < 3.3.0, which precisely matches the requirement for the latest patch within the 3.2.x series. Option C is correct because it locks the major and minor versions while permitting patch-level updates.

Exam trap

A common trap in Terraform is confusing the `~>` operator with two versus three numbers. `~> 3.2` allows minor version updates (e.g., 3.3, 3.4), while `~> 3.2.0` restricts updates to only patch versions (e.g., 3.2.1, 3.2.2). Candidates often mistakenly choose `~> 3.2` thinking it constrains to the 3.2.x series, but it actually allows any 3.x version.

How to eliminate wrong answers

Option A is wrong because `~> 3.2` allows both minor and patch updates (i.e., >= 3.2.0 and < 4.0.0), which would permit 3.3.x or 3.4.x, not just the 3.2.x series. Option B is wrong because `3.2.*` is not a valid Terraform version constraint syntax; Terraform uses the pessimistic operator or range constraints, not glob patterns. Option D is wrong because `>= 3.2, < 4.0` allows any version from 3.2.0 up to but not including 4.0.0, which includes minor version bumps (e.g., 3.3.0, 3.4.0) and not just patches within 3.2.x.

253
MCQmedium

A team of five engineers manages infrastructure using Terraform with remote state stored in an S3 bucket and state locking via a DynamoDB table. After a power outage, an engineer notices that a terraform apply command fails with the message: 'Error: Error acquiring the state lock'. The engineer suspects that a lock from a previous run has not been released. The team needs to proceed with applying changes. Which action should the engineer take to resolve the issue safely?

A.Wait for the lock to expire automatically (locks have a 5-minute TTL).
B.Delete the lock record from the DynamoDB table using the AWS CLI.
C.Run terraform force-unlock with the lock ID obtained from the error message.
D.Run terraform apply with the -lock=false flag to bypass locking.
AnswerC

The `terraform force-unlock` command is the officially supported and safest method for releasing a persistent state lock when the original process that acquired it has crashed or is no longer active. This command specifically requires the lock ID, which is typically provided within the error message when an operation attempts to acquire an already held lock. Using `force-unlock` ensures that Terraform's backend properly acknowledges the lock's release, preventing potential state corruption that could arise from manual intervention.

Why this answer

The `terraform force-unlock` command is the intended safe method to release a stuck lock when the lock holder process is confirmed dead. The lock ID is provided in the error message. Option A is incorrect because Terraform state locks do not have a default automatic expiration; they must be explicitly released.

Option B is risky: directly deleting the lock record from DynamoDB can lead to inconsistent state if not done carefully, and is not recommended as a standard practice. Option D bypasses locking entirely with `-lock=false`, which can cause state corruption if other operations are in progress, so it is unsafe.

254
MCQhard

A developer creates a module that provisions an AWS EC2 instance and an S3 bucket. The module outputs the instance ID and bucket ARN. When using this module, the root configuration references module.my_module.instance_id and module.my_module.bucket_arn. After running terraform apply, they notice that the bucket ARN is empty. What is the most likely cause?

A.The output is defined in the module but not in the root configuration.
B.The S3 bucket creation depends on another resource that hasn't been created yet.
C.The output value in the module is defined incorrectly, e.g., referencing a non-existent attribute.
D.The IAM role used by Terraform does not have permission to read the bucket ARN.
AnswerC

When an output block within a module attempts to reference an attribute that does not exist on the specified resource, or uses an incorrect attribute path, Terraform often evaluates this expression to an empty string or a null value. This results in the module's output appearing empty when consumed by the root configuration, as the requested data simply isn't found at the specified location within the resource object. This is a common cause of unexpected empty outputs.

Why this answer

The most likely cause of an empty output value is that the output block in the module references an attribute that does not exist on the resource. For example, if the output is defined as `output "bucket_arn" { value = aws_s3_bucket.my_bucket.arn }` but the resource is actually `aws_s3_bucket.my_bucket` and the correct attribute is `arn`, a typo like `arnn` or `id` would cause Terraform to return an empty string (or an error during plan). Terraform validates attribute references at plan time, but if the attribute is missing or misspelled, the output value will be empty or cause a failure.

Exam trap

HashiCorp often tests the misconception that missing outputs in the root configuration cause empty values, but the real issue is almost always a misconfigured output block in the module itself, such as referencing a wrong attribute name.

How to eliminate wrong answers

Option A is wrong because outputs defined in the root configuration are not required to reference module outputs; the root configuration can directly use module outputs without redefining them. Option B is wrong because dependency ordering does not cause an output to be empty; if the S3 bucket depends on another resource, Terraform will wait for that resource to be created before reading the bucket's attributes, so the output would still be populated. Option D is wrong because IAM permissions affect the ability to create or describe resources, not the ability to read an attribute that is already part of the Terraform state; the bucket ARN is computed by the provider and stored in state, so no read permission is needed to output it.

255
Multi-Selecteasy

Which TWO statements about Terraform configuration files are correct? (Choose two.)

Select 2 answers
A.All .tf files in subdirectories are automatically loaded.
B.A file named terraform.tfvars is automatically processed.
C.The backend configuration must be defined in the same file as the provider configuration.
D.The -var-file flag accepts a comma-separated list of variable files.
E.Variable definitions files can have .tfvars.json extension.
AnswersB, E

Terraform automatically loads terraform.tfvars if present in the root directory.

Why this answer

Options B and E are correct. Terraform automatically processes a file named terraform.tfvars if it exists in the configuration directory, making option B correct. Variable definitions files can also have a .tfvars.json extension, as stated in option E.

Option A is incorrect because Terraform does not load .tf files from subdirectories by default; only the root directory is scanned. Option C is incorrect because the backend configuration does not have to be defined in the same file as the provider configuration; they can be in separate files. Option D is incorrect because the -var-file flag does not accept a comma-separated list; you must use multiple -var-file flags to specify multiple variable files.

256
MCQmedium

A DevOps engineer needs to generate multiple similar AWS EC2 instances from a single resource block. They want each instance to have a unique name tag based on an index. Which approach should they use?

A.Use a `locals` block to define multiple resources
B.Use `for_each` and reference `each.key` for the name tag
C.Use a `terraform_data` resource to loop
D.Use `count` and reference `count.index` for the name tag
AnswerD

The `count` meta-argument is specifically designed for creating multiple instances of a resource based on a numerical index. By setting `count` to the desired number of instances, Terraform creates that many resources, each accessible via `count.index` (a zero-based integer). This index can then be directly incorporated into resource attributes, such as a name tag, to uniquely identify each "similar" EC2 instance, perfectly fulfilling the requirement.

Why this answer

The `count` meta-argument creates multiple resources from a single resource block, and `count.index` provides a zero-based index for each instance. This index can be used directly in the name tag, such as `"instance-${count.index}"`, to generate unique names. `count` is the simplest and most appropriate mechanism when you need a fixed number of similar resources differentiated by an index.

Exam trap

The TF-003 exam often tests the distinction between `count` and `for_each` by presenting a scenario that requires index-based naming, leading candidates to incorrectly choose `for_each` because they confuse key-based iteration with index-based iteration.

How to eliminate wrong answers

Option A is wrong because a `locals` block defines computed values, not resources; it cannot create multiple EC2 instances. Option B is wrong because `for_each` iterates over a map or set of strings, using `each.key` as the key from that collection, not a numeric index; it is designed for non-sequential, key-based uniqueness, not index-based naming. Option C is wrong because `terraform_data` is a resource used to manage lifecycle dependencies or store plain values, not to create multiple instances or loop over a count.

257
MCQmedium

A team has been manually modifying cloud resources outside of Terraform. They now find that Terraform plans show changes that don't match their expectations. What core concept of Terraform's purpose does this situation violate?

A.Declarative configuration with desired state
B.Idempotency
C.Immutable infrastructure
D.Procedural scripting
AnswerA

Terraform operates on a declarative configuration model where the desired state of infrastructure is explicitly defined in HCL files. When resources are manually modified outside of Terraform, it introduces configuration drift, causing the actual state to diverge from the desired state defined in the configuration. This violation means Terraform's next `plan` or `apply` might propose unexpected changes or fail to reconcile the infrastructure to the intended state, undermining the reliability and predictability of infrastructure management.

Why this answer

Terraform's core purpose is to manage infrastructure through a declarative configuration that defines the desired state. When users manually modify cloud resources outside of Terraform, the actual state diverges from the desired state defined in the configuration. Terraform detects this drift and plans changes to reconcile the actual state back to the desired state, which may include unexpected modifications or deletions.

This violates the fundamental principle that Terraform should be the single source of truth for infrastructure state.

Exam trap

In the HashiCorp Terraform exam, this scenario tests understanding of Terraform's declarative nature. Candidates often confuse 'idempotency' with 'declarative configuration' because idempotency ensures consistent results, but the core issue here is that Terraform always reconciles the actual state to the desired state defined in configuration, which is the essence of declarative management.

How to eliminate wrong answers

Option B is wrong because idempotency refers to the property that applying the same configuration multiple times produces the same result, but the issue here is about state drift caused by out-of-band changes, not about repeated application behavior. Option C is wrong because immutable infrastructure is a pattern where resources are replaced rather than modified, but the core violation is about state management and drift detection, not about immutability. Option D is wrong because procedural scripting describes an imperative approach where steps are explicitly ordered, which is the opposite of Terraform's declarative model, but the question specifically highlights the mismatch between actual and desired state due to manual changes, not the scripting paradigm.

258
MCQmedium

You are managing a multi-environment Terraform configuration using separate workspaces for 'dev', 'staging', and 'prod'. Each workspace uses the same root module but different variable values stored in terraform.tfvars files per workspace. Your team reports that after a recent change to the root module, running `terraform plan` in the 'dev' workspace shows that it will destroy and recreate a critical RDS database instance, even though no changes were made to the database configuration. The state file for 'dev' is stored in a remote S3 backend with DynamoDB locking. You suspect the issue is related to how Terraform generates and reads configuration. What is the most likely cause?

A.The S3 backend is misconfigured, causing the 'dev' workspace to use the 'prod' state file.
B.A new variable with a default value that forces recreation of the database was added to the root module, but the 'dev' workspace's tfvars file does not override it, so Terraform uses the default which differs from the current state.
C.The root module was changed to use a different Terraform provider version that is incompatible with the existing state.
D.The DynamoDB lock is not being released after previous operations, causing state corruption.
AnswerB

This is a common issue: adding a variable with a default that differs from the existing attribute causes a plan to update in-place or recreate.

Why this answer

When a new variable with a default value is added to the root module, and the 'dev' workspace's terraform.tfvars does not override it, Terraform uses the default value. If that default differs from the value currently tracked in the state (e.g., a database engine version or instance class), Terraform interprets this as a configuration change and plans to destroy and recreate the resource to match the new default. This is a common pitfall when variables are introduced without updating all workspace-specific variable files.

Exam trap

HashiCorp often tests the misconception that state corruption or backend misconfiguration is the root cause, when the real issue is Terraform's variable default behavior and its interaction with 'ForceNew' attributes in resource schemas.

How to eliminate wrong answers

Option A is wrong because a misconfigured S3 backend would typically cause an error or use the wrong workspace entirely, but the question states the 'dev' workspace is being used and the state file is stored correctly; using the 'prod' state would produce different resource addresses, not a targeted destroy/recreate of the same database. Option C is wrong because an incompatible provider version would cause a provider initialization error or state serialization mismatch, not a clean plan showing destroy/recreate of a single resource without provider-related errors. Option D is wrong because DynamoDB lock issues would prevent Terraform from acquiring a lock or cause a locking error, not silently corrupt state to produce a false destroy/recreate plan; state corruption typically manifests as parse errors or inconsistent results, not a coherent plan.

259
MCQhard

A company uses Terraform Cloud and wants to enforce policies that prevent creating resources with public IP addresses unless explicitly approved. What Terraform Cloud feature should they use?

A.Sentinel policies
B.VCS integration
C.Workspaces
D.Run tasks
AnswerA

Sentinel is HashiCorp's policy-as-code framework, deeply integrated with Terraform Cloud to enforce governance rules. It allows organizations to define granular policies that evaluate Terraform plans and states, preventing non-compliant infrastructure changes before they are applied. Policies can enforce various rules, such as mandatory tagging, allowed AWS regions, or resource size limits, ensuring compliance and security.

Why this answer

Sentinel is HashiCorp's policy-as-code framework that integrates directly with Terraform Cloud. It allows you to define fine-grained, logic-based policies (e.g., 'deny resources with public IPs unless a specific approval tag is present') that are enforced during the plan phase before any resources are created. This is the correct feature for enforcing custom governance rules on infrastructure provisioning.

Exam trap

A common mistake in Terraform Cloud is confusing Sentinel policies with run tasks. Run tasks are for integrating external tools (like security scanners), not for enforcing custom governance rules. Sentinel is the built-in policy-as-code engine.

How to eliminate wrong answers

Option B (VCS integration) is wrong because it only connects a version control repository to Terraform Cloud for triggering runs; it does not evaluate or enforce policies on resource configurations. Option C (Workspaces) is wrong because workspaces are logical containers for managing state and variables, not a mechanism for policy enforcement or approval workflows. Option D (Run tasks) is wrong because run tasks are used to integrate third-party tools (e.g., security scanners) into the run lifecycle, not to define native policy rules like Sentinel does.

260
MCQeasy

An organization wants to ensure that running the same Terraform configuration multiple times produces the same result without unintended changes. Which IaC concept is most critical for this goal?

A.Dynamic provider credentials
B.Modularity
C.Version control
D.Idempotency
AnswerD

Idempotency guarantees repeated runs produce the same outcome.

Why this answer

Idempotency ensures that applying the same Terraform configuration multiple times results in the same desired state, with no unintended changes on subsequent runs. Terraform achieves this by comparing the current state (stored in a state file) with the desired configuration and only making changes necessary to reconcile differences. This is the core principle behind Terraform's 'plan and apply' workflow, which guarantees repeatable infrastructure provisioning.

Exam trap

HashiCorp often tests the distinction between 'version control' and 'idempotency' by presenting version control as a plausible answer, since it is a fundamental IaC practice, but the question specifically asks about producing the same result across multiple runs, which is the definition of idempotency.

How to eliminate wrong answers

Option A is wrong because dynamic provider credentials (e.g., using AWS STS AssumeRole) relate to authentication and access control, not to ensuring repeatable, unchanged results across multiple runs. Option B is wrong because modularity improves code organization and reusability but does not inherently guarantee that repeated executions produce the same outcome; a non-idempotent module can still cause drift. Option C is wrong because version control tracks changes to configuration files over time but does not enforce that applying the same configuration multiple times yields identical infrastructure state; it is a best practice for collaboration, not a mechanism for idempotent execution.

261
MCQhard

Refer to the exhibit. An engineer sees this error. Which command should they run to force-unlock?

A.terraform force-unlock my-company-terraform-state/prod/terraform.tfstate
B.terraform unlock -id=123456
C.terraform state unlock 123456
D.terraform init -force-unlock=123456
E.terraform force-unlock 123456
AnswerE

The `terraform force-unlock` command is the correct and designated method for manually releasing a Terraform state lock that has become stale or orphaned. This command requires the specific lock ID, which is typically provided in the error message when a lock prevents an operation, or can be retrieved from the backend's locking mechanism. Providing the correct lock ID ensures that only the intended lock is released, allowing subsequent Terraform operations to proceed.

Why this answer

`terraform force-unlock <LOCK_ID>` is the exact command Terraform provides to manually release a state lock when the automatic unlocking mechanism fails (e.g., after a crash or network interruption). The lock ID is a unique identifier assigned by the backend (such as DynamoDB or Consul) when the lock was acquired, and this command bypasses the normal safety checks to force the unlock.

Exam trap

The Terraform exam often tests the exact syntax of `terraform force-unlock <LOCK_ID>` versus similar-sounding commands like `terraform state unlock` or `terraform unlock`, exploiting the fact that candidates may confuse the command name or the required argument (lock ID vs. state file path).

How to eliminate wrong answers

Option A is wrong because `terraform force-unlock` does not accept a state file path as an argument; it requires the lock ID, not a file path. Option B is wrong because `terraform unlock` is not a valid Terraform command; the correct command is `force-unlock`. Option C is wrong because `terraform state unlock` is not a valid subcommand; the `state` subcommand does not have an `unlock` action.

Option D is wrong because `terraform init` does not accept a `-force-unlock` flag; that flag belongs to `terraform force-unlock`.

262
MCQhard

During a `terraform apply`, the operation fails mid-way due to a network outage, leaving some resources created. The operator wants to resume applying from where it left off without destroying the already-created resources. What should they do?

A.Run terraform apply again
B.Run terraform destroy and then apply
C.Run terraform refresh
D.Run terraform apply -auto-approve
AnswerA

Idempotent; creates missing resources.

Why this answer

Terraform uses a state file to track the resources it manages. When `terraform apply` fails mid-way, the state file is updated to reflect the resources that were successfully created. Running `terraform apply` again will cause Terraform to compare the current state with the configuration, detect that the already-created resources exist, and proceed to create only the remaining resources, effectively resuming from where it left off without destroying anything.

Exam trap

The trap here is that candidates may think a failed apply requires a full destroy or refresh, but Terraform's state-driven design allows idempotent resumption, and the exam tests understanding that `terraform apply` is the correct command to re-run after any partial failure.

How to eliminate wrong answers

Option B is wrong because `terraform destroy` would delete all resources, including those already created, which defeats the goal of resuming without destruction. Option C is wrong because `terraform refresh` only updates the state file to match real-world infrastructure; it does not create any resources or resume a failed apply. Option D is wrong because `terraform apply -auto-approve` simply skips the interactive approval prompt; it does not change the core behavior of the apply command and would still work correctly, but the key issue is that the operator must run `terraform apply` again, and the `-auto-approve` flag is irrelevant to the question's focus on resuming without destruction.

263
MCQhard

A CI/CD pipeline runs 'terraform plan' and needs to automatically approve only if no resources will be destroyed. Which approach should be used?

A.Run 'terraform apply -auto-approve' after a successful plan.
B.Run 'terraform plan -destroy' and check the exit code.
C.Run 'terraform fmt' to check for formatting issues.
D.Run 'terraform validate' to ensure no destroys are needed.
E.Run 'terraform plan -out=plan.tfplan', then 'terraform show -json plan.tfplan' and parse the output for destroy actions.
AnswerE

This is the correct and recommended approach for programmatically inspecting a Terraform plan for specific actions. First, 'terraform plan -out=plan.tfplan' saves the detailed execution plan to a binary file. Subsequently, 'terraform show -json plan.tfplan' converts this binary plan into a machine-readable JSON format. This JSON output contains a comprehensive breakdown of all proposed changes, including resource creations, updates, and crucially, destructions, which can then be parsed by a CI/CD pipeline to detect and flag any destroy actions.

Why this answer

'terraform plan -out=plan.tfplan' generates a plan file, and 'terraform show -json plan.tfplan' outputs it in JSON format, which can be parsed to detect destroy actions. If no destroy actions are present, the pipeline can proceed to apply. Option A is wrong because 'terraform apply -auto-approve' would apply any changes without checking for destroys.

Option B is wrong because 'terraform plan -destroy' always shows a destroy plan, not a way to detect destroys in a normal plan. Option C is wrong because 'terraform fmt' only formats code, not checks for destroys. Option D is wrong because 'terraform validate' only checks syntax, not planned changes.

264
MCQmedium

A developer accidentally deleted a resource from the Terraform state file using 'terraform state rm'. The resource still exists in the cloud provider. How can the developer re-import the resource without affecting other resources?

A.Re-run 'terraform apply' to recreate the resource.
B.Use 'terraform state push' with a previous state backup.
C.Run 'terraform refresh' to discover and add the resource.
D.Use 'terraform import' with the resource address and ID.
AnswerD

"terraform import" is specifically designed to bring existing infrastructure resources, which were created outside of Terraform or are no longer tracked by its state, under Terraform's management. It requires the resource's Terraform address (e.g., `aws_instance.web`) and its unique identifier from the cloud provider (e.g., `i-0abcdef1234567890`). This command adds the resource to the state file, allowing Terraform to manage it going forward.

Why this answer

`terraform import` is the designated command to bring an existing cloud resource back under Terraform management without affecting other resources. It requires the resource address (as defined in the configuration) and the provider-specific resource ID, allowing Terraform to write the current state into the state file without modifying the actual infrastructure.

Exam trap

A common misconception is that `terraform refresh` can automatically discover and add untracked resources, when in fact it only updates state for resources already in the state file.

How to eliminate wrong answers

Option A is wrong because `terraform apply` would attempt to recreate the resource from scratch, which could cause downtime or duplicate resources if the existing resource is not destroyed first. Option B is wrong because `terraform state push` is used to overwrite the entire state file with a local state file, not to selectively re-import a single resource; using a previous state backup would revert all state changes, potentially losing other intentional modifications. Option C is wrong because `terraform refresh` only updates the state file with the current attributes of resources already tracked in state; it cannot discover or add a resource that was removed from the state file.

265
MCQhard

An organization has a multi-cloud strategy using Terraform. They need to ensure that secrets such as API keys are not stored in plaintext in the configuration files. Which Terraform feature should they use to securely manage sensitive data?

A.Terraform variable definitions with environment variables
B.Terraform workspaces
C.Integration with a secrets management tool like Vault
D.Terraform state file encryption
E.Terraform's sensitive parameter in output blocks
AnswerC

Integrating with a dedicated secrets management tool like HashiCorp Vault is the most robust solution for securing sensitive data in a multi-cloud Terraform strategy. Vault provides centralized, secure storage for static secrets and can dynamically generate temporary credentials for various services, ensuring secrets are never hardcoded in configuration. This approach allows secrets to be retrieved at runtime, benefiting from strong encryption, auditing, and fine-grained access control policies.

Why this answer

Integrating Terraform with a dedicated secrets management tool like HashiCorp Vault allows sensitive data (e.g., API keys, passwords) to be stored securely and retrieved at runtime via data sources, rather than being hardcoded in plaintext in configuration files. This approach ensures secrets are never written to disk in plaintext, are encrypted in transit and at rest, and can be dynamically rotated without modifying Terraform code.

Exam trap

A common trap in Terraform certification is thinking that marking outputs as sensitive or using environment variables is sufficient for secure secret management, but those methods do not prevent secrets from being stored in plaintext in the state file or configuration files. Only integration with a secrets management tool like Vault ensures secrets are never exposed in plaintext.

How to eliminate wrong answers

Option A is wrong because environment variables can still leak sensitive values through logs, process listings, or shell history, and they do not provide encryption or access control for the secrets themselves. Option B is wrong because Terraform workspaces are used to manage multiple state files and environments, not to secure or encrypt sensitive data. Option D is wrong because state file encryption protects the state file at rest, but secrets may still be stored in plaintext in configuration files or in the state file before encryption; it does not prevent plaintext exposure in source code.

Option E is wrong because the `sensitive` parameter in output blocks only masks the value in CLI output and logs, but the secret is still stored in plaintext in the state file and configuration.

266
MCQhard

An organization uses Terraform Cloud workspaces to manage multiple environments. They notice that after promoting a configuration change from development to production workspace, the production workspace's state file contains references to resources that were only created in development. What is the most likely cause?

A.The workspaces were configured to use the same S3 backend and prefix, causing state overlap.
B.The user ran `terraform state mv` to move resource instances from development to production workspace.
C.A user manually edited the production state file to include development resources.
D.The development workspace's output values were used in production via `terraform_remote_state`.
AnswerB

The `terraform state mv` command is the standard and intended method for relocating resource instances within or between Terraform state files. When executed against a remote backend like Terraform Cloud, it directly modifies the state of the target workspace, effectively transferring the management of specific resources from one state to another, such as from a development to a production workspace.

Why this answer

The `terraform state mv` command can move resource instances from one workspace's state file to another, which explains why production state contains references to development resources. Option A (same backend/prefix) could cause state corruption but would not selectively move resources. Option C is unlikely and error-prone.

Option D would allow reading outputs but not modify production state.

267
MCQhard

You are a platform engineer at a large e-commerce company that uses Terraform Enterprise to manage thousands of infrastructure resources across multiple teams. The company has a central 'networking' workspace that provisions shared VPCs and subnets, and several application workspaces that consume these networking resources via remote state data sources. Recently, the networking team changed the CIDR block of a shared subnet from '10.0.1.0/24' to '10.0.2.0/24' and applied the change successfully. However, the application teams are now reporting that their Terraform runs are failing with errors indicating that the subnet ID they reference does not exist. The application workspaces use the following configuration to consume the subnet: ```hcl data "terraform_remote_state" "networking" { backend = "remote" config = { organization = "mycompany" workspaces = { name = "networking" } } } resource "aws_instance" "app" { subnet_id = data.terraform_remote_state.networking.outputs.subnet_id ... } ``` The application workspaces have not been modified recently. The networking workspace output 'subnet_id' now contains the ID of the updated subnet. What is the most likely cause of the failures?

A.The application workspaces do not have permission to read the networking workspace's state.
B.The networking workspace output variable 'subnet_id' was removed or renamed.
C.The application workspaces are using a cached version of the remote state outputs and need to run 'terraform plan' to refresh.
D.The application workspaces need to update the remote state data source to reference the new subnet ID.
AnswerC

When Terraform references a remote state data source, it fetches the state data at the beginning of a `terraform plan` or `terraform apply` run and caches it for the duration of that specific operation. If the upstream networking workspace's state changes *after* the application workspace's last `plan` or `apply`, the application workspace will continue to use its locally cached, now stale, version of the `subnet_id`. A new `terraform plan` execution is required to re-fetch and update this cached remote state data.

Why this answer

Terraform caches remote state data during the planning phase, and the `terraform_remote_state` data source only fetches the latest state when `terraform plan` or `terraform apply` is executed. Since the application workspaces have not been modified or re-planned, they are using a stale cached version of the networking workspace's outputs, which still contains the old subnet ID. Running `terraform plan` forces a refresh of the remote state data, retrieving the updated `subnet_id` and resolving the error.

Exam trap

The trap here is that candidates may assume the remote state data source always reads the latest state on every run, when in fact Terraform caches the data from the last plan and only refreshes it during a new plan or apply operation.

How to eliminate wrong answers

Option A is wrong because if the application workspaces lacked permission to read the networking workspace's state, the error would be an authorization failure (e.g., 403 Forbidden), not a 'subnet ID does not exist' error. Option B is wrong because the scenario explicitly states that the networking workspace output 'subnet_id' now contains the ID of the updated subnet, meaning the output was not removed or renamed. Option D is wrong because the remote state data source configuration does not need to be updated; it already references the correct workspace and output name, and the issue is simply that the cached data is stale.

268
MCQmedium

A company has a Terraform configuration that creates many AWS resources. They want to check the estimated cost of the plan before applying. Which approach should they use?

A.Use 'terraform plan -cost' command.
B.Manually use 'terraform show -json' and parse pricing.
C.Enable cost estimation in Terraform Cloud.
D.Use 'terraform validate' with a custom script.
AnswerC

Terraform Cloud offers native cost estimation capabilities, particularly for AWS resources, by integrating directly into the planning workflow. When a "terraform plan" is executed in Terraform Cloud, it analyzes the proposed resource changes against current cloud provider pricing data. This feature provides an estimated monthly cost impact directly within the plan output, offering a streamlined and automated solution for financial oversight.

Why this answer

Terraform Cloud provides a built-in cost estimation feature that analyzes the resources in a plan against current cloud provider pricing APIs to estimate monthly costs. This is the recommended approach because it is integrated directly into the Terraform workflow and does not require manual parsing or external scripts. Option C is correct because it leverages Terraform Cloud's native capability to estimate costs before applying.

Exam trap

Terraform often tests the misconception that 'terraform plan' has a built-in cost flag, but no such flag exists in the Terraform CLI; cost estimation is exclusively a Terraform Cloud feature.

How to eliminate wrong answers

Option A is wrong because 'terraform plan -cost' is not a valid Terraform CLI command; the Terraform CLI does not have a built-in cost estimation flag. Option B is wrong because while 'terraform show -json' outputs the plan in JSON format, manually parsing it and integrating with pricing APIs is error-prone, unsupported, and not a standard or recommended approach. Option D is wrong because 'terraform validate' only checks configuration syntax and internal consistency, not cost estimation, and a custom script would not be integrated with Terraform's workflow or pricing data.

269
MCQeasy

A user wants to use a remote state backend for the first time. After adding the backend configuration, which command must they run to migrate the state from local to remote?

A.`terraform plan`
B.`terraform init`
C.`terraform apply`
D.`terraform state push`
AnswerB

The `terraform init` command is essential for preparing a working directory for Terraform operations, which includes configuring the backend. When a backend configuration is present for the first time, `init` detects it, initializes the connection, and crucially, prompts the user to migrate any existing local state file to the newly configured remote backend. This makes it the correct and primary command for setting up remote state.

Why this answer

When you add a remote backend configuration to your Terraform code, `terraform init` is the required command to initialize the backend and migrate the existing local state file to the remote backend. During initialization, Terraform detects the backend change, prompts for confirmation, and automatically copies the state from the local `terraform.tfstate` to the configured remote store (e.g., S3, Azure Storage, or Terraform Cloud). Without running `init`, the remote backend is not configured and local state remains unchanged.

Exam trap

A common misconception is that `terraform apply` or `terraform state push` can handle backend migration, but only `terraform init` performs the full initialization and state migration workflow.

How to eliminate wrong answers

Option A is wrong because `terraform plan` only creates an execution plan by comparing the current state with the configuration; it does not initialize backends or migrate state. Option C is wrong because `terraform apply` executes changes to infrastructure but relies on an already-initialized backend; it cannot set up or migrate state to a remote backend. Option D is wrong because `terraform state push` is used to manually overwrite the remote state with a local state file, but it is not the correct or safe command for initial migration; it bypasses the proper initialization workflow and can cause state conflicts.

270
MCQeasy

A DevOps engineer is managing a multi-cloud infrastructure using Terraform. The team relies on a module sourced from the Terraform Registry to deploy a standard web application. This module defines an input variable called 'instance_count' with a default value of 2. For the production environment, the engineer wants to deploy 3 instances. They create a root module configuration that references the module. In the root module's main.tf, they write a block that sets instance_count = 3. However, when they run terraform plan, the output indicates that the module will still use instance_count = 2. The engineer double-checks the configuration: the root module's main.tf is syntactically correct, the module source points to the correct registry module and version, and they have run terraform init and terraform validate without errors. What is the most likely reason the variable override is not taking effect?

A.The module version specified does not support variable overrides; the engineer must use a different module.
B.The variable 'instance_count' is not declared as an input variable in the child module's variables.tf.
C.The engineer forgot to run terraform init after modifying the root module's configuration.
D.The root module defines instance_count as a local value rather than passing it as an argument to the module block.
AnswerD

To pass a value to an input variable of a child module, it must be explicitly defined as an argument directly within the `module` block declaration in the calling configuration. A local value, defined using the `locals` block in the root module, is an internal construct for simplifying expressions within that *same* root module. It does not automatically get passed down or override variables within a child module; it must be referenced and then passed as a module argument.

Why this answer

The scenario describes the engineer setting instance_count = 3 in the root module, but if it is defined as a local value (e.g., locals { instance_count = 3 }) rather than passed as an argument to the module block (e.g., module "web" { source = "...", instance_count = 3 }), the module will not receive the override and will use its default value. Option A is incorrect: module version does not prevent variable overrides; the module source is correct. Option B is incorrect: the variable is declared in the child module (it has a default).

Option C is incorrect: terraform init is not required for configuration changes that don't affect providers or modules; terraform validate passed, indicating no syntax error.

271
MCQhard

An organization uses Terraform with a remote backend in Azure. After a network outage, a developer attempts to run `terraform apply` and receives the error: "Error: Failed to get existing workspaces: blob (key) not found". What is the most likely cause?

A.The Terraform backend configuration has incorrect access key
B.The Azure storage account was deleted
C.The state file for the current workspace was deleted or corrupted
D.The workspace was not created via `terraform workspace new`
AnswerC

When Terraform reports a "blob not found" error in an Azure backend, it specifically means that the expected state file object, identified by its unique blob path (which includes the workspace name), does not exist within the configured storage container. This directly indicates that the state file for the currently selected Terraform workspace has either been inadvertently deleted from the Azure Blob Storage or has become corrupted in a way that makes it unretrievable by its expected key. Terraform successfully connected to the storage account and container but failed to locate the specific state object.

Why this answer

The error 'blob (key) not found' indicates that Terraform cannot locate the state file for the current workspace in the Azure storage container. After a network outage, the state file may have been deleted or corrupted, preventing Terraform from reading the existing state. This error is specific to the missing blob key, not to authentication or storage account availability.

Exam trap

HashiCorp often tests the distinction between authentication/authorization errors and resource-not-found errors; the trap here is that candidates may confuse a missing state file with a misconfigured backend or deleted storage account, but the specific 'blob (key) not found' message points directly to the state file blob being absent.

How to eliminate wrong answers

Option A is wrong because an incorrect access key would produce an authentication error (e.g., 'Failed to obtain existing workspaces: storage: service returned error: StatusCode=403'), not a 'blob not found' error. Option B is wrong because if the storage account were deleted, the error would indicate that the container or account does not exist (e.g., 'The specified storage account was not found'), not that a specific blob key is missing. Option D is wrong because workspaces are created via `terraform workspace new` only when using multiple workspaces; the default workspace exists without explicit creation, and the error is about the state file itself, not workspace existence.

272
MCQeasy

Which Terraform command is used to validate the syntax of configuration files without accessing any cloud provider?

A.terraform validate
B.terraform fmt
C.terraform plan
D.terraform init
AnswerA

The `terraform validate` command performs a static analysis of the configuration files in the current working directory. It checks for syntactical correctness of the HashiCorp Configuration Language (HCL), verifies proper variable usage, and ensures internal consistency of resource and data source references. This crucial step identifies configuration errors early, without requiring any network calls to cloud providers or interacting with remote state, making it the ideal command for purely syntax validation.

Why this answer

`terraform validate` checks syntax and internal consistency of configuration files. `init` initializes backends and providers, `plan` accesses remote state, `fmt` formats code.

273
Multi-Selectmedium

Which three of the following are core characteristics of Terraform's execution plan? (Choose three.)

Select 3 answers
.It is generated by the `terraform plan` command.
.It shows what actions Terraform will take to reach the desired state.
.It can be saved to a file and later applied using `terraform apply` with that file.
.It automatically applies changes to infrastructure without user confirmation.
.It only shows changes for resources that were manually modified outside Terraform.
.It is a read-only view of the current state file with no indication of future actions.

Why this answer

The `terraform plan` command generates an execution plan that shows exactly what actions Terraform will take to reach the desired state defined in the configuration. This plan can be saved to a file and later applied using `terraform apply` with that file, ensuring the exact same changes are executed. These three characteristics are fundamental to Terraform's workflow, providing a safe and predictable way to manage infrastructure changes.

Exam trap

HashiCorp often tests the misconception that the execution plan is an automatic apply mechanism or that it only detects drift from manual changes, when in fact it is a deliberate, user-initiated preview that compares the entire configuration against the current state.

274
MCQhard

A Terraform configuration uses `count` to create multiple EC2 instances. After adding a new variable for instance type, the user runs `terraform plan` and sees that all instances are marked for recreation. What is the most likely cause?

A.The `count` index changed, causing all resources to be re-indexed
B.The user forgot to run `terraform refresh` after changing the variable
C.The state file is corrupt and needs to be refreshed
D.The variable change triggers a new value for each resource, causing Terraform to see differences
E.The provider version is incompatible with the new variable type
AnswerD

When an input variable's value changes, and that variable is referenced within the configuration of resources created using `count`, Terraform re-evaluates the entire configuration. For each resource instance managed by `count`, the new variable value is used to compute its attributes. If these newly computed attributes for an existing resource instance differ from what is currently recorded in the state file, Terraform identifies these as 'differences' and proposes actions (e.g., update, replace, or destroy/create) in the execution plan to reconcile the desired state with the actual state.

Why this answer

When you change a variable that is referenced within a resource's configuration (such as `instance_type`), Terraform sees a diff between the current state and the new configuration for every resource created by `count`. Since `count` resources are identified by their index in the state, and the new variable value changes the desired configuration for each instance, Terraform plans to recreate all of them to apply the new instance type.

Exam trap

The trap here is that candidates often confuse `count` re-indexing (which happens when the count value itself changes) with the effect of changing a variable that is used inside the resource block, leading them to incorrectly select Option A.

How to eliminate wrong answers

Option A is wrong because changing the `count` index (i.e., the number of resources) would cause re-indexing, but the question states that the variable for instance type was added, not that the count value changed. Option B is wrong because `terraform refresh` updates the state to match real-world infrastructure but does not prevent Terraform from detecting configuration changes; the plan would still show recreation if the variable changed. Option C is wrong because a corrupt state file would typically cause errors or inconsistencies, not a clean plan showing all resources marked for recreation.

Option E is wrong because provider version incompatibility would manifest as errors during initialization or plan, not as a planned recreation of all instances due to a variable change.

275
MCQeasy

A developer wants to see the list of resources currently managed by Terraform in the state file. Which command should they use?

A.terraform graph
B.terraform output
C.terraform show
D.terraform state list
AnswerD

The `terraform state list` command is precisely designed to enumerate all resources and data sources currently tracked within the Terraform state file. It provides a clean, hierarchical list of resource addresses (e.g., `aws_instance.web`, `aws_s3_bucket.my_bucket`), making it the most direct and efficient way to see exactly which infrastructure components Terraform is managing. This command directly addresses the developer's need for a simple, concise list of managed resources without displaying their full configurations.

Why this answer

`terraform state list` is the dedicated command to list all resources tracked in the Terraform state file. It reads the state directly and outputs the resource addresses (e.g., `aws_instance.web`), giving the developer a clear view of what Terraform currently manages.

Exam trap

The trap here is that candidates confuse `terraform show` (which dumps the full state) with `terraform state list` (which provides a concise, filtered list of resource addresses), leading them to pick C instead of D.

How to eliminate wrong answers

Option A is wrong because `terraform graph` generates a visual dependency graph of resources in DOT format, not a list of state-managed resources. Option B is wrong because `terraform output` displays only the output values defined in the configuration, not the full list of resources in the state. Option C is wrong because `terraform show` displays the state or plan file in a human-readable format, but it shows the entire state content (including attributes and metadata), not a simple list of resource addresses.

276
MCQhard

You are a platform engineer at a fintech company. Your team manages a multi-region application on AWS using Terraform. The infrastructure includes VPCs, subnets, EC2 instances, and an Application Load Balancer (ALB). The configuration uses modules from the Terraform Registry and remote state in S3 with DynamoDB locking. Recently, after a colleague ran `terraform apply` in the us-east-1 region, the application experienced downtime because the ALB's target group was accidentally updated to point to instances in us-west-2 instead of us-east-1. The root cause was that the Terraform configuration for the ALB used a variable `target_region` which was hardcoded to us-west-2 in a `terraform.tfvars` file that was not intended for that workspace. Your team wants to prevent such misconfigurations in the future. Which course of action would most effectively reduce the risk of using incorrect variable values across workspaces?

A.Implement a CI/CD pipeline that runs `terraform plan` for every workspace and requires manual approval before apply
B.Use the same S3 backend for all regions but with different state file keys, and enforce naming conventions
C.Store all variables in a single `terraform.tfvars` file and use conditionals with `terraform.workspace` to select values
D.Create separate Terraform configurations for each region, each with its own backend configuration and variable files, and use directory structure to enforce separation
AnswerD

Creating separate Terraform configurations for each region, each within its own dedicated directory, provides the strongest form of isolation. This approach ensures that each region has its own backend configuration, state file, and explicitly defined variable files (e.g., `region.tfvars`). This physical separation makes it virtually impossible to accidentally apply variables or configurations meant for one region to another, as the `terraform` command must be executed from the correct, isolated directory.

Why this answer

Creating separate Terraform configurations for each region enforces strict isolation at the directory and backend level, preventing accidental cross-region variable injection. This approach ensures that each region's configuration has its own dedicated variable files and state, eliminating the risk of a `terraform.tfvars` file from one workspace affecting another. It aligns with infrastructure-as-code best practices for multi-region deployments where environment boundaries must be explicit.

Exam trap

The trap here is that candidates often assume workspaces provide sufficient isolation for multi-region deployments, but workspaces share the same variable files and backend configuration, making them unsuitable for preventing cross-region variable misconfigurations.

How to eliminate wrong answers

Option A is wrong because a CI/CD pipeline with manual approval only adds a process gate but does not prevent the root cause—the hardcoded variable value in the tfvars file—and can still allow the same misconfiguration to pass through if the plan output is not carefully reviewed. Option B is wrong because using the same S3 backend with different state file keys and naming conventions does not prevent a developer from accidentally applying a configuration that references the wrong region variable; it only organizes state files, not variable values. Option C is wrong because storing all variables in a single tfvars file with conditionals based on `terraform.workspace` still allows a single file to contain the wrong default or a typo, and it does not enforce separation of concerns; a misconfigured workspace name could still select the wrong value.

277
MCQeasy

Which Terraform command is used to check the syntax and internal consistency of configuration files?

A.terraform validate
B.terraform fmt
C.terraform plan
D.terraform graph
AnswerA

The `terraform validate` command performs a static analysis of the configuration files in the current directory, checking for syntactical correctness and internal consistency. It ensures that all required arguments are provided, variable types match, and provider configurations are properly structured, all without interacting with any remote state or cloud providers. This early detection mechanism is crucial for identifying configuration errors before attempting a `plan` or `apply`, making it the definitive tool for syntax and consistency checks.

Why this answer

The `terraform validate` command checks the syntax and internal consistency of Terraform configuration files, ensuring that the code is syntactically valid and that references between resources, data sources, and variables are correct. It does not access remote state or providers, making it a fast, offline validation step. This is the correct command for verifying configuration correctness before applying changes.

Exam trap

HashiCorp often tests the distinction between `terraform validate` (syntax and internal consistency) and `terraform plan` (operational correctness against real infrastructure), leading candidates to mistakenly choose `plan` when the question specifically asks about configuration file syntax and consistency.

How to eliminate wrong answers

Option B is wrong because `terraform fmt` is used to rewrite configuration files into a canonical format and style, not to check syntax or internal consistency; it focuses on formatting, not validation. Option C is wrong because `terraform plan` creates an execution plan by comparing the current state with the desired configuration, which involves remote state and provider interactions, not just syntax or internal consistency checking. Option D is wrong because `terraform graph` outputs a visual dependency graph of resources in DOT format, used for understanding resource relationships, not for validating syntax or internal consistency.

278
MCQmedium

A DevOps engineer needs to integrate Terraform with a CI/CD pipeline. What is a common practice?

A.Run terraform plan in a pull request
B.Avoid using variables
C.Use -auto-approve always
D.Store state in a local file
AnswerA

Running `terraform plan` within a pull request (PR) is a best practice for CI/CD integration, as it provides a transparent preview of the infrastructure changes before they are applied. This allows team members to review the exact resources that will be created, updated, or destroyed, facilitating early detection of unintended modifications and ensuring adherence to infrastructure as code (IaC) principles prior to any actual state modification.

Why this answer

Running `terraform plan` in a pull request is a common practice because it allows the team to review the proposed infrastructure changes before they are applied. This integrates Terraform's safety mechanism into the CI/CD pipeline, ensuring that any destructive or unexpected modifications are caught during code review, not during deployment. It aligns with the principle of infrastructure as code (IaC) where changes are validated and approved through the same workflow as application code.

Exam trap

A common trap is to assume that `-auto-approve` is safe for automation, but it bypasses the human review step and can lead to unintended changes. The best practice is to use `terraform plan` in pull requests to review changes before applying.

How to eliminate wrong answers

Option B is wrong because avoiding variables defeats Terraform's purpose of making configurations dynamic, reusable, and environment-agnostic; variables are essential for parameterizing infrastructure across dev, staging, and production. Option C is wrong because using `-auto-approve` always bypasses the manual confirmation step, which can lead to unintended destruction of resources or misconfigurations; it should only be used in non-production pipelines with strict safeguards. Option D is wrong because storing state in a local file prevents collaboration and state locking, making it impossible for a team to safely run Terraform concurrently; remote state backends (e.g., S3 with DynamoDB locking) are required for CI/CD pipelines.

279
MCQmedium

Based on the exhibit, what will happen to the existing Elastic IP (aws_eip.web_eip) when this plan is applied?

A.It will remain unchanged
B.It will be updated in-place
C.It will be created
D.It will be destroyed
AnswerD

The '-' symbol in a Terraform plan output unambiguously signifies that the associated resource will be destroyed or removed from the managed infrastructure. This action typically occurs when a resource is removed from the Terraform configuration, or when a change to its attributes necessitates its replacement (destroy and then create). Consequently, the existing 'elastic' resource will be destroyed as indicated by this symbol.

Why this answer

The Terraform configuration shows that the `aws_eip.web_eip` resource is no longer defined in the configuration after the plan is applied. Terraform will detect that the resource exists in the state but is absent from the configuration, and by default, it will destroy the Elastic IP to reconcile the state with the configuration. This is standard Terraform behavior for resources removed from `.tf` files.

Exam trap

HashiCorp often tests the misconception that removing a resource from configuration leaves it unchanged in the cloud, but Terraform's default behavior is to destroy any resource not present in the configuration, unless lifecycle rules or `removed` blocks are used.

How to eliminate wrong answers

Option A is wrong because Terraform does not leave orphaned resources; if a resource is removed from the configuration, it will be destroyed unless explicitly protected with `prevent_destroy` or `lifecycle` settings. Option B is wrong because in-place updates occur only when the resource still exists in the configuration but has attribute changes; here the resource is entirely absent, so no update is possible. Option C is wrong because the resource already exists in the state (as indicated by the exhibit showing an existing Elastic IP), so Terraform will not create a new one; it will destroy the existing one.

280
Multi-Selectmedium

Which TWO of the following are best practices when writing Terraform configuration for a team? (Select TWO.)

Select 2 answers
A.Always use the `latest` version for providers.
B.Pin provider versions using `required_providers`.
C.Hardcode all values in the configuration for simplicity.
D.Use a remote backend with state locking.
E.Store the entire infrastructure in a single configuration file.
AnswersB, D

Pinning specific provider versions within the `terraform` block's `required_providers` configuration is a crucial best practice for ensuring consistent and reproducible infrastructure deployments. This explicit version constraint guarantees that Terraform always uses a known, tested version of the provider, preventing unexpected behavior or breaking changes that might be introduced in newer, untested releases. It fosters reliability, predictability, and stability across different environments and among team members, making your infrastructure code robust and dependable.

Why this answer

Options B and D are correct. Pinning provider versions using `required_providers` ensures reproducibility across team members. Using a remote backend with state locking prevents state corruption and conflicts.

Option A is wrong because using `latest` versions can introduce breaking changes unexpectedly. Option C is wrong because hardcoding values (especially secrets) is insecure and inflexible. Option E is wrong because a single monolithic configuration file is harder to maintain and collaborate on.

281
MCQhard

A team is using Terraform to manage multiple environments (dev, staging, prod) with the same configuration but different variable values. They want to avoid duplicating configuration files. Which Terraform feature is best suited for this?

A.Terraform modules with separate directories for each environment
B.Terraform data sources to fetch environment-specific variables
C.Using multiple Terraform configuration files in a single directory
D.Terraform workspaces
AnswerD

Terraform workspaces provide a robust mechanism for managing multiple distinct infrastructure environments using a single, consistent Terraform configuration. Each workspace maintains its own isolated state file, allowing for independent deployments and modifications without affecting other environments. This approach significantly reduces configuration duplication, simplifies environment management, and ensures consistency across development, staging, and production deployments.

Why this answer

Terraform workspaces allow you to manage multiple environments (e.g., dev, staging, prod) using the same root configuration and variable definitions, but with separate state files. This avoids duplicating configuration files while enabling environment-specific variable values via `terraform.workspace` interpolation or separate `.tfvars` files per workspace. Option D is correct because workspaces are the native Terraform feature designed for this exact use case.

Exam trap

HashiCorp often tests the misconception that Terraform modules (Option A) are the primary tool for environment separation, but modules are for code reuse, not state isolation—workspaces handle state separation without duplicating configuration.

How to eliminate wrong answers

Option A is wrong because using separate directories for each environment with modules still duplicates the root configuration and state files, which is exactly what the team wants to avoid. Option B is wrong because data sources are used to fetch or compute data from providers (e.g., AWS, Azure) at plan/apply time, not to manage environment-specific variable values or state separation. Option C is wrong because placing multiple configuration files in a single directory does not inherently separate state or variable values per environment; it would still require manual management and risks state corruption.

282
MCQhard

A Terraform configuration uses a module from the public registry. After a provider update, the module's resources fail to create. What is the most probable cause?

A.The provider binary is corrupted
B.The state file is corrupted
C.The module is incompatible with the new provider version
D.The backend configuration is incorrect
AnswerC

When a Terraform configuration uses a module that was developed against an older provider version, upgrading the provider can introduce breaking changes. The module's internal resources might rely on arguments, attributes, or behaviors that have been deprecated, removed, or altered in the newer provider version. This incompatibility would specifically manifest as errors during resource creation or update within that module, as the provider no longer understands or supports the module's requested configuration.

Why this answer

C is correct because modules from the public registry often declare a `required_providers` block with version constraints. When the provider is updated outside those constraints (e.g., from v3.x to v4.x), the module may rely on deprecated attributes or changed resource schemas, causing resource creation to fail. Terraform will not automatically adjust module code to match provider API changes.

Exam trap

HashiCorp often tests the misconception that provider updates are always backward-compatible, leading candidates to incorrectly suspect state corruption or backend misconfiguration instead of module-provider version incompatibility.

How to eliminate wrong answers

Option A is wrong because a corrupted provider binary would typically cause a checksum error or crash during `terraform init`, not a failure during resource creation after a provider update. Option B is wrong because a corrupted state file would manifest as state read errors or inconsistency warnings during `terraform plan` or `apply`, not as a creation failure tied specifically to a provider version change. Option D is wrong because an incorrect backend configuration would prevent Terraform from loading or saving state entirely, often with an explicit error about backend initialization or authentication, not a resource creation failure after a successful provider update.

283
MCQeasy

What is the primary purpose of 'terraform init'?

A.To format the Terraform configuration files.
B.To apply changes to the infrastructure.
C.To preview infrastructure changes before applying them.
D.To initialize the working directory, download providers, and set up the backend.
AnswerD

This option correctly describes the primary purpose of `terraform init`. It performs essential bootstrapping tasks, including discovering and downloading the necessary provider plugins specified in the configuration, which enable Terraform to interact with various cloud services. Furthermore, `terraform init` configures the backend, determining where Terraform stores its state file, which is crucial for tracking infrastructure changes and enabling collaboration. These steps collectively prepare the local working directory for subsequent Terraform operations like `plan` and `apply`.

Why this answer

The 'terraform init' command is the first step in the core Terraform workflow. Its primary purpose is to initialize the working directory containing Terraform configuration files, download and install the required provider plugins (e.g., AWS, Azure, GCP), and configure the backend (e.g., local, S3, Terraform Cloud) for state storage. Without running 'terraform init', subsequent commands like 'terraform plan' or 'terraform apply' will fail because the providers and backend are not set up.

Exam trap

HashiCorp often tests the distinction between the initialization phase and the planning/execution phases, so the trap here is that candidates confuse 'terraform init' with 'terraform plan' or 'terraform apply' because they all appear early in the workflow, but only 'init' handles provider and backend setup.

How to eliminate wrong answers

Option A is wrong because 'terraform fmt' is the command used to format Terraform configuration files, not 'terraform init'. Option B is wrong because 'terraform apply' is the command that applies changes to the infrastructure, not 'terraform init'. Option C is wrong because 'terraform plan' is the command used to preview infrastructure changes before applying them, not 'terraform init'.

284
MCQhard

Refer to the exhibit. After importing an AWS instance, the state file shows the resource. However, the configuration file (main.tf) does not yet contain the resource definition. What will happen when 'terraform plan' is run?

A.It will show a plan to destroy the resource because it exists in state but not in configuration.
B.It will show a plan to create the resource because the configuration is missing.
C.It will error because the configuration and state are out of sync.
D.It will show no changes because the resource is already in state.
AnswerA

When a resource is present in the Terraform state file but its corresponding definition is absent from the configuration files, Terraform's `plan` command identifies this discrepancy. The configuration explicitly defines the *desired* state of the infrastructure. If a resource exists in the actual infrastructure (and thus in state) but is not desired per the configuration, Terraform will propose to destroy it to align the real world with the declared configuration.

Why this answer

Terraform plan compares the state to the configuration. Since the resource exists in state but not in configuration, Terraform will plan to destroy the resource because it is no longer managed (configuration is the source of truth for what should exist).

285
Multi-Selectmedium

Which TWO of the following are valid ways to use Terraform outside the core workflow (i.e., in automation or CI/CD pipelines)?

Select 2 answers
A.Using the Terraform CLI in a CI/CD pipeline with -auto-approve after a successful plan.
B.Using 'terraform state mv' to reorganize state files.
C.Using 'terraform init -from-module' to force module re-download.
D.Using the Terraform Cloud API to trigger runs and check results.
E.Using 'terraform graph' to generate visual output.
AnswersA, D

Automating Terraform deployments in a CI/CD pipeline is a standard practice for achieving continuous delivery of infrastructure. After a `terraform plan` confirms the intended infrastructure changes, `terraform apply -auto-approve` can be safely executed to provision or modify resources without requiring manual confirmation. This enables fully automated, hands-off deployments, crucial for maintaining infrastructure as code principles and accelerating release cycles.

Why this answer

The Terraform CLI's `-auto-approve` flag is designed for non-interactive environments like CI/CD pipelines, allowing automated execution of `terraform apply` after a successful plan without manual confirmation. This bypasses the interactive approval step, making it suitable for automation where human input is not possible.

Exam trap

HashiCorp often tests the distinction between commands that are part of the core workflow (plan, apply, destroy) versus auxiliary commands (state manipulation, graph generation, module initialization) that are not directly used for automated execution in CI/CD pipelines.

286
MCQeasy

A developer runs `terraform plan` and it fails with a provider plugin error. Which command should they run first to resolve the issue?

A.terraform validate
B.terraform apply
C.terraform fmt
D.terraform init
AnswerD

terraform init is the foundational command that prepares a working directory for all subsequent Terraform operations. It performs several crucial setup steps, including discovering and downloading the necessary provider plugins specified in the configuration, initializing the chosen backend for state storage, and setting up module sources. A "provider not found" error during `terraform plan` indicates that the required provider binaries were not downloaded or properly configured, which `terraform init` specifically addresses by fetching them.

Why this answer

The `terraform init` command is the correct first step because it initializes the working directory, downloads the required provider plugins, and sets up the backend configuration. A provider plugin error typically indicates that the provider plugins are missing, outdated, or not properly installed, and `terraform init` resolves this by fetching the correct versions from the Terraform registry.

Exam trap

HashiCorp often tests the misconception that `terraform validate` can fix runtime errors, but candidates must remember that `validate` only checks syntax and schema, not the availability of external dependencies like provider plugins.

How to eliminate wrong answers

Option A is wrong because `terraform validate` checks the syntax and internal consistency of the configuration files but does not download or install provider plugins, so it cannot fix a missing or corrupted provider. Option B is wrong because `terraform apply` attempts to execute the plan and apply changes, but it will fail if the provider plugins are not available, and it is not designed to resolve plugin installation issues. Option C is wrong because `terraform fmt` only reformats the configuration files for consistent style and has no effect on provider plugin availability or installation.

287
MCQhard

A company uses Terraform workspaces to manage environments. They have a monorepo with separate configurations for each environment. They want to introduce a new team that will manage only the staging environment. The new team will run terraform commands only on the staging workspace. They are using a single S3 backend for all workspaces. The team is concerned about accidentally applying changes to other workspaces. What is the best way to restrict the team's access?

A.Create a separate S3 bucket for staging and configure a different backend.
B.Use Terraform Cloud with team-based permissions.
C.Use terraform workspace select staging in the CI/CD pipeline and only allow that.
D.Use IAM policies to restrict access to the state files of other workspaces.
AnswerB

Terraform Cloud provides robust Role-Based Access Control (RBAC) capabilities, enabling granular permissions to be set at the workspace level. This allows administrators to define specific teams or users who can interact with, modify, or even view particular workspaces, such as a "staging" workspace. By enforcing these permissions, Terraform Cloud effectively prevents team members from accidentally or intentionally targeting production or other sensitive environments, as their access would be explicitly denied by the platform.

Why this answer

Terraform Cloud provides native workspace-level permissions, allowing you to grant the new team access only to the staging workspace while preventing them from applying changes to other workspaces. This is the most secure and manageable approach, as it leverages Terraform Cloud's RBAC (Role-Based Access Control) to enforce separation of duties without modifying the backend configuration or relying on error-prone manual processes.

Exam trap

The trap here is that candidates often confuse IAM-based state file access control with workspace-level command restrictions, not realizing that Terraform commands are executed client-side and IAM cannot prevent a user from running `terraform apply` on a different workspace if they have the state file path and credentials.

How to eliminate wrong answers

Option A is wrong because creating a separate S3 bucket for staging would require changing the backend configuration for the staging environment, which breaks the single-backend design and adds operational complexity; it also does not prevent the team from accidentally using the wrong backend configuration. Option C is wrong because relying on `terraform workspace select staging` in the CI/CD pipeline is a procedural control that can be bypassed if the team runs commands locally or if the pipeline is misconfigured; it does not enforce access restrictions at the infrastructure level. Option D is wrong because IAM policies can restrict access to S3 objects (state files) but cannot prevent the team from running `terraform apply` against other workspaces if they have access to the state file; Terraform commands are executed locally or in CI/CD, and IAM does not control which workspace is selected.

288
MCQeasy

Based on the error, what is the most likely reason the 'acl' argument is not expected?

A.The module version currently installed does not have an 'acl' variable.
B.The argument name is misspelled; it should be 'acl_control'.
C.The module requires the 'acl' to be set inside a separate block.
D.The 'bucket' argument is missing; 'acl' must follow it.
AnswerA

The error message "not expected here" for an argument within a module block directly indicates that the module's defined interface, specifically its `variables.tf` file, does not declare an input variable named 'acl'. This situation commonly arises when a module has been updated, and the 'acl' variable was either removed, renamed, or never existed in the specific version of the module currently being used. Terraform strictly validates all provided arguments against the module's explicit variable definitions.

Why this answer

The error indicates that the 'acl' argument is not recognized by the Terraform module. This typically occurs when the installed module version does not expose an 'acl' variable in its schema. Terraform validates arguments against the module's declared variables; if 'acl' is absent from the module's variables.tf, Terraform will reject it as an unexpected argument.

Exam trap

This question tests the distinction between 'unexpected argument' errors (caused by undeclared variables in the module) and 'missing required argument' errors (caused by omitting a declared variable without a default), leading candidates to confuse the two and select an option that addresses a missing argument rather than an unrecognized one.

How to eliminate wrong answers

Option B is wrong because there is no standard 'acl_control' argument in Terraform's AWS S3 bucket module; the correct argument for access control lists is 'acl', not a misspelling. Option C is wrong because the 'acl' argument is a top-level argument in the 'aws_s3_bucket' resource, not something that must be nested inside a separate block; Terraform does not require 'acl' to be set inside a sub-block. Option D is wrong because Terraform arguments are order-independent; the 'bucket' argument does not need to precede 'acl', and the absence of 'bucket' would cause a different error (e.g., missing required argument), not an unexpected argument error.

289
MCQhard

Refer to the exhibit. A developer updates the network state and runs terraform apply. The aws_instance.web is not recreated. Which statement explains this behavior?

A.The instance resource does not reference the remote state data source, so changes to the remote state do not trigger recreation.
B.Terraform automatically locks the remote state to prevent changes during apply.
C.The security group resource depends on the remote state, and it was updated, but the instance was not affected.
D.The remote state data source is cached and only refreshes every hour.
AnswerA

The instance resource's configuration arguments did not change as a direct result of the remote state update because it does not explicitly reference any outputs from the `terraform_remote_state` data source. Terraform's core principle for resource recreation is based on detecting a diff in the resource's *own* defined arguments or its direct dependencies. Since the instance resource's definition remained stable and independent of the remote state, it was not marked for recreation, even if other resources that *did* depend on the remote state were updated.

Why this answer

The data source data.terraform_remote_state.network is read during planning and is not stored in state. If the remote state changes, Terraform will see the new vpc_id and may update the security group, but the instance resource does not depend on the remote state, so it is not affected.

290
MCQmedium

A team is using a remote backend in Terraform Cloud. After a failed apply, the state file is locked. The team lead wants to unlock the state immediately. What should be done?

A.Delete the state file from the backend and reinitialize
B.Run terraform force-unlock with the lock ID
C.Manually edit the state file to remove the lock
D.Run terraform unlock
AnswerB

The terraform force-unlock command with the lock ID manually releases the lock.

Why this answer

The `terraform force-unlock` command with the lock ID is the correct way to manually unlock a state file in Terraform Cloud after a failed apply. This command overrides the backend's lock mechanism, which is designed to prevent concurrent modifications and state corruption. Deleting or editing the state file would bypass Terraform's safety guarantees and risk data loss or inconsistency.

Exam trap

The trap here is that candidates may confuse `terraform force-unlock` with a non-existent `terraform unlock` command, or mistakenly think that deleting or editing the state file is a valid workaround, when in fact Terraform's state locking is enforced at the backend API level and requires the proper command with the lock ID.

How to eliminate wrong answers

Option A is wrong because deleting the state file from the backend destroys the entire state history and can cause Terraform to lose track of managed resources, leading to orphaned infrastructure or re-creation attempts. Option C is wrong because manually editing the state file is unsupported and dangerous; it can corrupt the state, break Terraform's internal structure, and is not a valid operation for removing a lock. Option D is wrong because `terraform unlock` is not a valid Terraform command; the correct command is `terraform force-unlock`, which requires the lock ID as an argument.

291
Multi-Selecthard

A company is using Terraform to manage secrets in AWS Secrets Manager. They want to ensure that sensitive values are not exposed in logs, the console, or plan output. Which two practices should they implement? (Choose two.)

Select 2 answers
A.Use the sensitive flag in variable definitions
B.Use a remote backend with encryption
C.Use a data source to fetch secrets at runtime instead of hardcoding
D.Store variable values in terraform.tfvars file
E.Mark outputs as sensitive = true
AnswersA, E

Using sensitive = true within a variable definition explicitly instructs Terraform to redact the variable's value from all CLI outputs, including terraform plan and terraform apply. This ensures that sensitive data, such as API keys or database credentials, is replaced with (sensitive value) in the console, preventing accidental exposure in build logs or terminal history. This mechanism is crucial for maintaining the confidentiality of secrets during the infrastructure provisioning lifecycle.

Why this answer

Marking a variable with `sensitive = true` in its definition block tells Terraform to redact its value in CLI output, logs, and plan output. This prevents the secret from being displayed in plaintext during `terraform plan` or `terraform apply`, even if the variable is used in a resource argument. Option E is correct because setting `sensitive = true` on an output value instructs Terraform to suppress that output in the CLI and in any logs or console displays, ensuring the secret value is not exposed after apply.

Exam trap

A common trap is thinking that using a remote backend with encryption or a data source alone is sufficient to protect secrets from exposure in logs and plan output, when in fact only explicit `sensitive` annotations on variables and outputs control CLI display.

292
MCQmedium

A developer accidentally deletes the local terraform.tfstate file. The backend is configured to store state remotely in an S3 bucket. What is the effect on Terraform operations?

A.Terraform will create a new empty state file, losing all existing managed resources.
B.Terraform will fail with an error because the local state is missing.
C.Terraform will automatically recover the state from the remote backend on the next plan or apply.
D.Terraform will prompt the user to confirm whether to use the remote state.
AnswerC

Correct. With a remote backend, Terraform downloads the state from the remote source; the local file is not the authoritative copy.

Why this answer

When a remote backend (e.g., S3) is configured, Terraform stores the state file in the remote location and maintains a local copy as a cache. Deleting the local terraform.tfstate file does not affect the remote state. On the next plan or apply, Terraform automatically pulls the latest state from the remote backend, effectively recovering it without data loss or manual intervention.

Exam trap

The HashiCorp exam often tests the misconception that Terraform requires a local state file to operate, but with a remote backend, the local file is merely a cache and its deletion does not disrupt operations.

How to eliminate wrong answers

Option A is wrong because Terraform does not create a new empty state file when a remote backend is configured; it retrieves the existing state from the remote backend, preserving all managed resources. Option B is wrong because the local state is only a cache; its absence does not cause a failure since Terraform reads from and writes to the remote backend directly. Option D is wrong because Terraform does not prompt the user for confirmation; it automatically uses the remote state as defined in the backend configuration without interactive prompts.

293
Multi-Selecteasy

Which two statements about Terraform state files are true? (Choose two.)

Select 2 answers
A.State files are automatically encrypted at rest by all backends.
B.State files should be stored in version control.
C.State files are used to map configuration to real-world resources.
D.State files can be shared across multiple users simultaneously without issues.
E.State files can contain sensitive data such as database passwords.
AnswersC, E

State files are indeed used to map configuration to real-world resources, which is their primary and most fundamental function. The state file serves as the definitive source of truth, meticulously recording the unique identifiers and attributes of all infrastructure components provisioned by Terraform. This mapping allows Terraform to understand the current state of the infrastructure and accurately determine the necessary actions to reconcile it with the desired configuration defined in your HCL files.

Why this answer

Terraform state files serve as a mapping between configuration and real-world resources (C). They can contain sensitive data such as database passwords or resource attributes (E). However, state files are not automatically encrypted by all backends; encryption depends on the backend configuration (A false).

State files should not be stored in version control due to potential sensitive content (B false). Concurrent writes to state files can cause corruption or conflicts, so sharing without locking is problematic (D false).

294
MCQmedium

A startup is adopting Terraform to manage their cloud infrastructure. They want to ensure that changes to infrastructure are reviewed and approved before being applied. Which practice aligns with Infrastructure as Code principles to achieve this?

A.Implement a Git-based workflow with pull requests and automated plan reviews.
B.Use Terraform workspaces to separate environments and manually apply changes.
C.Store Terraform state files in a version control system to track changes.
D.Encourage developers to run terraform apply directly on production.
AnswerA

A Git-based workflow provides robust version control for Terraform configurations, enabling a complete audit trail of all infrastructure changes. Pull requests facilitate essential peer review and approval gates, ensuring code quality and adherence to organizational standards. Automated plan reviews, typically integrated into a CI/CD pipeline, validate syntax, enforce policies, and predict infrastructure changes, significantly reducing the risk of errors before deployment.

Why this answer

It aligns with Infrastructure as Code (IaC) principles by using a Git-based workflow where changes are proposed via pull requests, reviewed by peers, and validated through automated Terraform plan runs before merging. This ensures that all infrastructure modifications are version-controlled, auditable, and require explicit approval, preventing unauthorized or erroneous changes from being applied directly.

Exam trap

A common misconception is that storing Terraform state files in version control is a best practice, but it is actually a security anti-pattern because state files often contain sensitive data and Terraform requires state locking for safe concurrent operations.

How to eliminate wrong answers

Option B is wrong because Terraform workspaces are designed to manage multiple environment configurations within the same backend, but manually applying changes bypasses the review and approval process, violating IaC's principle of automated, auditable change management. Option C is wrong because storing Terraform state files in a version control system is a security risk (state files often contain sensitive data like plaintext passwords or access keys) and can lead to state corruption or conflicts; state should be stored in a remote backend with locking, not in VCS. Option D is wrong because encouraging developers to run terraform apply directly on production undermines the entire purpose of IaC, which is to enforce review, approval, and repeatability; it introduces risk of unapproved, unreviewed changes and violates the principle of treating infrastructure as code.

295
MCQhard

A module requires an input variable named 'vpc_id'. How should the calling configuration pass the VPC ID from another module's output?

A.vpc_id = module.vpc.outputs.vpc_id
B.vpc_id = var.vpc_id
C.vpc_id = vpc.module.vpc_id
D.vpc_id = module.vpc.vpc_id
AnswerD

This syntax, `vpc_id = module.vpc.vpc_id`, is the correct and standard method for referencing an output value from a module in Terraform. The `module` keyword signifies that a module instance is being referenced, `vpc` is the local name given to that specific module instance within the configuration, and `vpc_id` is the name of the output variable defined within the `vpc` module itself. This allows the output of one module to be used as an input for another resource or module.

Why this answer

In Terraform, when you need to reference an output from a child module, the syntax is `module.<module_name>.<output_name>`. The `.outputs.` prefix is not used; Terraform automatically exposes module outputs as direct attributes of the module resource. Therefore, `module.vpc.vpc_id` correctly retrieves the `vpc_id` output from the module named `vpc`.

Exam trap

The Terraform exam often tests the misconception that module outputs require an explicit `.outputs.` attribute, leading candidates to choose Option A, when in fact Terraform flattens outputs into direct module attributes for simplicity.

How to eliminate wrong answers

Option A is wrong because `module.vpc.outputs.vpc_id` incorrectly includes the `.outputs.` prefix; Terraform does not use an `outputs` attribute on module references—outputs are accessed directly as `module.<name>.<output_name>`. Option B is wrong because `var.vpc_id` references an input variable, not a module output; this would only work if the calling configuration had defined a variable named `vpc_id` and passed the VPC ID into it, which is not the scenario described. Option C is wrong because `vpc.module.vpc_id` uses an invalid syntax—module references must start with the `module.` keyword, not the module name first, and the order is reversed.

296
MCQeasy

Refer to the exhibit. A user has this backend configuration. The user then runs `terraform init` and receives an error: 'NoSuchBucket: The specified bucket does not exist'. What is the most likely cause?

A.The bucket does not exist and needs to be created.
B.The AWS region is wrong.
C.The DynamoDB table is missing.
D.The credentials lack S3 permissions.
AnswerA

The NoSuchBucket error explicitly indicates that the Amazon S3 bucket specified in the Terraform backend configuration does not exist within the AWS region where Terraform is attempting to initialize. Terraform's S3 backend requires a pre-existing S3 bucket to securely store the state file, which tracks the infrastructure managed by Terraform. Therefore, this error mandates that the user must manually create the S3 bucket with the exact name and in the correct region before terraform init can successfully configure the remote state.

Why this answer

The error 'NoSuchBucket: The specified bucket does not exist' directly indicates that the S3 bucket referenced in the backend configuration does not exist in the AWS account. Terraform requires the S3 bucket to already exist before running `terraform init` because it needs to store the state file; it does not create the bucket automatically. Therefore, the most likely cause is that the bucket has not been created yet.

Exam trap

Many candidates assume Terraform will automatically create the S3 bucket when the backend is configured, but Terraform requires the bucket to exist beforehand. Understanding this prerequisite is key for the exam.

How to eliminate wrong answers

Option B is wrong because if the AWS region were incorrect, the error would typically be 'BucketRegionError' or a timeout, not 'NoSuchBucket'; the bucket name is globally unique and the error specifically says the bucket does not exist, not that it cannot be reached. Option C is wrong because a missing DynamoDB table would cause an error related to state locking (e.g., 'ResourceNotFoundException') during `terraform apply`, not during `terraform init`; `terraform init` only checks the S3 bucket existence, not the DynamoDB table. Option D is wrong because insufficient S3 permissions would produce an 'AccessDenied' or 'Forbidden' error, not 'NoSuchBucket'; the error indicates the bucket is absent, not that access is denied.

297
MCQmedium

After running `terraform plan`, the user receives an error: `Error: Missing required variable`. The variable 'vpc_cidr' is provided. What is the most likely cause?

A.The module requires a variable 'environment' that is not passed.
B.The module block syntax is incorrect.
C.The variable 'vpc_cidr' is misspelled.
D.The variable 'vpc_cidr' conflicts with a provider variable.
AnswerA

A Terraform module's `variables.tf` file likely declares a variable named 'environment' without specifying a `default` value. When a variable lacks a default, it becomes mandatory and must be explicitly provided when the module is called. The `terraform plan` command fails because it cannot resolve a value for this required input, preventing the configuration from being evaluated and a plan from being generated.

Why this answer

The error 'Missing required variable' indicates that a variable required by the module has not been provided. Even though 'vpc_cidr' is supplied, the module likely defines a required input variable named 'environment' without a default value, and the user did not pass it in the module block. Terraform enforces that all required variables without defaults must be explicitly set by the caller.

Exam trap

The trap here is that candidates assume the error is about the variable they did provide, rather than recognizing that other required variables may be missing.

How to eliminate wrong answers

Option B is wrong because a syntax error in the module block would produce a parsing error (e.g., 'Expected: identifier'), not a 'Missing required variable' error. Option C is wrong because if 'vpc_cidr' were misspelled, Terraform would report an 'Unsupported argument' error, not a missing variable error. Option D is wrong because variable names in Terraform are scoped to the module or root; a provider variable cannot conflict with a module input variable — they are separate namespaces.

298
MCQeasy

A junior administrator wants to practice Terraform by deploying a single web server in AWS. They write a configuration file and run terraform init and terraform apply. The deployment succeeds but they notice the web server is not accessible from the internet. What is the most likely reason?

A.The instance type chosen does not support public IP addresses.
B.The terraform init command failed and the apply did not actually create resources.
C.The subnet is configured as private and does not have a route to the internet.
D.The security group does not allow inbound HTTP/HTTPS traffic from 0.0.0.0/0.
AnswerD

The security group does not allow inbound HTTP/HTTPS traffic from 0.0.0.0/0. This is the most probable cause. Security groups function as stateful virtual firewalls that control inbound and outbound traffic for instances. For a web server to be accessible over HTTP (port 80) or HTTPS (port 443) from any IP address on the internet (represented by 0.0.0.0/0), explicit inbound rules must be configured within the associated security group. Without these specific rules, all connection attempts on those ports will be silently dropped, making the web server appear inaccessible even if it is running and has a public IP address.

Why this answer

Even if the web server is deployed in a public subnet with a public IP address, the security group acts as a virtual firewall at the instance level. By default, AWS security groups block all inbound traffic. Without an explicit rule allowing inbound HTTP (port 80) or HTTPS (port 443) traffic from 0.0.0.0/0, the web server will not respond to internet requests, making it inaccessible from the internet.

Exam trap

HashiCorp often tests the misconception that a public subnet or public IP alone guarantees internet accessibility, when in fact the security group's inbound rules are the primary gatekeeper for traffic reaching the instance.

How to eliminate wrong answers

Option A is wrong because all AWS instance types support the assignment of public IP addresses; the ability to assign a public IP is controlled by the subnet's auto-assign public IP setting or the instance's network interface configuration, not the instance type. Option B is wrong because if terraform init had failed, terraform apply would not proceed to create resources; the question states the deployment succeeded, meaning both commands completed without error. Option C is wrong because a private subnet would prevent internet access entirely, but the question does not specify the subnet type; the most common and direct reason for a web server being inaccessible after a successful deployment is the lack of an inbound security group rule for HTTP/HTTPS traffic.

299
MCQmedium

A team is adopting Terraform to manage infrastructure. One requirement is that all configuration changes must be reviewed and approved before being applied. The team wants to ensure that the Terraform state file reflects the actual deployed infrastructure at all times. Which practice should they implement to meet these requirements?

A.Store state locally and use a manual approval process outside of Terraform.
B.Store state remotely and use a version control system with pull requests to review changes before applying.
C.Store state locally and use a shared network drive for team access.
D.Have each team member run terraform apply from their local machine after informal discussion.
AnswerB

Remote state enables team collaboration and VCS with PRs enforces review.

Why this answer

Storing state remotely (e.g., in S3, Azure Storage, or Terraform Cloud) enables state locking and versioning, which is essential for team collaboration. Using a version control system with pull requests ensures that all configuration changes are reviewed and approved before being applied, meeting the requirement for change control. This combination also ensures the state file accurately reflects deployed infrastructure by preventing concurrent modifications and providing an audit trail.

Exam trap

HashiCorp often tests the misconception that local state with manual processes is sufficient for team collaboration, but the trap here is that without remote state and version-controlled review, you cannot guarantee state consistency or enforce an approval gate, leading to drift and conflicts.

How to eliminate wrong answers

Option A is wrong because storing state locally prevents team collaboration and state locking, and a manual approval process outside of Terraform does not integrate with Terraform's workflow, risking state drift and concurrent apply conflicts. Option C is wrong because a shared network drive lacks state locking and versioning, leading to corruption or overwrites when multiple team members run terraform apply simultaneously. Option D is wrong because having each team member run terraform apply from their local machine after informal discussion bypasses any formal review or approval process, and local state files will diverge, causing inconsistency and potential infrastructure drift.

300
MCQmedium

A user wants to inspect the current attributes of a specific resource in the Terraform state. Which command should they use?

A.terraform state list <resource>
B.terraform output
C.terraform state show <resource>
D.terraform plan
E.terraform show
AnswerC

The `terraform state show <resource>` command precisely fulfills the requirement by displaying the complete, current state data for a specified resource address. This includes all recorded attributes, dependencies, and metadata as stored in the Terraform state file. It provides a detailed snapshot of the resource's last known configuration and status, making it ideal for inspecting specific resource attributes.

Why this answer

The `terraform state show <resource>` command is specifically designed to inspect the current attributes of a single resource within the Terraform state file. It reads the state directly and outputs the resource's attributes in a human-readable format, making it the correct tool for this task.

Exam trap

Terraform often tests the distinction between commands that list resources (`state list`) versus those that show detailed attributes (`state show`), and candidates frequently confuse `terraform show` (which dumps the entire state) with the resource-specific `terraform state show`.

How to eliminate wrong answers

Option A is wrong because `terraform state list` only lists resource addresses in the state, not their attributes; it does not show detailed attribute values. Option B is wrong because `terraform output` displays only output values defined in the configuration, not the attributes of arbitrary resources in the state. Option D is wrong because `terraform plan` compares the current state with the configuration to show changes, but it does not simply inspect current attributes of a specific resource.

Option E is wrong because `terraform show` displays the entire state or plan file in a formatted way, but it is not scoped to a single resource and does not provide the focused attribute inspection that `terraform state show` does.

Page 3

Page 4 of 6

Page 5

All pages