Courseiva

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

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

Page 5

Page 6 of 6

376
MCQeasy

A junior DevOps engineer is learning about Infrastructure as Code (IaC) and asks why Terraform is preferred over manual configuration in cloud consoles. Which of the following is the primary benefit of using Terraform for infrastructure management?

A.It can only manage infrastructure on major cloud providers like AWS, Azure, and GCP.
B.It automatically rolls back any failed infrastructure changes.
C.It enables version-controlled, repeatable, and automated infrastructure provisioning.
D.It uses an imperative approach where you specify exact commands to execute.
AnswerC

Infrastructure as Code (IaC), as implemented by Terraform, fundamentally enables treating infrastructure configurations like application code. This allows for storing configurations in version control systems (e.g., Git), facilitating change tracking, collaboration, and peer review. The codified nature ensures that infrastructure deployments are repeatable, consistent, and can be fully automated through CI/CD pipelines, significantly reducing manual errors and operational overhead.

Why this answer

Terraform's core value proposition is enabling infrastructure as code (IaC), which allows teams to define infrastructure in declarative configuration files, version control them with Git, and provision consistently across environments. This repeatability and automation eliminate the drift and manual errors inherent in clicking through cloud consoles, making infrastructure management auditable, collaborative, and scalable.

Exam trap

The trap here is that candidates confuse declarative (Terraform) with imperative (e.g., Ansible or shell scripts) approaches, or assume Terraform's state management includes automatic rollback, when in fact it only provides a plan and requires explicit user action to revert changes.

How to eliminate wrong answers

Option A is wrong because Terraform is not limited to major cloud providers; it uses a plugin-based provider architecture that supports hundreds of providers, including on-premises solutions like VMware, OpenStack, and custom APIs via the Terraform Provider SDK. Option B is wrong because Terraform does not automatically roll back failed changes; it creates a state file to track resources and can detect drift, but rollbacks require manual intervention or a separate 'terraform destroy' and re-apply of a previous configuration. Option D is wrong because Terraform uses a declarative approach, not imperative; you define the desired end state in HCL (HashiCorp Configuration Language), and Terraform determines the necessary actions to reach that state, unlike imperative tools that require step-by-step commands.

377
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 plans to destroy resources that are in state but removed from configuration.

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.

378
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.

379
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.

380
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.

381
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.

382
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 allow you to define reusable infrastructure and pass environment-specific variable values. This is the recommended approach for code reuse across environments.

383
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.

384
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.

385
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

