Courseiva

HashiCorp Terraform Associate TF-004 (TF-004) — Questions 376–434

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

Page 5

Page 6 of 6

376
MCQmedium

Based on the exhibit, what can be inferred about the Terraform state and configuration?

A.The aws_instance.db resource is in state but not in configuration, so it will be destroyed.
B.The configuration for aws_instance.db has been added back to the .tf files.
C.The aws_instance.db resource was manually deleted from the AWS console.
D.The aws_instance.web resource is being imported into Terraform management.
AnswerA

Terraform state lists aws_instance.db while the configuration no longer declares it, so the resource is orphaned. Applying the plan reconciles state to configuration by destroying that instance, satisfying the stem's inference about drift between the two.

Why this answer

The `terraform plan` output shows that `aws_instance.db` exists in the state file but is absent from the current configuration. Terraform interprets this as a resource that should be removed to align the real-world infrastructure with the configuration, so it will be destroyed. This is a core behavior of Terraform's desired-state management: any resource in state but not in configuration is marked for deletion.

Exam trap

HashiCorp often tests the distinction between resources missing from configuration (destroy) versus resources missing from the real world (re-create), and the trap here is confusing manual deletion with configuration removal.

How to eliminate wrong answers

Option B is wrong because if the configuration for `aws_instance.db` had been added back, the plan would show an update or no change, not a destroy. Option C is wrong because manual deletion from the AWS console would cause Terraform to detect the resource as missing and plan to re-create it, not destroy it. Option D is wrong because importing a resource would produce a plan that shows the resource being added to state without a destroy action, and the exhibit shows a destroy, not an import.

377
Multi-Selectmedium

Which TWO scenarios could cause 'terraform plan' to show 'No changes' even though the configuration file was recently modified? (Choose two.)

Select 2 answers
A.The user ran 'terraform plan' from a different directory that does not contain the modified configuration.
B.A lifecycle block with ignore_changes was applied to the modified attribute.
C.The resource was manually updated in the cloud provider console.
D.A new resource block was added.
E.The provider version was changed in the required_providers block.
AnswersA, B

terraform plan operates strictly within the current working directory, scanning for .tf configuration files to build its desired state. If a user executes terraform plan from a directory that does not contain the relevant configuration files, or an outdated set, Terraform will not detect any changes made to files in other directories. Consequently, the plan output will reflect no changes, as it's comparing the current state to an unchanged or non-existent desired state from its perspective.

Why this answer

`terraform plan` operates on the configuration files in the current working directory. If the user runs the command from a different directory that does not contain the modified configuration, Terraform will compare the state against the unmodified files in that directory, resulting in 'No changes'. Option B is correct because a `lifecycle` block with `ignore_changes` tells Terraform to disregard changes to specified attributes when planning, so even if the configuration file modifies that attribute, Terraform will not detect a diff and will report 'No changes'.

Exam trap

HashiCorp often tests the misconception that manual cloud console changes always cause plan output to show changes, but the trap here is that `ignore_changes` can suppress those diffs, and running `terraform plan` from the wrong directory can cause the command to read unmodified files, both leading to a false 'No changes' result.

378
Multi-Selectmedium

Which three practices help maintain consistency and reduce configuration drift in IaC? (Choose three.)

Select 3 answers
A.Storing state files remotely and locking them
B.Implementing CI/CD pipelines with automated testing
C.Regularly running terraform plan and apply
D.Using manual changes to fix minor issues
E.Allowing multiple team members to run apply simultaneously
AnswersA, B, C

Storing Terraform state files remotely, typically in a backend like S3, Azure Blob Storage, or HashiCorp Consul, centralizes the authoritative record of managed infrastructure. This remote storage, combined with state locking mechanisms provided by the backend, prevents multiple users or automated processes from concurrently modifying the state file. This ensures that only one operation can write to the state at a time, preventing race conditions, state corruption, and configuration drift caused by uncoordinated changes.

Why this answer

Storing state files remotely (e.g., in an S3 bucket with DynamoDB locking) prevents concurrent modifications and ensures that the state file reflects the true infrastructure state. This practice eliminates the risk of conflicting changes and configuration drift caused by local or stale state files.

Exam trap

A common trap in Terraform exams is assuming that manual changes or concurrent applies are acceptable shortcuts. The exam emphasizes that any deviation from the IaC pipeline—even minor fixes—introduces drift and undermines reproducibility.

379
MCQeasy

A developer runs terraform apply to create an AWS EC2 instance using an AMI sourced from the aws_ami data source with most_recent = true. Immediately after apply completes, the developer runs terraform plan again. The plan shows that Terraform intends to replace the EC2 instance. What is the most likely cause?

A.A new AMI was released after the apply, causing the data source to return a different AMI ID.
B.The developer did not run terraform init before the second plan.
C.The instance type was changed in the configuration between apply and plan.
D.The Terraform state file was corrupted during the apply.
AnswerA

When an `aws_ami` data source is configured with `most_recent = true`, Terraform dynamically queries AWS for the latest matching AMI during each `terraform plan` execution. If a new AMI is released by AWS between an `apply` and a subsequent `plan`, the data source will resolve to a different AMI ID. This change in the computed AMI ID, which is typically used by an `aws_instance` resource, will be detected by Terraform as a drift, necessitating the replacement of the existing EC2 instance to use the newly identified AMI.

Why this answer

The `aws_ami` data source with `most_recent = true` dynamically queries AWS for the latest AMI matching the specified filters at plan time. If a new AMI is published between the first `apply` and the subsequent `plan`, the data source returns a different AMI ID, causing Terraform to detect a change in the AMI attribute of the EC2 instance. Since the AMI ID is a force-new attribute for `aws_instance`, Terraform plans to replace the instance.

Exam trap

The TF-003 exam often tests the misconception that data source results are cached in state and remain static between runs, whereas in reality they are fetched fresh each plan, leading to potential drift when external resources change.

How to eliminate wrong answers

Option B is wrong because `terraform init` initializes the working directory and downloads providers/modules; it does not affect the freshness of data source results between plan runs. Option C is wrong because the question states the configuration was not changed between apply and plan, so a changed instance type is not the cause. Option D is wrong because a corrupted state file would typically cause errors or inconsistencies, not a clean plan to replace a resource with a different AMI ID.

380
Multi-Selecthard

A team uses an S3 backend for state storage with DynamoDB locking. They want to migrate to a new S3 bucket. Which two steps are necessary to perform a successful state migration? (Choose two.)

Select 2 answers
A.Run `terraform plan` to verify no resource changes before migration.
B.Delete the old state file after migration.
C.Run `terraform init -reconfigure` to update the backend configuration.
D.Manually copy the state file from the old bucket to the new bucket.
E.Update the `backend` block in the Terraform configuration with the new bucket name.
AnswersC, E

This command initializes the new backend and copies state.

Why this answer

`terraform init -reconfigure` forces Terraform to reinitialize the backend and apply the new backend configuration from the `backend` block without prompting for confirmation. Option E is correct because the `backend` block in the Terraform configuration must be updated to reference the new S3 bucket name; Terraform reads this block during initialization to determine where to store and retrieve state. Together, these steps ensure Terraform knows the new backend location and can properly manage state going forward.

Exam trap

A common misconception is that manually copying the state file is required or that `terraform plan` can validate backend changes, when in fact the correct workflow is to update the backend block and run `terraform init -reconfigure` to reinitialize the backend.

381
MCQmedium

A team is using Terraform to manage infrastructure across multiple environments (dev, test, prod). They want to reuse the same configuration but vary resource configurations like instance size and number of instances. Which Terraform feature should they use?

A.Separate directories with symlinks
B.Remote backends with different state files
C.Terraform modules with variables
D.Terraform workspaces
AnswerC

Terraform modules with variables are the correct and recommended pattern for managing infrastructure across multiple environments or teams. Modules encapsulate a set of related resources into a reusable component, which can then be instantiated multiple times. By passing different variable values to the module for each environment (e.g., `dev`, `staging`, `prod`), teams can deploy identical infrastructure patterns with environment-specific configurations, promoting consistency, reducing code duplication, and simplifying maintenance.

Why this answer

Terraform modules with variables let the team define a single reusable configuration and pass environment-specific values (instance size, instance count) as input variables, avoiding duplication while keeping one source of truth. This is the idiomatic Terraform pattern for multi-environment deployments.

Exam trap

The trap is confusing state isolation (workspaces, remote backends) with configuration parameterization — candidates pick D because workspaces sound environment-aware, but they don't vary resource attributes.

How to eliminate wrong answers

Option A is wrong because symlinked directories are a fragile anti-pattern that duplicates configuration and breaks portability — Terraform does not natively support symlinks well and they cause state confusion. Option B is wrong because remote backends with different state files isolate state but do not parameterize resource configuration; you still need separate configs or variables. Option D is wrong because workspaces share the same configuration and are intended for ephemeral or parallel environments, but they do not natively support different variable values per environment without external tooling (e.g., tfvars per workspace), and they are discouraged for strong dev/prod separation due to shared backend risk.

382
MCQmedium

A team has two resources: an AWS security group and an EC2 instance that uses it. Terraform does not automatically detect the dependency. Which argument should be added to the instance resource?

A.depends_on = [aws_security_group.sg.*]
B.depends_on = aws_security_group.sg
C.depends_on = [aws_security_group.sg]
D.depends_on = [aws_security_group.sg.id]
AnswerC

This option, `depends_on = [aws_security_group.sg]`, correctly specifies an explicit dependency. It uses the full resource address `aws_security_group.sg` within a list, which is the precise syntax Terraform expects for the `depends_on` argument. This ensures that the `aws_security_group.sg` resource is fully created and available before the resource declaring this dependency is provisioned, correctly ordering operations in the dependency graph.

Why this answer

Terraform requires explicit dependency declarations when it cannot infer them from resource references. The `depends_on` argument must be a list of resource references, and `[aws_security_group.sg]` correctly references the security group resource as a single-element list. This ensures Terraform creates the security group before the EC2 instance that depends on it.

Exam trap

The trap here is that candidates confuse attribute references (like `.id`) with resource references, or forget that `depends_on` must be a list, leading them to pick options that are syntactically or semantically invalid.

How to eliminate wrong answers

Option A is wrong because `aws_security_group.sg.*` is a splat expression that returns a list of all attributes of the resource, not a resource reference; Terraform expects resource addresses, not attribute lists. Option B is wrong because `depends_on` requires a list type, not a single resource reference; omitting the square brackets causes a type error. Option D is wrong because `aws_security_group.sg.id` is an attribute reference (the ID string), not a resource reference; Terraform cannot use attribute values to establish dependencies.

383
Multi-Selecthard

Which TWO of the following are valid ways to reference a resource attribute in Terraform?

Select 2 answers
A.`module.vpc.output`
B.`data.aws_ami.ubuntu.id`
C.`var.instance_type`
D.`module.vpc.vpc_id`
E.`aws_instance.web.id`
AnswersD, E

This is a valid way to reference an attribute. It correctly accesses the `vpc_id` output from a child module named `vpc`. Module outputs are commonly used to expose specific attributes or computed values from resources managed within that module, making them accessible to the parent module or other parts of the configuration. This effectively references a value derived from a resource within the module, making it a valid answer.

Why this answer

`module.vpc.vpc_id` directly references an output attribute from a module. In Terraform, module outputs are accessed using the syntax `module.<module_name>.<output_name>`, and `vpc_id` is a common output from VPC modules that exposes the ID of the created VPC resource.

Exam trap

HashiCorp often tests the distinction between resource attributes, data source attributes, module outputs, and input variables, and the trap here is that candidates confuse data source references (like `data.aws_ami.ubuntu.id`) with resource attribute references, or they think `module.vpc.output` is a valid catch-all syntax for module outputs.

384
MCQeasy

A developer has a Terraform configuration that includes an output block. They run `terraform apply` and then want to quickly retrieve the output value without re-running the entire apply. Which command should they use?

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