quickly retrieves output values from state

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`.

386
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.

387
Drag & Dropmedium

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

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

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

Why this order

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

388
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.

389
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.

390
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

The plan output shows a -/+ next to the ingress rule, indicating that Terraform will destroy the existing rule and create a new one with the updated CIDR block. This replacement occurs because the `cidr_blocks` attribute change for an ingress rule forces resource recreation. Thus, the existing ingress rule is replaced with a new one, matching option A.

391
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.

392
MCQhard

Refer to the exhibit. A user runs terraform init and receives an error about state data content. The state file in S3 has not been manually modified. What is the most likely cause?

A.The S3 bucket policy denies access to the state file.
B.Terraform version mismatch between local and state file.
C.The state file is locked by another process.
D.The state file was written by a different Terraform workspace.
AnswerD

When a state file is written by a different Terraform workspace, the serial number or other internal metadata within the state file may not align with what the currently selected local workspace expects. Terraform uses serial numbers to track the evolution of the state and ensure consistency, preventing operations on an outdated or incorrect view of the infrastructure. A mismatch indicates that the remote state's serial number is different from the one Terraform expects for the current workspace, often due to switching workspaces without proper `terraform workspace select` or external manipulation.

Why this answer

The error indicates that the state file content does not match what Terraform expects. This can happen when the state file has a different serial number (e.g., if another process wrote to it) or if the state file is corrupted. However, since the user hasn't manually modified it, the most likely cause is that the state file was modified by a different Terraform process (perhaps from another workspace or different version) that changed the state structure.

Option D is correct because a conflicting workspace can write state with a different serial, causing the error.

393
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.

394
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.

395
Drag & Dropmedium

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

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

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

Why this order

The correct 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.

396
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.

397
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.

398
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

Using a remote state backend (like Terraform Cloud) ensures state is stored securely and can be accessed by pipeline runs. Local state with .gitignore is not secure or accessible. Terraform import is for adding existing resources, not state storage. terraform state push is used to manually upload state.

399
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

A 'State version conflict' in Terraform Cloud typically occurs when two runs attempt to modify the same state concurrently. Even though Terraform Cloud serializes runs via a queue, a conflict arises if a run completes before another run that started based on an older state version. Terraform Cloud detects that the state has changed externally, resulting in a version conflict.

Missing or incorrect backend configuration (option B) would cause errors like 'backend initialization required' or 'workspace not found', not specifically a state version conflict. Authentication failures (A) yield access denied errors. State size limits (C) produce size-related errors.

Version mismatches (D) cause compatibility warnings.

400
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.

401
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.

402
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.

403
Drag & Dropmedium

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

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

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

Why this order

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

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 lock info shows an operation type "OperationTypeInvalid", which typically occurs when a previous Terraform process was terminated abruptly (e.g., Ctrl+C, crash), leaving the lock in place.

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
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 (~).

411
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.

412
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.

413
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 and any .auto.tfvars files in the root module directory.

Why this answer

Options C and E are correct. Option C is correct because Terraform automatically loads terraform.tfvars and any *.auto.tfvars files in the working directory. Option E is correct because variables are declared using the 'variable' block in .tf files.

Option A is incorrect: variables can have default values and are not required to be assigned before terraform plan. Option B is incorrect: variable values can be overridden using environment variables with the TF_VAR_ prefix. Option D is incorrect: default values are set within the variable block using the default argument, not in .tfvars files.

414
MCQhard

A large enterprise uses Terraform Cloud with remote execution mode to manage infrastructure across multiple AWS accounts. Each environment (dev, staging, prod) has a separate workspace. The security team requires that all changes to production must be approved by a senior engineer before applying. Additionally, developers should be able to plan changes in production to preview the impact, but not apply them. The current setup uses the same Terraform Cloud team membership for all workspaces. When a developer runs a plan in production, the plan succeeds but they are unable to apply. However, the security team notices that the developer can accidentally apply if they quickly approve their own plan via the UI because the workspace is configured with 'Auto Apply' enabled. The security team wants to enforce the approval process without removing the developer's ability to plan. Which combination of changes should be made? (Select only one option.)

A.Keep 'Auto Apply' enabled but restrict the production workspace to only the infrastructure lead's Terraform Cloud account.
B.Use run triggers to promote runs from dev to staging to production, and only the lead can promote to production.
C.Disable 'Auto Apply' on the production workspace and configure team permissions so that developers have 'plan' role and the infrastructure lead has 'write' role.
D.Use VCS branch restrictions to only allow applies from the 'main' branch, and have developers plan from feature branches.
AnswerC

This enforces manual approval and restricts apply permissions.

Why this answer

Disabling 'Auto Apply' on the production workspace ensures that no apply occurs without explicit approval. Configuring team permissions so that developers have the 'plan' role (which allows running plans but not applying) and the infrastructure lead has the 'write' role (which allows applying) enforces the required approval process while preserving the developer's ability to preview changes via plan.

Exam trap

HashiCorp often tests the distinction between run triggers (which automate promotion) and manual approval workflows, leading candidates to incorrectly choose run triggers as a solution for approval enforcement when they actually bypass manual approval.

How to eliminate wrong answers

Option A is wrong because keeping 'Auto Apply' enabled would still allow applies to happen automatically after a plan, bypassing the approval process; restricting to the lead's account does not prevent a developer from triggering a plan that auto-applies. Option B is wrong because run triggers are designed to chain runs between workspaces (e.g., promoting from dev to staging to prod) but do not enforce a manual approval step before applying in production; they automate the promotion, not the approval. Option D is wrong because VCS branch restrictions control which branches can trigger runs, but they do not prevent a developer from applying a plan if they have apply permissions; the developer could still apply from the 'main' branch if they have the appropriate role, and the scenario requires that developers cannot apply at all.

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 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.

419
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

Lock acquisition fails because another process holds the lock.

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.

420
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

Increasing DynamoDB write capacity reduces contention and lock acquisition failures during concurrent applies. Option D (implementing a pre-apply hook) is not standard and could add complexity. Options A and C disable or bypass locking, which is dangerous.

421
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.

422
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.

423
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.

424
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

The typical method is to write configuration and run terraform import. Third-party tools can generate configuration from existing resources. terraform import requires configuration beforehand. terraform state push is not for importing; it pushes a state file. terraform apply would try to create new resources.

425
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.

426
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.

427
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

The error indicates that the required variable 'cidr_block' has no value. Terraform does not automatically load .tfvars files; they must be explicitly specified with the -var-file flag. Since the team is in the 'dev' workspace but did not include '-var-file=dev.tfvars', the variable file is ignored.

Option A correctly fixes this by adding the flag. Option B is incorrect because 'module.cidr_block' is not a valid reference; variables are passed to modules via module block inputs, not by referencing the variable name directly. Option C is incorrect because the workspace is confirmed as 'dev'.

Option D is incorrect because the variable is already defined in the module; the issue is that the .tfvars file is not being loaded, not that the module input is missing.

428
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