terraform output reads values directly from the state file, printing declared outputs without contacting providers or recalculating the plan. This satisfies the stem's requirement to retrieve the value quickly without re-running apply, which would otherwise refresh resources and risk unintended changes.

Why this answer

The `terraform output` command is specifically designed to retrieve the values of output variables from the state file without re-running the entire `terraform apply` operation. It reads the outputs stored in the Terraform state after a successful apply, making it the fastest and most direct way to access those values. This command supports flags like `-json` for structured output and can target a specific output by name.

Exam trap

The TF-003 exam often tests the distinction between commands that read the state (`terraform output`, `terraform state list`, `terraform show`) versus commands that modify infrastructure or plan changes, and the trap here is that candidates confuse `terraform show` with `terraform output` because both can display state information, but only `terraform output` is optimized for retrieving output values.

How to eliminate wrong answers

Option A is wrong because `terraform plan` creates or updates an execution plan to show what changes will be made, but it does not display output values from the state. Option B is wrong because `terraform state list` only lists resources tracked in the state, not output values. Option C is wrong because `terraform show` displays the current state or a saved plan in human-readable form, but it is not the dedicated command for quickly retrieving output values; it shows the entire state or plan, which is less efficient than `terraform output`.

385
MCQhard

A team uses Terraform Cloud with a VCS-backed workflow. They notice that a recent commit triggered a run that failed because of an invalid configuration. The team fixed the configuration and wants to re-run the plan without committing again. Which action should they take?

A.Amend the previous commit and force push
B.Create a new commit with the fix
C.Use the 'Queue Plan' button in the Terraform Cloud UI
D.Run terraform plan locally and apply
AnswerB

Creating a new commit with the fix is the correct and standard procedure for a VCS-backed workflow in Terraform Cloud. This action pushes the updated configuration to the remote repository, which Terraform Cloud actively monitors for changes. Upon detecting the new commit, Terraform Cloud automatically initiates a new run (plan and potentially apply) using the corrected code, ensuring the infrastructure aligns with the intended state.

Why this answer

In a VCS-backed Terraform Cloud workspace, runs are triggered by commits to the linked repository. When a configuration error is found in the code, fixing it requires a new commit that includes the corrected code. The 'Queue Plan' button re-runs a plan using the same commit, so it cannot incorporate local fixes.

Creating a new commit (option B) triggers a new run with the fixed configuration.

Exam trap

Candidates may think that the 'Queue Plan' button can re-run a plan with any configuration fix, but it only uses the same commit and workspace settings. If the fix involves version-controlled files, a new commit is necessary.

How to eliminate wrong answers

Option A is wrong because amending the previous commit and force pushing rewrites Git history, which can disrupt team collaboration and is not a recommended practice for fixing a failed run in Terraform Cloud; it also does not leverage Terraform Cloud's built-in run management. Option B is wrong because creating a new commit with the fix would trigger a new run automatically, but the question specifically asks to re-run the plan without committing again, making this an unnecessary and incorrect approach. Option D is wrong because running terraform plan locally and applying bypasses Terraform Cloud's VCS-backed workflow, state management, and collaboration features, and the apply would not be tracked or approved through Terraform Cloud's run pipeline.

386
Drag & Dropmedium

Drag and drop the steps to manage Terraform state locking with a backend in the correct order.

Drag or tap steps into the slots.

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

Why this order

Backend config must include locking mechanism; init sets up backend, apply uses lock.

387
MCQhard

A team uses Terraform with multiple workspaces and wants to automatically trigger a plan when a pull request is opened in their Git repository. They use Terraform Cloud. Which feature enables this?

A.VCS-driven workflow
B.API-driven workflow
C.CLI-driven workflow
D.Registry-driven workflow
AnswerA

A VCS-driven workflow integrates Terraform with a Version Control System like Git, automatically triggering `terraform plan` operations in a remote execution environment (e.g., Terraform Cloud/Enterprise) whenever changes are pushed or a Pull Request (PR) is opened. This approach provides continuous validation of infrastructure changes, allowing teams to review and approve proposed modifications before they are applied, which is essential for managing multiple workspaces collaboratively and maintaining infrastructure consistency.

Why this answer

The VCS-driven workflow in Terraform Cloud automatically triggers a plan when a pull request is opened in a connected Git repository. This is configured by linking a VCS provider (e.g., GitHub, GitLab) to a workspace and enabling speculative plans on pull requests, which allows Terraform Cloud to run a plan without applying changes.

Exam trap

HashiCorp often tests the distinction between VCS-driven and API-driven workflows, where candidates mistakenly think any automated trigger must use the API, but the VCS-driven workflow is the native Git integration that handles PR events without custom API calls.

How to eliminate wrong answers

Option B is wrong because the API-driven workflow requires an external system to call the Terraform Cloud API to trigger runs, not automatically on pull requests. Option C is wrong because the CLI-driven workflow relies on local execution of Terraform commands, not on Git events. Option D is wrong because the Registry-driven workflow is used for consuming modules from the Terraform Registry, not for triggering plans from VCS events.

388
MCQmedium

A company uses Terraform to manage infrastructure across multiple AWS accounts. They want to use a single S3 bucket to store state files for all accounts, but ensure that state files are isolated per account. What is the best approach?

A.Use Terraform workspaces with a single state file
B.Use separate state files with unique S3 key prefixes per account
C.Store all state in the same S3 key
D.Use a DynamoDB table with different lock IDs per account
AnswerB

This approach correctly isolates Terraform state for each distinct AWS account. By configuring the S3 backend with unique `key` prefixes (e.g., `account-a/terraform.tfstate`, `account-b/terraform.tfstate`), each account's infrastructure state is stored in its own dedicated path within the S3 bucket. This prevents state file collisions, ensures independent management, and maintains clear separation of concerns across different environments or accounts.

Why this answer

Using separate state files with unique S3 key prefixes per account ensures that each AWS account's Terraform state is stored in the same S3 bucket but logically isolated. This approach leverages S3's hierarchical key structure to prevent cross-account state contamination, while still allowing centralized management. Terraform's backend configuration supports dynamic key prefixes (e.g., `key = "account-${var.account_id}/terraform.tfstate"`), enabling per-account isolation without requiring separate buckets or workspaces.

Exam trap

The trap here is that candidates confuse Terraform workspaces with true state isolation across accounts, not realizing that workspaces only provide logical separation within a single backend path and do not prevent cross-account state conflicts when using a shared S3 bucket.

How to eliminate wrong answers

Option A is wrong because Terraform workspaces store state files within the same backend path (same S3 key) by default, using a directory-like structure (e.g., `env:/workspace_name`), which does not provide true isolation per AWS account—state files can still be accidentally overwritten or accessed across workspaces if the backend key is not carefully managed. Option C is wrong because storing all state in the same S3 key would cause all accounts to share a single state file, leading to conflicts, corruption, and inability to manage separate infrastructure stacks. Option D is wrong because DynamoDB lock IDs are used for state locking and consistency, not for isolating state files per account; different lock IDs do not prevent state file collisions when multiple accounts write to the same S3 key.

389
MCQmedium

Refer to the exhibit. An engineer runs terraform plan and sees this output. Which statement about the planned change is true?

A.The change will replace the existing ingress rule with a new one.
B.The security group will be destroyed and recreated.
C.Terraform will add a new ingress rule without removing the old one.
D.The security group will be updated but the ingress rule will remain unchanged.
AnswerA

The plan output shows '-/+' next to the ingress rule, meaning Terraform will destroy the existing rule and create a new one with the updated CIDR block. This is a replacement, not an in-place update.

Why this answer

When Terraform's plan output shows an ingress rule being replaced — typically indicated by a `-/+` symbol or a `~` with a `# forces replacement` annotation on the ingress block — it means the existing rule cannot be updated in place and must be destroyed and recreated. This happens because the ingress attribute is a set of objects, and changing a set element's identity forces Terraform to remove the old element and add the new one. The security group itself remains, only the rule is swapped.

Exam trap

The trap is misreading the plan symbol — candidates see a change on the security group and assume the whole resource is being destroyed, when only the nested ingress rule is being replaced.

How to eliminate wrong answers

Option B is wrong because the plan output shows only the ingress rule being replaced, not the entire security group resource — a full replacement would show `-/+` on the aws_security_group resource itself. Option C is wrong because Terraform does not append a new ingress rule alongside the old one; the plan explicitly shows the old rule being removed as part of the replacement. Option D is wrong because the plan clearly indicates the ingress rule is changing, not remaining unchanged — if it were unchanged, no diff would appear for that attribute.

390
MCQhard

Refer to the exhibit. A developer runs terraform plan and sees "No changes". However, the developer knows that manual changes were made to the infrastructure outside Terraform. What is the most likely reason terraform plan does not detect the drift?

A.The manual changes were made to resources not managed by Terraform.
B.Terraform only detects drift when running terraform apply.
C.The manual changes were reverted before the plan was run.
D.Terraform plan does not refresh state by default; it uses the existing state file.
AnswerA

This is the correct explanation. Terraform's `plan` command operates by comparing the desired state (from configuration files) with the actual state of *managed* resources (as recorded in the state file and refreshed from the cloud provider). If manual changes were applied to resources that were provisioned outside of Terraform's control, or to attributes of managed resources that Terraform does not explicitly track, these changes would not be reflected in the Terraform state file and thus would be invisible to `terraform plan`.

Why this answer

Terraform plan detects drift by comparing the current configuration against the state file, but only for resources that Terraform manages. If manual changes are made to resources that are not recorded in Terraform's state (i.e., resources created outside of Terraform or not imported), then plan will not detect them because those resources are unknown to Terraform. Options B, C, and D are incorrect: B is false because plan can detect drift with refresh; C is not necessarily true as the changes may still exist; D is false because modern Terraform refreshes state by default before planning, but that refresh only applies to managed resources.

Exam trap

A common mistake is assuming that `terraform plan` detects any infrastructure drift, but it only detects changes to resources that Terraform manages. Manual changes to unmanaged resources are invisible to Terraform.

How to eliminate wrong answers

Option A is wrong because even if manual changes are made to resources managed by Terraform, the plan will still show 'No changes' if the state is not refreshed — the issue is not about whether the resource is managed, but about the state being stale. Option B is wrong because Terraform can detect drift during `terraform plan` if the refresh step is enabled (which it is by default in recent versions), but the question's scenario assumes the default behavior where the plan does not refresh; `terraform apply` also refreshes by default, but drift detection is not exclusive to apply. Option C is wrong because the question explicitly states that manual changes were made and not reverted; the 'No changes' result is due to the state not reflecting those changes, not because they were undone.

391
MCQhard

After running terraform apply, you see the error: 'Error: Error loading state: state snapshot was created by Terraform v0.12.0, but this is Terraform v1.2.0'. What should you do to resolve this?

A.Run terraform state upgrade
B.Run terraform apply with no changes to upgrade the state format
C.Delete the state file and reimport resources
D.Downgrade Terraform to v0.12.0
AnswerB

When an older Terraform state file is detected by a newer version of the Terraform CLI, running `terraform apply` will automatically initiate an upgrade of the state format to the current version. Even if there are no configuration changes to apply, Terraform processes the existing state and writes it back in the updated format, resolving compatibility issues. This is the standard and recommended procedure for state file upgrades.

Why this answer

Running `terraform apply` with no changes triggers Terraform to automatically upgrade the state file format to the version compatible with the current Terraform binary (v1.2.0). Terraform state files are versioned internally, and when a newer version of Terraform reads an older state format, it performs an in-place upgrade during the next state write operation, such as an apply that results in no changes. This avoids manual intervention or data loss.

Exam trap

HashiCorp often tests the misconception that there is a dedicated `terraform state upgrade` command, leading candidates to choose Option A, but Terraform handles state format upgrades implicitly during apply operations, not via a separate command.

How to eliminate wrong answers

Option A is wrong because `terraform state upgrade` is not a valid Terraform command; the correct command for upgrading state format is `terraform apply` with no changes or `terraform init -upgrade` for provider upgrades, not a dedicated state upgrade command. Option C is wrong because deleting the state file and reimporting resources is unnecessarily destructive and error-prone; it would require manual re-import of every resource, losing any existing state metadata and risking configuration drift. Option D is wrong because downgrading Terraform to v0.12.0 is a backward step that would lose access to features and fixes in v1.2.0, and it does not resolve the version mismatch; the state file would still be in the older format and would need to be upgraded eventually.

392
MCQeasy

Refer to the exhibit. A Terraform plan fails with the error shown. What is the most likely cause?

A.The S3 bucket does not have versioning enabled.
B.The DynamoDB table is not configured correctly.
C.The state file is corrupted.
D.Another Terraform run is currently in progress.
AnswerD

When a Terraform operation, such as `plan` or `apply`, is initiated, it first attempts to acquire a state lock to prevent concurrent modifications. If another Terraform process is already running against the same state, it will hold this lock, causing subsequent operations to fail with a 'lock acquisition failed' error. This mechanism ensures state consistency and prevents potential corruption from simultaneous updates.

Why this answer

The error message indicates that Terraform cannot acquire a state lock. This typically occurs when another Terraform run is already in progress and holds the lock on the state file. Terraform uses a locking mechanism (often via DynamoDB) to prevent concurrent modifications; if a lock is already held, subsequent runs will fail with this error until the lock is released or expires.

Exam trap

HashiCorp often tests the distinction between state file corruption and state locking errors; the trap here is that candidates may confuse a lock failure with a state file issue, especially when the error message includes DynamoDB references.

How to eliminate wrong answers

Option A is wrong because S3 bucket versioning is not related to state locking; versioning helps with state file history and recovery, but does not cause lock acquisition failures. Option B is wrong because while a misconfigured DynamoDB table could cause lock failures, the error message specifically points to an existing lock being held, not a configuration issue. Option C is wrong because a corrupted state file would typically cause parsing or validation errors, not a lock acquisition failure.

393
Drag & Dropmedium

Drag and drop the steps to use Terraform workspaces for environment separation in the correct order.

Drag or tap steps into the slots.

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

Why this order

The correct sequence for using Terraform workspaces is: first create the workspace (if it doesn't exist) to isolate state, then select it to switch to that workspace's state, then set environment-specific variables (e.g., via .tfvars files) to tailor configuration, and finally run terraform plan and apply to manage resources. Workspaces are essential for environment separation, ensuring state isolation and preventing cross-environment interference.

394
MCQhard

A team is using Terraform with multiple environments (dev, staging, prod) and wants to use separate state files. They are considering workspaces. A senior engineer suggests using separate directory structures instead of workspaces for prod. What is the strongest reason for this recommendation?

A.Workspaces share the same backend configuration, increasing the risk of accidental changes to production.
B.Workspaces cannot isolate state files.
C.Workspaces make it harder to refactor configurations.
D.Workspaces do not support state locking.
AnswerA

Workspaces, by design, share the same backend configuration, meaning a single `terraform init` command configures access to a specific remote state location (e.g., an S3 bucket or Azure Storage Account) for all workspaces. This shared backend increases the risk that an operator might accidentally switch to a production workspace while intending to work in a development environment, leading to unintended modifications or destruction of critical production infrastructure. The underlying backend access credentials and configuration are identical across all workspaces within that directory.

Why this answer

Workspaces share the same backend configuration, meaning all workspaces (including prod) use the same state storage location and access controls. This increases the risk of accidental changes to production because a single backend misconfiguration or a mistaken workspace switch can lead to unintended modifications to the production state file. Separate directory structures allow for independent backend configurations, enabling stricter access controls and isolation for production.

Exam trap

HashiCorp often tests the misconception that workspaces provide full isolation, when in fact they only isolate state file keys, not the backend configuration or access controls, making separate directories safer for production environments.

How to eliminate wrong answers

Option B is wrong because workspaces do isolate state files by storing them under the same backend with a workspace-specific key, but they do not isolate the backend configuration itself. Option C is wrong because workspaces do not inherently make refactoring harder; in fact, they can simplify configuration reuse across environments. Option D is wrong because workspaces fully support state locking via the backend (e.g., DynamoDB for S3), just like separate directories.

395
MCQhard

When running terraform plan, the output indicates that a resource will be replaced (destroy then create) due to a change in the 'name' attribute. However, the engineer only changed a tag. What is the most likely cause?

A.The tag change triggered a ForceNew attribute.
B.The resource has create_before_destroy enabled.
C.The 'name' attribute is computed and any change to the resource forces replacement.
D.The underlying API does not support in-place updates.
AnswerC

Many resource types have core identifying attributes, such as 'name', that are immutable after initial creation. If the provider marks the 'name' attribute as `ForceNew`, any attempt to modify its value in the configuration will necessitate the destruction of the existing resource and the creation of a new one. Even if 'name' is `computed`, meaning its value is determined by the provider, if the provider's internal logic dictates that the resource's identity (often tied to its name) cannot be altered in-place, then any change impacting that identity will trigger replacement.

Why this answer

When a resource attribute is marked as 'computed' and 'ForceNew' in the Terraform provider schema, any change to that attribute—or, in some provider implementations, any change to the resource at all—triggers a destroy-and-create cycle. In this scenario, the engineer changed only a tag, but the provider has been configured to treat the entire resource as requiring replacement if any attribute changes, often because the 'name' attribute is computed from other inputs or because the provider's internal logic forces replacement on any update. This is a known behavior in certain Terraform providers where the 'name' attribute is set to 'Computed' and 'ForceNew' in the schema, causing any modification to the resource to result in a plan that shows replacement.

Exam trap

A common misconception is that any attribute change causing replacement must be due to a ForceNew on that specific attribute, when in fact a computed attribute like 'name' can force replacement on any resource change because the provider recalculates it and sees a diff.

How to eliminate wrong answers

Option A is wrong because a tag change does not inherently trigger a ForceNew attribute; ForceNew is a schema-level property of a specific attribute, not a side effect of changing a tag. Option B is wrong because 'create_before_destroy' is a lifecycle configuration that affects the order of operations during replacement (creating the new resource before destroying the old one), not the cause of the replacement itself. Option D is wrong because while some APIs do not support in-place updates, this would cause a replacement for any change, not just a tag change, and the question specifies that only a tag was changed—so the API's lack of support would not explain why a tag change specifically triggers replacement unless the tag itself is mapped to a ForceNew attribute.

396
MCQeasy

A company wants to integrate Terraform with their CI/CD pipeline to automatically deploy infrastructure. Which Terraform feature should they use to ensure state files are stored securely and accessible by the pipeline?

A.Terraform import
B.Local state with .gitignore
C.Terraform Cloud remote state
D.terraform state push
AnswerC

Terraform Cloud provides a highly secure, reliable, and accessible remote backend for storing Terraform state files. It automatically handles state locking to prevent concurrent modifications, encrypts state at rest and in transit, and offers versioning for auditability. Its API-driven nature and direct integration with Terraform runs make it an ideal solution for CI/CD pipelines, ensuring consistent and collaborative infrastructure management across automated deployments.

Why this answer

Terraform Cloud remote state stores the state file in a managed, access-controlled backend that CI/CD pipelines can authenticate to via API tokens, providing secure storage, locking, and versioning. This satisfies the requirement that state be stored securely and be reliably accessible to the pipeline without committing it to source control.

Exam trap

TF-004 often tests the misconception that keeping state local and gitignoring it is 'secure enough,' when the real requirement is a shared, locked, access-controlled remote backend for CI/CD.

How to eliminate wrong answers

Option A is wrong because 'terraform import' brings existing infrastructure under Terraform management; it has nothing to do with where or how state is stored. Option B is wrong because local state with .gitignore keeps state off source control but leaves it on a single machine, making it inaccessible to CI/CD runners and prone to loss or concurrent-write corruption. Option D is wrong because 'terraform state push' is a manual command to overwrite remote state — it is an operation, not a secure storage feature, and misusing it can corrupt state.

397
MCQhard

In a CI/CD pipeline, Terraform state is stored in Terraform Cloud. A pipeline run fails with the error: 'State version conflict'. What is the most likely cause?

A.Authentication failure with Terraform Cloud
B.Missing or incorrect backend configuration
C.State file exceeds maximum size limit
D.Terraform version mismatch between local and remote
E.Two runs started at the same time
AnswerE

This is the most likely cause. When two runs are started at the same time, the second run may be based on an outdated state version because the first run's state write completes before the second run's state read. Terraform Cloud then detects the version mismatch and throws a 'State version conflict' error.

Why this answer

Terraform Cloud enforces state locking so that only one run can modify a given workspace's state at a time. When two runs (e.g., concurrent pipeline jobs, or a manual run overlapping a CI run) attempt to write state simultaneously, the second run fails with a 'state version conflict' because the state serial it read is no longer current. This is the classic concurrency symptom.

Exam trap

TF-004 often tests whether candidates can distinguish state locking/concurrency errors from authentication, backend, or version errors, tempting them toward 'backend misconfiguration' when the real signal is simultaneous runs.

How to eliminate wrong answers

Option A is wrong because authentication failures produce 401/403 errors or 'invalid credentials' messages, not state version conflicts. Option B is wrong because a missing or incorrect backend configuration causes initialization errors like 'backend initialization required' or 'no backend configured,' not a version conflict at apply time. Option C is wrong because Terraform Cloud's state size limit (typically 500 MB for the free tier) produces a size-related error, not a version conflict.

Option D is wrong because a Terraform version mismatch triggers a 'state was created by a newer version' or required_version constraint error, distinct from a serial/version conflict.

398
Multi-Selecteasy

A small company with no cloud automation today wants to understand what adopting Terraform would give them beyond simply storing infrastructure definitions in Git. Which two outcomes does Terraform's core workflow provide? (Choose two.)

Select 2 answers
A.Continuous runtime monitoring with alerting when application latency exceeds a threshold.
B.Automatic remediation of misconfigured operating system settings inside running virtual machines.
C.A preview of proposed changes before any are applied, so reviewers can approve or reject them.
D.Guaranteed zero-downtime deployments for every resource type without any configuration effort.
E.A recorded mapping of configuration to real resources that lets later runs detect drift and target updates.
AnswersC, E

The core workflow includes terraform plan, which compares configuration and state and shows the actions that would be taken without changing real infrastructure. This preview supports peer review and change approval, which is a concrete benefit beyond merely keeping definitions in version control, since Git alone cannot show what an apply would do.

Why this answer

Terraform's core workflow is write, plan, and apply, backed by state. The plan step gives a reviewable preview of pending changes, and state maps configuration to real resources so subsequent runs can detect drift and compute targeted updates. In-guest OS remediation, application monitoring, and universal zero-downtime guarantees fall outside the provisioning workflow and are handled by other tooling or by explicit design choices.

Exam trap

The trap here is conflating Terraform's provisioning scope with configuration management and monitoring duties that other tools own.

399
MCQhard

A company uses Terraform to manage infrastructure on AWS. They have a configuration that creates an S3 bucket and a DynamoDB table for state locking. The team notices that sometimes when two members run terraform apply simultaneously, they get a state locking error. However, they want to allow concurrent operations on different workspaces. What is the best approach?

A.Remove the DynamoDB table and use local state files to avoid locking issues.
B.Configure all team members to use the same workspace so that only one person can apply at a time.
C.Keep the current setup because the error is harmless and users can retry.
D.Use separate state files per workspace and ensure each workspace has its own lock entry in DynamoDB; the current setup already supports this.
AnswerD

Terraform workspaces inherently create separate state files within the configured remote backend, such as an S3 bucket. Each of these distinct state files is then protected by its own unique lock entry in the DynamoDB table, preventing concurrent modifications to that specific workspace's state. This design allows multiple team members to concurrently apply changes to different workspaces without conflict, leveraging the robust locking mechanisms provided by the remote backend.

Why this answer

Terraform natively supports per-workspace state files, and when using a remote backend like S3 with DynamoDB for state locking, each workspace's state file is stored at a distinct path in S3. The DynamoDB lock entry is tied to the specific state file path via the LockID, so concurrent operations on different workspaces acquire separate locks and do not conflict. This setup allows multiple team members to run terraform apply simultaneously as long as they are working in different workspaces.

Exam trap

HashiCorp often tests the misconception that DynamoDB locking is global across all workspaces, when in fact the lock is scoped to the specific state file path, which includes the workspace name.

How to eliminate wrong answers

Option A is wrong because removing the DynamoDB table and using local state files eliminates state locking entirely, which can lead to state corruption if multiple users apply changes concurrently, even on different workspaces. Option B is wrong because configuring all team members to use the same workspace defeats the purpose of allowing concurrent operations and forces serialization of all applies, reducing team productivity. Option C is wrong because the state locking error is not harmless; it indicates a real conflict that can cause corruption or inconsistent state if ignored, and simply retrying does not address the underlying need for concurrent workspace-level isolation.

400
MCQhard

A DevOps engineer runs terraform plan and sees that a resource will be destroyed and recreated, but they expected an in-place update. The resource is an AWS EC2 instance with a specific AMI. Which attribute change is most likely causing the destruction?

A.The AMI ID was changed.
B.The security group list was modified.
C.The tags were updated.
D.The instance type was reduced from large to micro.
AnswerA

Changing the Amazon Machine Image (AMI) ID for an EC2 instance resource in Terraform necessitates a full replacement of the instance. This is because the AMI defines the operating system and initial software configuration of the instance's root volume at launch time. Since the root volume is intrinsically tied to the AMI used for its creation, an update to the AMI ID cannot be applied in-place to an already running instance, thus forcing Terraform to destroy the old instance and create a new one.

Why this answer

Changing the AMI ID of an AWS EC2 instance is a force-new attribute in Terraform. Because the AMI defines the root block device and operating system, Terraform cannot perform an in-place update; it must destroy the existing instance and create a new one with the new AMI. This behavior is hardcoded in the Terraform AWS provider for the `aws_instance` resource.

Exam trap

A common misconception is that any attribute change requiring a stop/start (like instance type) results in destroy-and-recreate, but in Terraform, stop/start is still an in-place update unless the attribute is explicitly marked `ForceNew`.

How to eliminate wrong answers

Option B is wrong because modifying the security group list triggers a `ModifyInstanceAttribute` API call, which is an in-place update, not a destroy-and-recreate. Option C is wrong because updating tags uses the `CreateTags` API and is always an in-place operation. Option D is wrong because changing the instance type (e.g., from large to micro) triggers a `StopInstances`, `ModifyInstanceAttribute` (instance type), and `StartInstances` sequence, which is an in-place update (though it requires a stop/start cycle) and does not cause destruction.

401
MCQmedium

A team is using a module from the Terraform Registry. They want to ensure that changes to the module's source version are tested in a non-production environment before being applied to production. Which approach best supports this workflow?

A.Fork the module repository and manage the module internally as a private module.
B.Pin the module to an exact version (e.g., version = "1.2.3") and update it manually after testing in isolation.
C.Configure the module source to reference the latest commit from the default branch of the repository.
D.Use a version constraint like ~> 1.0 in the module configuration and test the module in a non-production workspace before promoting to production.
AnswerD

Using a pessimistic version constraint like `~> 1.0` allows for automatic updates to minor and patch versions (e.g., `1.1.x`, `1.2.x`) while preventing potentially breaking major version upgrades. This strategy, combined with thorough testing in a dedicated non-production workspace, ensures controlled adoption of module improvements and bug fixes before safely promoting changes to critical production environments. It effectively balances stability with the ability to receive necessary updates.

Why this answer

Using a version constraint like `~> 1.0` allows Terraform to automatically select the latest compatible patch version within the specified minor version range. This enables safe, incremental updates that can be tested in a non-production workspace first, and then promoted to production by simply applying the same configuration. The constraint ensures that breaking changes (major version bumps) are not automatically pulled in, giving the team control over when to adopt them.

Exam trap

HashiCorp often tests the misconception that pinning to an exact version (Option B) is the safest approach for controlled testing, but the question specifically asks for a workflow that supports testing changes *before* production, which the pessimistic constraint enables automatically without manual version bumps.

How to eliminate wrong answers

Option A is wrong because forking the module repository and managing it internally as a private module adds significant overhead and defeats the purpose of using a public registry module; it also bypasses the version constraint workflow entirely. Option B is wrong because pinning to an exact version (e.g., version = "1.2.3") requires manual updates and does not automatically test newer compatible versions in a non-production environment before promotion. Option C is wrong because referencing the latest commit from the default branch introduces uncontrolled, potentially breaking changes directly into the configuration, with no versioning or testing gate before production.

402
Drag & Dropmedium

Drag and drop the steps to use Terraform modules from the registry in the correct order.

Drag or tap steps into the slots.

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

Why this order

Registry modules are sourced; init downloads, variables configure, plan/apply deploy.

403
MCQeasy

Which of the following commands creates an execution plan that shows what resources will be created, updated, or destroyed?

A.terraform apply
B.terraform plan
C.terraform output
D.terraform destroy
E.terraform validate
AnswerB

`terraform plan` performs a dry-run refresh and diff against state, then outputs the proposed changes as add, change, or destroy actions without applying them. This directly satisfies the stem's requirement for an execution plan showing what resources will be created, updated, or destroyed.

Why this answer

The `terraform plan` command creates an execution plan by comparing the current state against the configuration, showing what resources will be created, updated, or destroyed without making any changes. This is the correct command for previewing infrastructure changes before applying them.

Exam trap

HashiCorp Terraform often tests the distinction between `terraform plan` (preview only) and `terraform apply` (executes changes), trapping candidates who confuse the purpose of these commands.

How to eliminate wrong answers

Option A is wrong because `terraform apply` executes the plan and makes actual changes to infrastructure, not just showing what will change. Option C is wrong because `terraform output` displays output values from the state file, not an execution plan of resource changes. Option D is wrong because `terraform destroy` is a specialized apply that destroys all managed resources, not a plan-only preview.

Option E is wrong because `terraform validate` checks configuration syntax and internal consistency, but does not generate an execution plan showing resource changes.

404
Multi-Selectmedium

Which four of the following are valid techniques for reading, generating, or modifying Terraform configuration? (Choose all that apply. There are four correct answers.)

Select 4 answers
.Using the `templatefile` function to render a template with variables from the current configuration.
.Using `terraform console` to evaluate expressions and generate valid HCL configuration output.
.Using `terraform state pull` to retrieve remote state and then using `terraform state mv` to rename a resource address in the local state file before pushing it back.
.Using a `data` source with a `for_each` and a `local` value to dynamically generate resource blocks based on a variable input.
.Using the `jsonencode` function within a `local` value to programmatically construct a JSON string that is then used as part of a resource argument.
.Using `terraform validate` to check configuration syntax and internal consistency before applying changes.

Why this answer

The `templatefile` function is a valid technique for reading and generating configuration because it reads an external template file and renders it with variables from the current Terraform configuration, producing a string that can be used in resource arguments or other expressions. This is a core feature for dynamic configuration generation, such as injecting user data into cloud-init scripts or generating complex configuration files for provisioned resources.

Exam trap

HashiCorp often tests the distinction between commands that modify configuration versus those that only validate or inspect state, so candidates may incorrectly select `terraform validate` or `terraform console` as techniques for generating or modifying configuration when they are purely diagnostic or interactive tools.

405
MCQhard

Refer to the exhibit. A team member receives this error when running terraform apply. What is the most likely cause?

A.The state file is corrupted and needs to be restored from backup.
B.Another user is currently running terraform apply on the same state.
C.The S3 bucket containing the state has been deleted.
D.A previous Terraform process was terminated abruptly, leaving a stale lock.
AnswerD

When a Terraform process terminates unexpectedly, it may fail to release the state lock gracefully, leaving behind a 'stale' lock entry in the backend. This stale lock can contain incomplete or malformed metadata, such as an 'OperationTypeInvalid' value, preventing subsequent Terraform commands from acquiring a new lock. The existing lock is improperly defined and not actively held by a running process, causing the error.

Why this answer

The error shown is Terraform's state-lock error, which occurs when a lock entry exists in the backend (e.g., DynamoDB for S3) but no active process holds it. This typically happens when a previous terraform apply was killed (Ctrl+C, CI runner timeout, network drop) before Terraform could release the lock, leaving a stale lock that blocks new operations.

Exam trap

TF-004 often tests whether candidates can distinguish a stale lock (abrupt termination) from an active lock (concurrent run) — the error message looks identical, so the discriminator is the scenario context, not the error text.

How to eliminate wrong answers

Option A is wrong because a corrupted state file produces parse/JSON errors or resource drift, not a lock-acquisition failure message. Option B is wrong because if another user were actively running apply, the correct remediation would be to wait — but the question asks for the most likely cause of the error, and an abruptly terminated process is the classic trigger for a stale lock. Option C is wrong because a deleted S3 bucket yields a 404/NoSuchBucket error, not a lock conflict.

406
MCQeasy

A team wants to use a networking module from the public Terraform Registry. They need to ensure they always get the latest patch version within the 1.2.x series. Which version constraint should they use in the module block?

A.version = "= 1.2.0"
B.version = ">= 1.2.0, < 2.0.0"
C.version = ">= 1.2.0"
D.version = "~> 1.2"
AnswerD

This "pessimistic" version constraint is the most appropriate choice for allowing only patch-level updates. It specifies that the module version must be greater than or equal to 1.2.0 but strictly less than 1.3.0 (i.e., `1.2.x`). This ensures that the team receives essential bug fixes and security patches (e.g., 1.2.1, 1.2.5) without inadvertently introducing new features or breaking changes that could arise from minor or major version increments, thus balancing stability with necessary maintenance.

Why this answer

Uses the pessimistic version constraint operator `~>`, which in Terraform allows only the rightmost version component to increment. When written as `~> 1.2`, it permits any version `>= 1.2.0` and `< 1.3.0`, effectively locking to the 1.2.x series while allowing patch updates. This matches the requirement to always get the latest patch within 1.2.x without accidentally upgrading to 1.3.0 or 2.0.0.

Exam trap

A common pitfall is confusing `~> 1.2` with `>= 1.2.0, < 2.0.0`. The pessimistic constraint `~> 1.2` restricts updates to patches within the 1.2.x series (`>= 1.2.0, < 1.3.0`), while `>= 1.2.0, < 2.0.0` permits any 1.x version, including minor upgrades. Another subtle trap: `~> 1.2.0` would lock to patches within 1.2.0, but that is not the same as `~> 1.2`.

How to eliminate wrong answers

Option A is wrong because `= 1.2.0` pins the module to exactly version 1.2.0, preventing any patch updates, which contradicts the requirement to always get the latest patch. Option B is wrong because `>= 1.2.0, < 2.0.0` allows minor version upgrades (e.g., 1.3.0, 1.4.0), not just patches within 1.2.x, which is too permissive. Option C is wrong because `>= 1.2.0` permits any version from 1.2.0 upward, including major version 2.0.0 and beyond, which could introduce breaking changes and fails to constrain to the 1.2.x series.

407
MCQeasy

You are a platform engineer at a growing startup. The company currently manages infrastructure manually by SSH-ing into servers to install packages and update configurations. As the team grows, this approach has led to frequent configuration drift, inconsistent environments, and manual errors. Deploying a new environment takes several days and requires detailed runbooks. The CTO has asked you to propose a solution that improves consistency, reduces deployment time, and enables version control of infrastructure. You are evaluating Infrastructure as Code (IaC) tools like Terraform. Which course of action best addresses the CTO's requirements?

A.Improve SSH key management and use configuration management tools like Ansible to apply changes.
B.Migrate all applications to containers and use Kubernetes for orchestration.
C.Adopt Terraform to define all infrastructure as code, store configurations in a Git repository, and use a CI/CD pipeline to apply changes automatically.
D.Create more detailed runbooks and require peer review for all manual changes.
AnswerC

Adopting Terraform for Infrastructure as Code (IaC) allows declarative definition of all infrastructure resources, ensuring consistency and repeatability across environments. Storing these configurations in a Git repository provides robust version control, auditability, and collaborative development, while a CI/CD pipeline automates the application of changes. This integrated approach eliminates manual errors, enforces the desired state, and significantly accelerates infrastructure provisioning and updates.

Why this answer

Terraform directly addresses the CTO's requirements by enabling infrastructure as code (IaC), which ensures consistent, repeatable deployments through declarative configuration files stored in Git for version control. Using a CI/CD pipeline to automatically apply changes eliminates manual SSH errors, reduces deployment time from days to minutes, and prevents configuration drift by enforcing a single source of truth for infrastructure state.

Exam trap

HashiCorp often tests the distinction between configuration management tools (like Ansible) and infrastructure provisioning tools (like Terraform), trapping candidates who confuse managing software on existing servers with defining and versioning the infrastructure itself.

How to eliminate wrong answers

Option A is wrong because improving SSH key management and using Ansible for configuration management still relies on imperative, agent-based execution against existing servers, which does not provide the declarative, version-controlled infrastructure provisioning that Terraform offers; it also does not inherently prevent configuration drift across environments. Option B is wrong because migrating to containers and Kubernetes addresses application deployment and orchestration, not the underlying infrastructure provisioning (e.g., VMs, networks, storage), and introduces unnecessary complexity for a startup that has not yet solved basic infrastructure consistency. Option D is wrong because creating more detailed runbooks and requiring peer review only reduces manual errors marginally but does not automate provisioning, eliminate configuration drift, or enable version control of infrastructure; it perpetuates the slow, error-prone manual process.

408
MCQeasy

After running `terraform plan`, a developer sees the following line in the output: `Plan: 1 to add, 0 to change, 0 to destroy.` What does this indicate?

A.One resource will be destroyed.
B.No changes will be made.
C.One resource will be changed.
D.One resource will be created.
AnswerD

When `terraform plan` output indicates "to add" for a resource, it precisely means that Terraform has detected a new resource block in the configuration that is not yet reflected in the current Terraform state. This action signifies that Terraform intends to provision a brand-new instance of that resource in the target cloud provider or service. Therefore, "to add" directly translates to the creation of one resource.

Why this answer

The output `Plan: 1 to add, 0 to change, 0 to destroy` directly indicates that Terraform will create one new resource, with no modifications or removals. The 'add' count in a Terraform plan corresponds to resources that exist in the configuration but not in the current state file, meaning they will be provisioned during the apply phase.

Exam trap

The trap here is that candidates confuse 'add' with 'change' or 'destroy', failing to recognize that Terraform's plan output uses precise terminology—'add' always means creation, never modification or deletion.

How to eliminate wrong answers

Option A is wrong because '0 to destroy' explicitly means no resources will be removed, not one. Option B is wrong because '1 to add' shows a change will occur, contradicting 'no changes'. Option C is wrong because '0 to change' means no existing resources will be modified; the 'add' count refers to creation, not alteration.

409
MCQhard

A user receives the error shown in the exhibit when running `terraform init`. The user is behind a corporate proxy. Which environment variable should be set to resolve this issue?

A.TF_VAR_proxy=http://proxy:8080
B.AWS_ACCESS_KEY_ID
C.HTTP_PROXY=http://proxy:8080
D.TF_LOG=DEBUG
AnswerC

The `HTTP_PROXY` environment variable is a widely recognized standard that many applications, including Terraform and its providers, respect for configuring an HTTP proxy server. When set, Terraform will route its outgoing HTTP requests through the specified proxy server, enabling it to reach external endpoints that might otherwise be inaccessible due to network restrictions or firewalls. This is the correct and conventional method for configuring a network proxy for Terraform's HTTP communications, directly addressing connectivity errors in environments requiring proxy access.

Why this answer

Terraform uses the standard `HTTP_PROXY` environment variable to route HTTP/HTTPS requests through a corporate proxy when downloading providers and modules. Setting `HTTP_PROXY=http://proxy:8080` instructs Terraform's underlying HTTP client to connect via the specified proxy, resolving the connectivity error during `terraform init`.

Exam trap

HashiCorp often tests the distinction between Terraform-specific environment variables (like `TF_VAR_`) and standard system proxy variables, leading candidates to mistakenly choose `TF_VAR_proxy` as a Terraform-native proxy setting.

How to eliminate wrong answers

Option A is wrong because `TF_VAR_proxy` is not a recognized environment variable in Terraform; the `TF_VAR_` prefix is used to set input variables, not proxy configuration. Option B is wrong because `AWS_ACCESS_KEY_ID` is an AWS credential variable unrelated to proxy settings; it would not fix a network connectivity issue caused by a proxy. Option D is wrong because `TF_LOG=DEBUG` enables verbose logging for debugging but does not configure proxy routing; it only increases log output without addressing the underlying proxy requirement.

410
MCQhard

A team using a remote S3 backend with DynamoDB locking is experiencing frequent 'Error acquiring the state lock' messages in their CI/CD pipeline. The pipeline runs multiple concurrent jobs for different workspaces. What is the most likely cause and solution?

A.The DynamoDB table lacks sufficient read/write capacity; increase it.
B.The same workspace is being used for concurrent runs; use separate workspaces per environment.
C.The pipeline is running too many jobs; increase the lock wait time.
D.The S3 bucket is not versioned; enable versioning.
AnswerB

Terraform workspaces provide isolated state files and, crucially, independent state locks within the same backend configuration. When multiple concurrent `terraform apply` or `terraform plan` operations target the *same* workspace, only one can acquire the state lock at a time, leading to subsequent runs timing out while waiting for the lock to be released. Using distinct workspaces for different environments or concurrent operations ensures each run attempts to acquire a separate lock, preventing contention.

Why this answer

The error 'Error acquiring the state lock' occurs when Terraform cannot obtain a lock on the state file for a specific workspace. In this scenario, the pipeline runs multiple concurrent jobs for different workspaces, but if the same workspace is inadvertently used across concurrent runs, Terraform's DynamoDB-based locking mechanism will prevent simultaneous access to that workspace's state. The solution is to ensure each environment (e.g., dev, staging, prod) uses a separate workspace, avoiding lock contention.

Option B correctly identifies this as the most likely cause and solution.

Exam trap

HashiCorp often tests the misconception that DynamoDB capacity or S3 versioning are the root cause of lock errors, when the real issue is workspace-level contention in concurrent pipelines.

How to eliminate wrong answers

Option A is wrong because DynamoDB read/write capacity is not the issue; the lock error is about contention, not throughput limits, and increasing capacity would not resolve concurrent access to the same lock item. Option C is wrong because increasing the lock wait time (e.g., via the `-lock-timeout` flag) only delays the failure, it does not prevent the underlying conflict of multiple jobs trying to lock the same workspace state. Option D is wrong because S3 bucket versioning is unrelated to state locking; versioning protects against accidental deletion or corruption of state files, but does not affect DynamoDB lock acquisition.

411
MCQmedium

Refer to the exhibit. What does this output indicate?

A.A resource will be modified
B.A resource will be destroyed
C.No changes
D.A resource will be created
AnswerA

The Terraform plan output explicitly states "1 to change," which directly signifies that one existing infrastructure resource, previously managed by Terraform, has detected a configuration drift or an intentional update in the Terraform configuration. This indicates that Terraform will perform an in-place modification of that resource, altering one or more of its attributes without recreating it entirely. This action ensures the resource's state aligns with the desired configuration defined in the current Terraform code.

Why this answer

The output shows a Terraform plan with a tilde (~) prefix next to a resource attribute, which indicates an in-place update. This means Terraform will modify the existing resource without destroying and recreating it, confirming that option A is correct.

Exam trap

The Terraform plan output uses a tilde (~) to indicate an in-place update, meaning the resource will be modified without destruction and recreation. This is commonly confused with the plus (+) for creation or minus (-) for destruction.

How to eliminate wrong answers

Option B is wrong because a tilde (~) indicates modification, not destruction; destruction is shown with a minus (-) sign. Option C is wrong because the presence of a tilde (~) means changes are detected, so 'No changes' is incorrect. Option D is wrong because creation is indicated by a plus (+) sign, not a tilde (~).

412
MCQhard

An organization uses Terraform Cloud to manage infrastructure across multiple teams. They need to enforce that all workspaces use a specific version of Terraform and that no workspace can be deleted accidentally. Which approach meets these requirements without using Sentinel or Terraform Enterprise?

A.Include `required_version` in each workspace's root module and configure workspace locks in the UI.
B.Set `required_providers` with version constraints in a global Terraform file.
C.Use the Terraform Cloud API to write an OPA policy that enforces Terraform version and prevents workspace deletion.
D.Configure version constraints in the Terraform Cloud workspace settings and enable deletion protection.
AnswerD

Terraform Cloud workspaces offer explicit settings to define the exact Terraform CLI version used for all runs within that workspace, ensuring consistent execution environments regardless of the configuration's `required_version`. Additionally, a dedicated "Prevent deletion" safeguard can be enabled directly in the workspace settings. This critical feature protects against accidental or unauthorized removal of the workspace and its associated infrastructure state.

Why this answer

Terraform Cloud allows configuring the Terraform version at the workspace level, ensuring a specific version is used. The 'Prevent deletion' option in workspace settings protects against accidental deletion. While per-workspace, administrators can enforce these settings across workspaces via API or organization defaults.

Options A and B do not prevent deletion; Option C is incorrect because OPA is not natively integrated—Sentinel is the built-in policy engine but is excluded.

Exam trap

Candidates may think that built-in workspace settings are not enough to enforce global compliance, but administrators can enforce these settings via organization defaults or API scripts. OPA integration is often mistakenly assumed to be available natively.

How to eliminate wrong answers

Option A is wrong because `required_version` in a root module only enforces the Terraform version at plan/apply time, not across all workspaces globally, and workspace locks in the UI prevent concurrent operations but do not prevent accidental deletion. Option B is wrong because `required_providers` with version constraints controls provider versions, not the Terraform CLI version, and does not address workspace deletion prevention. Option D is wrong because Terraform Cloud workspace settings allow you to set a Terraform version per workspace, but there is no built-in 'deletion protection' toggle; deletion protection requires Sentinel or OPA policies via the API.

413
Multi-Selecthard

Which THREE files are considered part of the standard module structure?

Select 3 answers
A.main.tf
B.outputs.tf
C.backend.tf
D.terraform.tfvars
E.variables.tf
AnswersA, B, E

The main.tf file is conventionally used to define the primary resources, data sources, and local values that constitute the core functionality of a Terraform module. It serves as the central point for the module's infrastructure provisioning logic, making it an essential component for any standard module. Its presence is fundamental for the module to perform its intended infrastructure creation or management tasks, encapsulating the module's primary purpose.

Why this answer

`main.tf` is the primary entry point for defining the core resources and data sources in a Terraform module. It is one of the three mandatory files (along with `variables.tf` and `outputs.tf`) that constitute the standard module structure, as specified by HashiCorp's module best practices.

Exam trap

HashiCorp often tests the distinction between files that are part of the standard module structure versus files that are commonly used but not mandatory, such as `backend.tf` or `terraform.tfvars`, leading candidates to overcount or misidentify required files.

414
Multi-Selectmedium

Which TWO statements about Terraform's handling of input variables are true?

Select 2 answers
A.All variables must be assigned a value before running terraform plan.
B.Variable values cannot be overridden using environment variables.
C.The terraform.tfvars file is automatically loaded by Terraform.
D.Default values for variables can only be set using a .tfvars file.
E.Variables can be declared in a .tf file using the 'variable' block.
AnswersC, E

Terraform automatically loads terraform.tfvars from the working directory without any explicit flag, alongside terraform.tfvars.json and *.auto.tfvars. This automatic loading removes the need to pass -var-file manually, satisfying the stem's requirement for a true statement about input variable handling.

Why this answer

Option C is correct because Terraform automatically loads a file named terraform.tfvars (or terraform.tfvars.json) from the current working directory when running commands like terraform plan and terraform apply, without requiring an explicit -var-file flag. Option E is correct because input variables are declared in configuration files using the variable block, e.g. variable "region" { type = string }, which defines the variable's name, type, and optional default. Option A is false because variables with a default value, or those not referenced in the configuration, do not need to be assigned before terraform plan; only variables lacking a default and actually used must be supplied.

Option B is false because Terraform does read environment variables prefixed with TF_VAR_ (e.g. TF_VAR_region) to assign variable values. Option D is false because default values are set with the default argument inside the variable block, not via a .tfvars file, which is instead used to assign values at runtime.

Exam trap

TF-004 often tests the misconception that all variables must be assigned before plan, or that defaults can only come from .tfvars files, confusing declaration syntax with value assignment mechanisms.

415
Multi-Selecteasy

Which TWO are benefits of using Terraform modules?

Select 2 answers
A.Encapsulation of complexity, providing a clean interface.
B.Faster execution of terraform plan and apply.
C.Reusability of infrastructure configurations across projects.
D.Reduction in state file size.
E.Enhanced security by automatically encrypting state files.
AnswersA, C

Terraform modules encapsulate a set of related resources, abstracting away their intricate configurations and interdependencies. This allows users to interact with a complex infrastructure pattern through a simplified interface defined by input variables and output values. By hiding the underlying implementation details, modules reduce cognitive load and potential errors for consumers, promoting clarity and maintainability in larger configurations.

Why this answer

Terraform modules encapsulate complex infrastructure logic into a single, reusable abstraction. By defining input variables and output values, modules provide a clean interface that hides internal resource configurations, making configurations easier to manage and maintain.

Exam trap

HashiCorp often tests the misconception that modules improve performance or security directly, when in fact their primary benefits are encapsulation and reusability, not execution speed or automatic encryption.

416
MCQeasy

A DevOps team is using Terraform Cloud to manage infrastructure. They want to integrate Terraform into their CI/CD pipeline by triggering runs programmatically. Which approach should they use to invoke a Terraform run from an external system?

A.Use the Terraform Cloud API to trigger a run.
B.Set up a webhook from the VCS provider to trigger runs.
C.Configure a remote backend to automatically run apply.
D.Execute 'terraform apply -auto-approve' in the CI pipeline.
AnswerA

This is the correct method for programmatic interaction with Terraform Cloud. The Terraform Cloud API provides specific endpoints to create, manage, and trigger runs for designated workspaces, enabling seamless integration with external systems like CI/CD pipelines, custom scripts, or other automation tools. This approach allows for precise control over the run lifecycle, including dynamic variable overrides and explicit plan/apply actions, without requiring direct VCS commits.

Why this answer

The Terraform Cloud API provides a programmatic endpoint to trigger runs, allowing external CI/CD systems to initiate Terraform operations without manual intervention. This is the correct approach because it directly invokes a run with full control over variables, configuration versions, and apply strategies, aligning with the requirement to integrate Terraform into a CI/CD pipeline programmatically.

Exam trap

HashiCorp often tests the distinction between event-driven triggers (VCS webhooks) and programmatic API calls, where candidates mistakenly choose webhooks because they seem 'automated,' but the question explicitly requires programmatic invocation from an external system, not a VCS event.

How to eliminate wrong answers

Option B is wrong because setting up a webhook from the VCS provider triggers runs automatically on code changes, not programmatically from an external CI/CD system; it is event-driven, not API-driven. Option C is wrong because configuring a remote backend does not trigger runs—it only stores state remotely and enables remote execution, but the run must be initiated separately. Option D is wrong because executing 'terraform apply -auto-approve' in the CI pipeline is a local CLI command that bypasses Terraform Cloud's run management, state locking, and policy checks, and it does not integrate with Terraform Cloud's API or remote execution capabilities.

417
MCQhard

A team uses Terraform with a remote backend that stores state in Azure Storage. A developer runs terraform apply and receives an error: 'Error refreshing state: state data in Azure Blob does not have expected content.' What is the most likely cause?

A.The Azure Storage account access key has expired.
B.The blob name contains uppercase letters.
C.The Terraform version is incompatible with the backend.
D.The state file was manually edited.
AnswerD

Manually editing a Terraform state file directly introduces a high risk of corrupting its intricate JSON structure. Even minor syntax errors, like a missing comma, an unclosed bracket, or invalid data types, will cause Terraform's strict JSON parser to fail. When Terraform encounters such malformed content, it cannot interpret the file as valid state data, leading directly to an 'unexpected content' or parsing error.

Why this answer

The error 'state data in Azure Blob does not have expected content' indicates that Terraform's internal consistency check failed when reading the state file. This typically occurs when the state file has been manually edited outside of Terraform, corrupting its JSON structure or checksum. Terraform expects the state to be in a specific format and will reject any blob content that does not match its expected schema or hash.

Exam trap

A common mistake is to confuse authentication/authorization errors (like expired access keys) with state integrity errors. The error message specifically indicates a content validation failure, not a permission issue.

How to eliminate wrong answers

Option A is wrong because an expired storage account access key would result in an authentication error (e.g., '403 Forbidden' or 'Storage authentication failed'), not a content validation error. Option B is wrong because Azure Blob Storage is case-insensitive for blob names, and Terraform normalizes blob names to lowercase; uppercase letters would not cause a content mismatch error. Option C is wrong because version incompatibility between Terraform and the backend typically produces a 'backend initialization' or 'unsupported protocol version' error, not a state content validation error.

418
MCQhard

A team has an existing S3 bucket created outside Terraform. They want to manage it with Terraform by importing its state. Which of the following is the correct sequence of commands to read the bucket's configuration and avoid drift?

A.Run terraform refresh, then terraform state pull to generate configuration.
B.Run terraform plan, note the resource address, then run terraform import.
C.Run terraform import, then terraform state show to generate configuration.
D.Write a minimal resource configuration, run terraform import, then terraform plan, then adjust configuration to match state.
AnswerD

Writing a minimal resource block first gives Terraform a matching address to import into; terraform import then populates state from the real bucket, and terraform plan reveals differences, which you reconcile by editing configuration until it matches state, eliminating drift.

Why this answer

Importing an existing S3 bucket into Terraform requires first writing a minimal resource configuration (e.g., `resource "aws_s3_bucket" "example" { bucket = "existing-bucket-name" }`), then running `terraform import` to link the real-world bucket to the state file. After import, running `terraform plan` reveals any configuration-to-state mismatches, allowing you to adjust the resource block (e.g., adding `acl`, `versioning`, or `tags`) to match the actual bucket configuration, thereby avoiding drift. This workflow ensures the Terraform configuration accurately reflects the existing infrastructure before making changes.

Exam trap

A common misconception is that `terraform import` automatically generates configuration files, when in reality it only populates the state, requiring manual configuration writing and iterative `plan` adjustments to avoid drift.

How to eliminate wrong answers

Option A is wrong because `terraform refresh` updates the state file but does not generate or write Terraform configuration; it only syncs state with real-world resources, leaving the user without a `.tf` file to manage. Option B is wrong because `terraform plan` before import will fail or produce incomplete results since the resource is not yet in the state file; the correct order is to import first, then plan. Option C is wrong because `terraform state show` displays the state attributes of an imported resource but does not generate HCL configuration; it outputs JSON or text, not a `.tf` file that can be reused.

419
MCQhard

A developer runs terraform plan and sees a large number of resources will be destroyed. They suspect the state file is corrupted. They have a recent backup of the state file. Which command can help recover the previous state from the backup?

A.terraform state push
B.No command can recover; they must re-import all resources.
C.terraform state rm
D.terraform state pull
AnswerA

When a Terraform state file becomes corrupted or is accidentally deleted, and a valid backup of the state file exists locally, `terraform state push` is the command used to upload this backup to the configured remote backend. This action overwrites the current (potentially invalid or missing) state in the backend with the provided backup, effectively restoring the infrastructure's known state. This allows subsequent `terraform plan` and `apply` operations to correctly reflect the deployed resources.

Why this answer

The `terraform state push` command is used to manually upload a local state file to the remote backend, overwriting the current remote state. In this scenario, the developer can use a recent backup of the state file and run `terraform state push` to restore the previous state, effectively recovering from the corruption. This command directly replaces the remote state with the specified local file, allowing Terraform to revert to the known good state.

Exam trap

The trap here is that candidates often confuse `terraform state push` with `terraform state pull`, assuming that pulling a backup file is the recovery action, but only `push` can overwrite the remote state with a local backup.

How to eliminate wrong answers

Option B is wrong because Terraform provides state management commands to recover from backups without requiring re-importing all resources, which would be time-consuming and error-prone. Option C is wrong because `terraform state rm` is used to remove specific resources from the state file, not to restore a previous state from a backup. Option D is wrong because `terraform state pull` downloads the current remote state to a local file; it does not push a backup back into the remote backend.

420
MCQhard

An organization uses Terraform with remote state stored in S3 and DynamoDB for state locking. During a plan, they receive the error: 'Error acquiring the state lock: ConditionalCheckFailedException: The conditional request failed'. What is the most likely cause?

A.The state file in S3 is corrupted.
B.The DynamoDB table is not configured with a primary key named LockID.
C.The S3 bucket does not have versioning enabled.
D.Another Terraform process is currently running and holds the state lock.
AnswerD

DynamoDB state locking uses a conditional write on the lock item. ConditionalCheckFailedException means the lock item already exists and its condition was not met, which occurs when another Terraform process holds the lock and has not yet released it.

Why this answer

The error 'ConditionalCheckFailedException' occurs when DynamoDB's conditional put operation fails, which happens when a lock item already exists in the DynamoDB table. This indicates another Terraform process currently holds the state lock, preventing concurrent operations. Terraform uses DynamoDB's conditional writes to ensure only one process can acquire the lock at a time.

Exam trap

A common pitfall in Terraform exams is confusing S3 state file corruption with DynamoDB state lock contention. The ConditionalCheckFailedException specifically indicates that another process holds the lock, not that the state file is damaged.

How to eliminate wrong answers

Option A is wrong because a corrupted state file in S3 would cause a different error, such as 'Error loading state: JSON syntax error' or 'Failed to read state file', not a DynamoDB conditional check failure. Option B is wrong because if the DynamoDB table lacked a primary key named LockID, Terraform would fail during initialization with an error like 'Error configuring the backend' or 'DynamoDB table does not have a primary key attribute named LockID', not during a plan. Option C is wrong because S3 bucket versioning is not required for state locking; it is used for state file versioning and recovery, and its absence would not cause a DynamoDB conditional check failure.

421
MCQhard

A company uses Terraform to manage infrastructure across dev, staging, and production environments. They use Terraform workspaces to separate state files. The backend is configured with an S3 bucket for state storage and a DynamoDB table for state locking. Recently, the team has grown from 2 to 10 developers, and they frequently encounter the error: 'Error acquiring the state lock' when running terraform apply in quick succession. The error message includes: 'Lock Info: ID: ... Operation: Apply. Who: user@company.com. Version: 1.0.0. Created: ...' The error occurs intermittently, especially during peak deployment times. The DynamoDB table is configured with 5 read and 5 write capacity units. The team's current workflow involves multiple developers running apply on different workspaces simultaneously. Which course of action should the team take to minimize state locking errors?

A.Disable state locking to eliminate the error.
B.Increase the DynamoDB table's write capacity units to a higher value.
C.Use a different backend that does not support locking, such as local state.
D.Implement a pre-apply hook that checks if the state is already locked and waits.
AnswerB

Terraform's S3 backend utilizes a DynamoDB table for state locking, where a lock is acquired by writing a unique item to this table. Insufficient write capacity units (WCUs) on the DynamoDB table can cause these lock acquisition attempts to be throttled or fail, especially under high concurrency from multiple developers. Increasing the WCUs ensures that DynamoDB can handle the required throughput for lock writes and updates, thereby reducing throttling errors and allowing successful lock acquisition.

Why this answer

The intermittent 'Error acquiring the state lock' during peak deployment times points to DynamoDB throttling, not a fundamental locking problem. With 10 developers running applies across workspaces simultaneously, the 5 WCU provisioned on the lock table is insufficient to handle the burst of conditional writes used to acquire and release locks. Increasing the write capacity units (or switching to on-demand mode) allows DynamoDB to absorb the concurrent lock operations without throttling, which is what surfaces as a lock acquisition failure in Terraform.

Exam trap

The trap here is assuming any 'state lock' error means a stale lock or a locking design flaw, when in fact DynamoDB capacity exhaustion is the far more common root cause in growing teams.

How to eliminate wrong answers

Option A is wrong because disabling state locking removes the safety mechanism that prevents two developers from corrupting the same state file concurrently — it trades a transient error for potential state corruption. Option C is wrong because local state eliminates remote collaboration entirely and provides no locking at all, which is worse for a 10-developer team using shared workspaces. Option D is wrong because a pre-apply hook that polls for lock status does not address the underlying DynamoDB throttling; it just adds latency and still fails when the table cannot service the conditional write.

422
MCQmedium

A platform team currently provisions servers by filing tickets that an operations group fulfills manually over several days. Leadership wants developers to describe the desired end state of that infrastructure in version-controlled files so the tooling itself figures out which resources to create, modify, or remove. Which characteristic of Terraform directly supports this goal?

A.Terraform is declarative, so you define the desired end state and it computes the actions needed to reach it.
B.Terraform stores credentials in the configuration so provisioning runs unattended.
C.Terraform applies changes through a configuration management agent installed on each managed host.
D.Terraform is procedural, so engineers write ordered scripts that call each provider API in sequence.
AnswerA

Terraform's declarative model means configuration expresses the intended end state rather than the sequence of API calls, and the core engine builds a dependency graph and diffs current state against desired state to decide what to create, update, or destroy. That is exactly what removes the manual ticket-driven step-by-step provisioning described here.

Why this answer

The team needs files that describe the intended end state of infrastructure rather than a manual sequence of provisioning steps. A declarative configuration language fits that need because Terraform compares desired state with recorded state, builds a dependency graph, and produces an execution plan of create, update, and destroy actions. Procedural scripting, embedded credentials, and host-installed agents do not deliver that outcome.

Exam trap

The trap here is assuming Terraform executes configuration top-to-bottom like a script, when ordering actually comes from the dependency graph derived from references.

423
Multi-Selectmedium

Which THREE are part of Terraform's core workflow? (Choose three.)

Select 3 answers
A.Apply
B.Import
C.Plan
D.Destroy
E.Write
AnswersA, C, E

The "Apply" step, executed via `terraform apply`, is the critical phase where Terraform takes the execution plan generated during the `plan` step and provisions, updates, or deletes real infrastructure resources in the target cloud or on-premises environment. It prompts for user confirmation by default, ensuring that the proposed changes are reviewed before any actual modifications are made to the infrastructure. This action directly reconciles the desired state defined in configuration with the actual infrastructure, updating the Terraform state file upon successful completion.

Why this answer

Terraform's documented core workflow consists of three steps: Write, Plan, and Apply. Option E (Write) is correct because it is the first phase, where you author infrastructure as code in HashiCorp Configuration Language (HCL) in .tf files. Option C (Plan) is correct because it is the second phase, where `terraform plan` produces an execution plan showing the actions Terraform will take to reach the desired state.

Option A (Apply) is correct because it is the third phase, where `terraform apply` executes the planned changes to provision or modify real infrastructure. Option B (Import) is not part of the core workflow; `terraform import` is a supplementary command used to bring existing resources under Terraform management. Option D (Destroy) is not one of the three core workflow phases either; `terraform destroy` is a convenience command that applies a plan to remove all managed infrastructure, but it is not counted among Write, Plan, and Apply.

Exam trap

The exam often tests the distinction between the core workflow (write, plan, apply) and auxiliary commands like import or destroy, so the trap is that candidates may incorrectly include import or destroy as part of the core workflow because they are common Terraform operations.

424
MCQmedium

A team uses remote state stored in an S3 bucket with DynamoDB locking. A developer wants to read the current state outputs locally without making changes. Which command should they use?

A.terraform output
B.terraform state pull
C.terraform console
D.terraform plan
AnswerA

terraform output is the most appropriate command for retrieving the values of defined outputs from a Terraform state file, including remote state. This command specifically queries the state for output values without requiring a state lock, making it efficient for read-only access. It is ideal when a team needs to quickly access specific resource attributes or computed values exposed as outputs by the configuration, without modifying the infrastructure or acquiring exclusive access to the state.

Why this answer

The `terraform output` command retrieves and displays the values of output variables from the current state file. When using remote state with S3 and DynamoDB locking, this command reads the state from the backend without acquiring a lock or modifying the state, making it the safe, read-only option for viewing outputs.

Exam trap

The exam often tests the distinction between read-only commands (`terraform output`) and commands that modify or lock state (`terraform state pull`, `terraform plan`), trapping candidates who assume any state-reading command is safe for concurrent use.

How to eliminate wrong answers

Option B is wrong because `terraform state pull` downloads the entire raw state file from the remote backend, which is intended for debugging or manual inspection and can be disruptive if used carelessly; it also requires a lock to be acquired. Option C is wrong because `terraform console` opens an interactive shell for evaluating expressions against the current state, but it is not a simple read-only output command and is overkill for just viewing outputs. Option D is wrong because `terraform plan` creates an execution plan that compares the current state with the configuration, potentially triggering a state refresh and lock acquisition, and it is not designed solely for reading outputs.

425
MCQeasy

A team uses the backend configuration above. What is the primary benefit of storing state remotely in S3?

A.Automatic encryption of state files
B.Reducing the number of API calls to AWS
C.Enabling state sharing and locking across the team
D.Faster Terraform execution times
AnswerC

The paramount benefit of a remote backend is enabling seamless collaboration among multiple team members by centralizing the Terraform state file in a shared, persistent location. This ensures everyone operates against the same authoritative infrastructure definition. Furthermore, remote backends provide crucial state locking mechanisms, which prevent concurrent `terraform apply` operations from simultaneously modifying and potentially corrupting the state file, thereby maintaining state integrity and consistency.

Why this answer

Storing Terraform state remotely in S3 is the standard practice for team collaboration because it allows multiple team members to access and modify the same state file, preventing conflicts. Combined with DynamoDB for state locking, it ensures that only one person runs `terraform apply` at a time, avoiding race conditions and state corruption. This is the primary benefit over local state storage, which is single-user by design.

Exam trap

HashiCorp often tests the misconception that remote state is about performance (faster execution) or security (automatic encryption), when the actual core purpose is enabling safe, concurrent team collaboration through state sharing and locking.

How to eliminate wrong answers

Option A is wrong because S3 does not automatically encrypt state files by default; server-side encryption (SSE-S3 or SSE-KMS) must be explicitly configured in the backend block or bucket policy. Option B is wrong because storing state remotely in S3 does not reduce API calls to AWS; in fact, it may increase them due to state retrieval and locking operations. Option D is wrong because remote state storage typically increases execution time due to network latency for downloading/uploading the state file, not faster execution.

426
MCQhard

You are a DevOps engineer at a company that manages infrastructure for multiple environments (dev, staging, prod) using Terraform. The team has created a reusable module for deploying an AWS ECS Fargate service. The module accepts variables for environment name, container image tag, and desired count. The module is stored in a private Git repository. The root configurations for each environment are stored in separate directories, each with its own backend configuration. Recently, a developer added a new feature to the module that requires a new variable 'enable_xray' (boolean, default false). After updating the module source to point to the new commit, the developer runs 'terraform init' and 'terraform plan' in the dev environment. The plan shows that the ECS service will be updated, but the output does not show any changes related to X-Ray. The developer expected that setting 'enable_xray = true' in the dev root module would enable X-Ray tracing. However, the plan shows no changes to the task definition. What is the most likely cause?

A.The module source was not updated correctly; it still points to the old commit.
B.The developer forgot to run 'terraform init' after changing the module source.
C.The variable 'enable_xray' is not declared in the module's variables.tf file.
D.The module does not reference the 'enable_xray' variable in any resource, so setting it has no effect.
AnswerD

For a variable to influence the infrastructure managed by Terraform, it must be actively referenced within the module's resource configurations, data sources, or outputs. In this scenario, while 'enable_xray' was declared and passed a value, no resource block or data source within the module's implementation actually uses 'var.enable_xray' to conditionally create, modify, or configure any infrastructure component. Consequently, changing the variable's value has no effect on the desired state of any managed object, leading 'terraform plan' to correctly report "no changes to infrastructure."

Why this answer

The `enable_xray` variable, even when set to `true` in the root module, will not cause any changes in the plan unless the module's resources actually reference that variable. In Terraform, a variable declared in a module has no effect on infrastructure unless it is used in a resource argument. The developer saw no changes to the task definition because the module's code likely does not include a condition or argument that uses `enable_xray` to enable X-Ray tracing on the ECS task definition.

Exam trap

The trap here is that candidates assume declaring a variable and setting its value automatically triggers infrastructure changes, but Terraform only applies changes when the variable is actually consumed by a resource argument.

How to eliminate wrong answers

Option A is wrong because if the module source still pointed to the old commit, `terraform init` would not fetch the new variable definition, but the developer already ran `terraform init` and the plan showed an update to the ECS service, indicating the new module version was loaded. Option B is wrong because the developer explicitly ran `terraform init` after updating the module source, so the module was correctly initialized. Option C is wrong because the variable `enable_xray` is declared in the module's `variables.tf` (as stated in the scenario: 'requires a new variable'), and the developer set it to `true` in the root module; the issue is not the declaration but the lack of usage in resources.

427
Multi-Selecteasy

Which TWO of the following are valid methods for importing existing infrastructure into Terraform management? (Choose two.)

Select 2 answers
A.Use terraform apply directly on existing resources
B.Use a third-party tool like Terraformer to generate configuration
C.Use terraform state push to manually add state entries
D.Write configuration for the resource and use terraform import
E.Use terraform import without any prior configuration
AnswersB, D

Using a third-party tool like Terraformer is a valid method because these tools automate the complex process of reverse-engineering existing cloud infrastructure into Terraform HCL configuration files. By generating the necessary `resource` blocks, they provide the essential configuration required for Terraform to manage existing resources. This significantly streamlines the adoption of Terraform for existing environments, often also facilitating the population of the Terraform state.

Why this answer

Option B is correct because Terraformer is a real third-party tool that reads existing cloud infrastructure via provider APIs and generates both Terraform configuration files and matching state, letting you bring resources under management without hand-writing everything. Option D is correct because the canonical native workflow is to write the resource block in your configuration first, then run terraform import <address> <resource-id> so Terraform maps the existing object into state and subsequent plans reconcile it. Option A is wrong because terraform apply only creates or updates resources described in configuration and state; it cannot discover or adopt pre-existing infrastructure.

Option C is wrong because terraform state push writes a state file you supply, which is a state-manipulation operation, not a supported import mechanism, and it does not generate configuration. Option E is wrong because terraform import requires the target resource address to already exist in configuration (in modern Terraform), so importing without prior configuration fails or leaves the resource unmanaged in config.

Exam trap

TF-004 often tests whether candidates know that terraform import requires pre-existing configuration and that terraform apply cannot adopt resources — the misconception is that apply or state push can import.

428
Multi-Selectmedium

Which THREE of the following are characteristics of Terraform state? (Choose three.)

Select 3 answers
A.It can be stored remotely to enable team collaboration
B.It contains the entire Terraform configuration
C.It maps real-world resources to your configuration
D.It includes metadata such as resource dependencies
E.It stores the provider source code
AnswersA, C, D

Terraform state can be stored remotely using various backend configurations, such as Amazon S3, Azure Blob Storage, Google Cloud Storage, or HashiCorp Terraform Cloud. This remote storage is crucial for team collaboration, allowing multiple users to safely work on the same infrastructure by providing a shared source of truth. Remote state backends often include state locking mechanisms to prevent concurrent operations from corrupting the state file, ensuring consistency and preventing race conditions.

Why this answer

Terraform state is a critical artifact that maps the resources defined in your configuration to the real-world objects they represent, which is exactly what option C describes and is why it is correct. Option D is also correct because the state file stores metadata about resources, including dependency relationships between them, which Terraform uses to determine the correct order of operations during plan and apply. Option A is correct because state can be configured with a remote backend (such as S3, Terraform Cloud, or Consul) to enable team collaboration, locking, and shared access to the same state.

Option B is incorrect because the state file does not contain the entire Terraform configuration; the configuration lives in .tf files, while state only records the mapping and metadata of managed resources. Option E is incorrect because provider source code is not stored in state; providers are downloaded and installed separately via terraform init into the plugin cache or .terraform directory.

Exam trap

The Terraform exam often tests the misconception that state stores the entire configuration or provider code, but state only holds the mapping of resources to real-world objects and metadata like dependencies, not the configuration itself or provider binaries.

429
MCQmedium

A team uses a remote state backend with partial configuration. They have a `backend` block with only the `bucket` attribute, and the rest of the backend configuration is provided via CLI during `terraform init`. Which of the following best describes the purpose of partial configuration?

A.It reduces the number of files needed for configuration.
B.It is required when using Terraform Cloud.
C.It enables state locking.
D.It allows sensitive backend configuration to be provided dynamically, avoiding hardcoding.
AnswerD

The primary advantage of partial backend configuration is its ability to facilitate the dynamic provision of sensitive backend configuration attributes. This approach allows critical credentials, such as access keys, secret tokens, or database connection strings, to be supplied at runtime via CLI arguments or environment variables. Consequently, these sensitive details are prevented from being hardcoded directly into Terraform configuration files and committed to version control, significantly enhancing security posture.

Why this answer

Partial configuration in Terraform remote state backends allows you to split backend settings between the `backend` block in your configuration and dynamic inputs provided at `terraform init` time. This is especially useful for sensitive values like access keys or secret tokens, which can be supplied via CLI flags, environment variables, or interactive prompts, thereby avoiding hardcoding them in version-controlled files. Option D correctly identifies this primary purpose of enhancing security and flexibility.

Exam trap

A common misconception is that partial configuration is primarily for reducing file count or enabling state locking, when in fact its core purpose is to allow dynamic, secure injection of sensitive backend parameters without hardcoding.

How to eliminate wrong answers

Option A is wrong because partial configuration does not reduce the number of files; it merely separates backend settings across different input sources, and you still need at least one configuration file. Option B is wrong because partial configuration is optional when using Terraform Cloud; Terraform Cloud can also use full configuration or environment variables, and it is not a requirement. Option C is wrong because state locking is enabled by the backend type (e.g., S3 with DynamoDB) and is independent of whether the backend configuration is partial or complete; partial configuration does not inherently enable or disable locking.

430
MCQhard

A company manages multiple microservices across AWS accounts. Each service has its own Terraform configuration and state file stored in a shared S3 bucket. The team uses `terraform_remote_state` data sources to read outputs from other services' state files. A service team recently changed the output structure in their state, breaking the `terraform_remote_state` calls from other services. The affected services now show errors during plan. What is the best practice to avoid such cross-service dependency issues?

A.Publish service outputs to a dedicated data store (e.g., AWS SSM Parameter Store or Consul) and have other services consume those values instead of reading state directly
B.Use versioning on the S3 bucket and revert to a previous state version
C.Lock the state files and require approval for any changes
D.Store outputs in a configuration management database and read from there
AnswerA

Publishing service outputs to a dedicated data store like AWS SSM Parameter Store or HashiCorp Consul provides a robust mechanism for inter-service communication. This approach effectively decouples Terraform configurations, preventing direct dependencies on another service's remote state file, which can be fragile and prone to breaking changes. By consuming values from a stable, versioned API, services can reliably access necessary parameters without needing direct read access to potentially sensitive or rapidly evolving state files. This promotes a more resilient and scalable microservices architecture.

Why this answer

The best practice is to decouple services by using a dedicated data store (e.g., AWS SSM Parameter Store or Consul) as a service registry or contract. This avoids tight coupling to the internal state representation of another service. Option A correctly implements this pattern.

Option D (CMDB) is overly generic and not specifically designed for Terraform state outputs. Options B and C are reactive measures, not proactive best practices.

431
MCQmedium

A team uses Terraform to manage multiple environments (dev, staging, prod) with a shared networking module. The module defines a variable 'cidr_block' with no default. In the root module, they have a file dev.tfvars containing 'cidr_block = "10.0.0.0/16"'. When running 'terraform plan' while in the dev workspace, they receive: 'Error: No value for required variable cidr_block'. They have already run 'terraform init' and confirmed the workspace is 'dev'. What is the most likely cause and correct action?

A.They forgot to include the -var-file flag; add -var-file='dev.tfvars' to the plan command.
B.The variable is defined in the child module; they need to reference it with module.cidr_block in the root module.
C.The workspace is not selected; run 'terraform workspace select dev' again.
D.The variable must be passed through the module block; they should add a module input assignment.
AnswerA

Terraform has specific conventions for automatically loading variable definition files, which include `terraform.tfvars`, `terraform.tfvars.json`, and any files ending with `*.auto.tfvars` or `*.auto.tfvars.json`. A file named `dev.tfvars` does not adhere to these automatic loading patterns. Therefore, to ensure that the variable definitions within `dev.tfvars` are applied during a `terraform plan` operation, it must be explicitly included using the `-var-file='dev.tfvars'` flag on the command line.

Why this answer

Terraform does not automatically load *.tfvars files unless they are named terraform.tfvars or *.auto.tfvars, or explicitly passed with -var-file. Since dev.tfvars is a custom-named file, the plan command must include -var-file='dev.tfvars' to supply the required variable. Workspace selection alone does not bind a variable file to a workspace.

Exam trap

TF-004 often tests the assumption that selecting a workspace automatically loads a matching .tfvars file — it does not; only terraform.tfvars and *.auto.tfvars load automatically, so custom-named files require -var-file.

How to eliminate wrong answers

Option B is wrong because the error is about a missing value for a root-module variable, not about referencing a child module output; module.cidr_block syntax is for reading module outputs, not for supplying inputs. Option C is wrong because the scenario already confirms the workspace is 'dev' — re-selecting it changes nothing about variable resolution. Option D is wrong because the variable is declared in the root module (the error says 'required variable cidr_block' at plan time), and even if it were a module input, the fix would be to pass a value in the module block, not to add a new assignment that still lacks a source value.

432
MCQeasy

A cloud engineer is preparing to introduce Terraform to a team that currently provisions servers by opening support tickets and waiting for an operations group to build them manually. The engineer needs to explain the fundamental shift in how infrastructure is delivered. Which statement best describes the change that adopting Terraform represents?

A.Infrastructure is provisioned faster because Terraform replaces the cloud provider's API with its own provisioning engine.
B.Infrastructure is described imperatively with shell scripts that run in a fixed sequence on a build server.
C.Infrastructure changes are executed by a centralized operations group using an internal self-service portal.
D.Infrastructure is defined in declarative configuration files that are applied through a consistent, repeatable workflow.
AnswerD

Terraform shifts delivery from manual ticketing to declarative code: engineers write the desired end state, and Terraform plans and applies the API calls needed to reach it. This produces consistent, repeatable results and removes the variability of hand-built servers. It is the defining characteristic of infrastructure as code and directly answers what changes for the team.

Why this answer

Infrastructure as code replaces manual provisioning with declarative configuration applied through a consistent workflow. Engineers commit desired state, and Terraform calculates and executes the necessary provider API calls, yielding repeatable results. The other choices either misstate how Terraform interacts with cloud APIs, restate the old centralized model, or describe imperative scripting rather than the declarative approach Terraform uses.

Exam trap

The trap here is conflating Terraform's automation with an imperative scripting approach, when Terraform is declarative and reconciles desired state.

433
MCQhard

A platform team manages a large Terraform codebase with hundreds of resources across multiple environments (dev, staging, prod). They use terraform workspaces to manage environment-specific state files. Recently, an engineer made changes to the production workspace but forgot to switch from the dev workspace before applying. The apply was successful, but now the production resources are in an inconsistent state. The team wants to recover the production state to match the actual infrastructure. The previous state file for production was backed up in an S3 bucket before the accidental apply. What is the best course of action?

A.Use terraform state mv to correct the state entries by mapping resources from the backup to the current state
B.Use terraform import to manually import each production resource based on the backup state
C.Use terraform workspace select prod then terraform apply with the backup state file
D.Use terraform state push with the backup state file to overwrite the current state
AnswerD

terraform state push overwrites the current state file with the supplied backup, restoring production's recorded resource mappings to match reality. Because the accidental apply occurred in the dev workspace, the production state was corrupted; pushing the S3 backup realigns state with actual infrastructure before further operations.

Why this answer

`terraform state push` directly overwrites the current state file in the workspace with a provided state file. Since the team has a backup of the production state file taken before the accidental apply, pushing that backup restores the state to exactly match the actual infrastructure, assuming no other changes occurred. This is the fastest and most reliable method to recover from an incorrect state overwrite, as it bypasses any reconciliation logic and replaces the state wholesale.

Exam trap

A common trap in Terraform exams is the misconception that `terraform apply` can accept a state file as an argument, when in fact `terraform apply` always uses the workspace's current state, and state manipulation requires dedicated commands like `state push` or `state pull`.

How to eliminate wrong answers

Option A is wrong because `terraform state mv` is used to rename or move resources within the state, not to restore an entire state file from a backup; it would require manually mapping every resource and is error-prone for hundreds of resources. Option B is wrong because `terraform import` is designed to bring existing infrastructure into state, but it would require re-importing each resource individually based on the backup, which is inefficient and risks drift if the backup state is not perfectly aligned with current infrastructure. Option C is wrong because `terraform apply` with a backup state file is not a valid operation; `terraform apply` reads the current state from the workspace, not a specified file, and applying with a backup would attempt to modify infrastructure, not restore state.

434
MCQeasy

A developer wants to use Terraform in a CI pipeline where the pipeline runs on pull requests. They need to preview infrastructure changes without applying them. Which command should be used?

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

The `terraform plan` command generates an execution plan, detailing the actions Terraform will perform to reach the desired state defined in the configuration files. It compares the current state (from the state file) with the desired state (from the configuration) and the actual infrastructure, providing a preview of all proposed infrastructure changes (creations, updates, or destructions) without actually making them. This makes it ideal for CI/CD pipelines to review changes before approval.

Why this answer

`terraform plan` creates an execution plan that shows what actions Terraform will take to change infrastructure to match the configuration, without actually applying any changes. This is the standard command for previewing infrastructure changes in a CI pipeline triggered by pull requests, enabling developers to review proposed modifications before merging.

Exam trap

HashiCorp often tests the distinction between validation and planning, so the trap here is that candidates confuse `terraform validate` (syntax check) with `terraform plan` (infrastructure preview), assuming validation alone is sufficient to preview changes.

How to eliminate wrong answers

Option B is wrong because `terraform validate` checks only the syntactic correctness and internal consistency of Terraform configuration files, not the actual state or planned changes against real infrastructure. Option C is wrong because `terraform init` initializes the working directory by downloading providers and modules, but does not generate any preview of infrastructure changes. Option D is wrong because `terraform apply` executes the planned changes and modifies real infrastructure, which is the opposite of a preview-only operation and should not be used in a pull request pipeline without prior approval.

Page 5

Page 6 of 6

All pages