Courseiva

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

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

Data quality score: 85/100 — Review before indexing

1 error found across 75 questions. This page is set to noindex until issues are resolved.

Page 4

Page 5 of 6

Page 6
301
MCQhard

A developer runs `terraform apply` and gets the error: 'Error: No configuration files'. What is the most likely cause?

A.The working directory does not contain any `.tf` files
B.The state file is missing
C.The user does not have permissions to read the directory
D.The provider plugin is not installed
E.The backend configuration is incomplete
AnswerA

When `terraform apply` is executed, Terraform expects to find configuration files (ending with `.tf`) in the current working directory. These files define the infrastructure resources, providers, and variables that Terraform needs to manage. Without any `.tf` files, Terraform has no configuration to parse or plan against, leading to an error indicating that no configuration was found or that the directory is empty of Terraform files, preventing any operation.

Why this answer

The error 'No configuration files' occurs when Terraform cannot find any `.tf` files in the current working directory. Terraform requires at least one configuration file with a `.tf` extension to define resources, data sources, or providers. Without these files, Terraform has no instructions to execute, so it fails immediately during the initialization or planning phase.

Exam trap

Candidates often confuse the error for a missing configuration file with a missing state file. The error 'No configuration files' is specific to the absence of .tf files, not state files or permissions.

How to eliminate wrong answers

Option B is wrong because a missing state file does not cause the 'No configuration files' error; state files are separate from configuration files and are only required after configuration is loaded. Option C is wrong because permission issues would typically produce a 'permission denied' error, not a missing configuration files error. Option D is wrong because a missing provider plugin would cause a provider-related error during initialization or planning, not a 'No configuration files' error.

Option E is wrong because an incomplete backend configuration would result in a backend initialization error, not a missing configuration files error.

302
MCQeasy

What file extension is commonly used for Terraform configuration files?

A..json
B..hcl
C..tfstate
D..yaml
E..tf
AnswerE

The `.tf` file extension is the universally recognized and standard convention for Terraform configuration files. These files contain infrastructure definitions written in HashiCorp Configuration Language (HCL), specifying resources, data sources, variables, outputs, and providers. Terraform automatically loads and processes all `.tf` files found within a given directory as a single, cohesive configuration, making this extension essential for project organization and execution.

Why this answer

Terraform uses HashiCorp Configuration Language (HCL) for its configuration files, and the standard file extension for these files is `.tf`. Terraform automatically loads all files ending in `.tf` in a directory as part of its configuration, making `.tf` the primary and required extension for Terraform configuration.

Exam trap

Candidates often confuse the `.tf` extension (configuration) with the `.tfstate` extension (state file).

How to eliminate wrong answers

Option A is wrong because `.json` is used for Terraform configuration in JSON syntax (`.tf.json`), but it is not the common extension for standard HCL-based configuration files. Option B is wrong because `.hcl` is the generic extension for HashiCorp Configuration Language files used by other HashiCorp tools (e.g., Packer, Vault), but Terraform specifically uses `.tf` for its configuration files. Option C is wrong because `.tfstate` is the extension for Terraform state files, which track the current state of managed infrastructure, not configuration files.

Option D is wrong because `.yaml` is not a native Terraform configuration format; Terraform does not support YAML for its primary configuration files.

303
MCQmedium

An engineer is refactoring a monolithic Terraform configuration into reusable modules. One module outputs a list of subnet IDs. Another module needs to use these subnet IDs to create resources. What is the best way to pass this data between modules?

A.Use a Terraform data source in the second module to query the subnets directly.
B.Define the subnet IDs as a variable in the first module and pass them to the second module via a remote state data source.
C.Store the subnet IDs in a local file and use the 'file' function to read them in the second module.
D.Output the subnet IDs from the first module and reference that output as an input variable in the second module's block.
AnswerD

This is the correct pattern: module outputs are consumed as module input variables.

Why this answer

Terraform modules communicate through explicit input and output variables. By outputting the subnet IDs from the first module and then referencing that output as an input variable in the second module's block, you create a clear, versionable, and dependency-aware data flow. This approach avoids hidden dependencies and ensures Terraform can properly graph the resource dependencies for parallel execution.

Exam trap

HashiCorp often tests the misconception that remote state data sources are the only way to pass data between modules, when in fact direct output-to-variable passing is the simplest and most maintainable approach within a single Terraform configuration.

How to eliminate wrong answers

Option A is wrong because using a data source in the second module to query subnets directly reintroduces tight coupling to the underlying infrastructure and bypasses the modular abstraction, defeating the purpose of refactoring into reusable modules. Option B is wrong because defining subnet IDs as a variable in the first module is nonsensical—variables are inputs, not outputs; the correct mechanism is to output the IDs from the first module and then use a remote state data source only if the modules are in separate configurations, but here they are in the same configuration, so direct output-to-variable passing is simpler and more idiomatic. Option C is wrong because storing data in a local file introduces an external, non-versioned artifact that can become stale, breaks Terraform's dependency tracking, and is an anti-pattern for passing runtime data between modules.

304
MCQhard

Refer to the exhibit. A developer runs the commands shown. The Terraform configuration defines a `random_pet` resource. The developer expects the plan to show a new resource to be created, but it says "No changes." What is the most likely reason?

A.The random_pet resource was already created in a previous apply and is still in the state
B.The `-auto-approve` flag prevents showing changes in the plan
C.The `random_pet` resource is not supported by the Terraform version
D.The backend is local, so changes are not persisted across runs
AnswerA

The `terraform apply` command reporting "No changes. Your infrastructure matches the configuration." indicates that all resources defined in the Terraform configuration files are already present in the Terraform state file, and their current attributes align perfectly with the desired state. This means the `random_pet` resource was successfully created during a previous `terraform apply` operation and its existence and configuration are accurately tracked within the state, requiring no further action.

Why this answer

The `random_pet` resource was already created and recorded in the Terraform state file during a previous `terraform apply`. When the developer runs `terraform plan` again without any changes to the configuration, Terraform compares the current state to the configuration and finds no differences, resulting in 'No changes.' The resource already exists in the state, so no new resource is planned.

Exam trap

The trap here is that candidates may assume `random_pet` generates a new value on every plan, but Terraform treats it as a managed resource that only changes when the configuration or state is altered.

How to eliminate wrong answers

Option B is wrong because the `-auto-approve` flag only skips the interactive approval prompt during `terraform apply`; it does not affect whether changes are shown in `terraform plan`. Option C is wrong because `random_pet` is a built-in resource from the `random` provider, which is supported in all modern Terraform versions (0.12+). Option D is wrong because a local backend does persist state across runs (in the `terraform.tfstate` file); changes are not lost between runs, so the 'No changes' result is not due to the backend type.

305
MCQeasy

A developer runs terraform plan and sees that a resource will be destroyed. They want to confirm the exact cause of the destruction before applying. What should they do?

A.Run terraform show after plan.
B.Review the state file directly.
C.Run terraform validate.
D.Run terraform graph.
AnswerA

After running `terraform plan -out=tfplan`, executing `terraform show tfplan` is the definitive method to inspect the proposed changes in detail. This command renders the plan file in a human-readable format, explicitly listing each resource modification, including creations, updates, and destructions. Crucially, for destructive changes, it often indicates the specific attribute modifications that necessitate resource replacement or deletion, providing the "why" behind the planned action.

Why this answer

Running `terraform show` after `terraform plan` displays the plan output in a human-readable format, including the full set of changes (create, update, destroy) and the attributes that triggered them. This allows the developer to inspect the exact reason a resource is marked for destruction, such as a changed required argument or a removed configuration block. It is the standard way to review plan details without applying.

Exam trap

HashiCorp often tests the distinction between commands that inspect the plan (`terraform show`) versus commands that validate syntax (`terraform validate`) or visualize dependencies (`terraform graph`), leading candidates to confuse planning-phase diagnostics with configuration checks.

How to eliminate wrong answers

Option B is wrong because directly reviewing the state file (terraform.tfstate) shows the current state, not the planned changes; it does not reveal why Terraform decided to destroy a resource, only that it exists. Option C is wrong because `terraform validate` checks configuration syntax and internal consistency, not the planned execution or destruction reasons. Option D is wrong because `terraform graph` outputs a dependency graph in DOT format, which visualizes resource relationships but does not explain the specific cause of a planned destruction.

306
MCQmedium

Refer to the exhibit. A Terraform Cloud plan includes an EC2 instance of type 't2.medium'. The team uses Sentinel policies. Which action should they take to proceed?

A.Modify the Sentinel policy to allow t2.medium.
B.Disable the policy check for this run.
C.Change the instance type in the configuration to t2.micro or t2.small.
D.Override the policy in the run using Terraform Cloud UI.
AnswerC

Comply with the policy.

Why this answer

Sentinel policies enforce compliance rules, and if the policy explicitly denies 't2.medium', the team must modify their configuration to use an allowed instance type (e.g., t2.micro or t2.small) to pass the policy check. This aligns with the principle of infrastructure-as-code where policies are immutable guardrails, and the configuration must be adapted to meet them rather than bypassing the policy.

Exam trap

HashiCorp often tests the misconception that Sentinel policies can always be overridden or disabled, but the trap here is that hard-mandatory policies require configuration changes, not workarounds, and candidates must recognize that modifying the policy or bypassing the check violates the governance model.

How to eliminate wrong answers

Option A is wrong because modifying the Sentinel policy to allow t2.medium undermines the purpose of policy-as-code; policies are typically managed by a separate team (e.g., security or compliance) and should not be changed by the team running the plan to accommodate a non-compliant resource. Option B is wrong because disabling the policy check for this run bypasses governance entirely, which defeats the purpose of using Sentinel for continuous compliance and is not a recommended practice in Terraform Cloud workflows. Option D is wrong because overriding the policy in the Terraform Cloud UI is only possible for 'soft-mandatory' policies, not for 'hard-mandatory' ones; if the policy is hard-mandatory, the override option is unavailable, and even if available, it should be used sparingly for exceptions, not as a routine workaround.

307
Multi-Selecthard

Which three of the following are true regarding Terraform state?

Select 3 answers
A.State can be stored in a local file or remotely.
B.State can be manually edited with a text editor without risk.
C.State is required for Terraform to function.
D.State must be stored in a file named terraform.tfstate.
E.State contains resource metadata and dependencies.
AnswersA, C, E

Terraform state can be stored locally in a `terraform.tfstate` file, which is suitable for individual development and testing. For collaborative environments and production deployments, remote state storage is highly recommended. Terraform backends, such as Amazon S3, Azure Storage, or HashiCorp Consul, enable durable, shared, and versioned state management, often including state locking to prevent concurrent modifications and ensure consistency across teams.

Why this answer

Terraform state is the mechanism by which Terraform maps real-world resources to your configuration, and it can be stored either in a local file (e.g., terraform.tfstate) or remotely in a backend such as S3, Azure Storage, or Terraform Cloud. This flexibility allows teams to share state and enable collaboration, while local storage is suitable for single-user or testing scenarios.

Exam trap

A common pitfall is thinking that state is optional or that the filename is fixed; however, state is mandatory for Terraform to track resources and the filename is fully configurable via the backend configuration.

308
MCQmedium

A developer creates a module in a subdirectory called 'networking' relative to the root module. How should the module source be specified in the root module?

A../networking
B../modules/networking
C.../networking
D.networking
AnswerA

The path starts with './' indicating a relative path from the current directory.

Why this answer

When referencing a local module in a subdirectory relative to the root module, the correct path prefix is './' followed by the subdirectory name. Option A, './networking', correctly uses a relative path starting with './' to indicate the 'networking' directory is a child of the root module's directory. This is the standard Terraform convention for local module sources.

Exam trap

A common mistake on the Terraform exam is confusing local module paths (requiring './' or '../') with registry module references (bare name or 'namespace/name/provider'). Candidates often omit the './' prefix and incorrectly select a bare name like 'networking'.

How to eliminate wrong answers

Option B is wrong because './modules/networking' implies the module is inside a 'modules' subdirectory, but the question states the module is directly in a subdirectory called 'networking' relative to the root module, not nested under 'modules'. Option C is wrong because '../networking' uses a parent directory reference ('..'), which would look for the module in the directory above the root module, not in a subdirectory of the root. Option D is wrong because 'networking' without a path prefix is interpreted by Terraform as a Terraform Registry module reference, not a local filesystem path.

309
MCQmedium

A team wants to use Terraform to manage their AWS infrastructure. They have existing resources created manually. What is the recommended approach to bring these resources under Terraform management?

A.Delete the existing resources and recreate them using Terraform configuration.
B.Use terraform plan to detect existing resources and automatically adopt them.
C.Write Terraform configuration that matches existing resources and run terraform apply.
D.Use terraform import to bring each resource into state.
AnswerD

The `terraform import` command is the correct and intended workflow for bringing existing infrastructure under Terraform's management. It reads the current state and attributes of a specified remote resource and then records this information within the Terraform state file, associating it with a corresponding resource block in the local configuration. This crucial step allows Terraform to recognize and manage the resource's lifecycle, enabling subsequent `plan` and `apply` operations to detect drift and make controlled modifications without recreating the resource.

Why this answer

`terraform import` is the recommended approach to bring existing manually created resources under Terraform management. It maps the real-world resource ID into your Terraform state file, allowing Terraform to track and manage it without deleting or recreating it. This preserves the existing infrastructure while enabling future updates via configuration.

Exam trap

A common misconception is that `terraform plan` can discover and adopt existing resources, but in reality, `plan` only compares state to configuration and cannot detect resources outside of state.

How to eliminate wrong answers

Option A is wrong because deleting and recreating resources causes unnecessary downtime and risk, and is not the recommended workflow for adopting existing infrastructure. Option B is wrong because `terraform plan` does not detect existing resources or automatically adopt them; it only compares the current state against the configuration and cannot discover resources not already in state. Option C is wrong because running `terraform apply` on a configuration that matches existing resources will attempt to create new resources, leading to conflicts or duplicate resources, unless the resources are already in state via import.

310
MCQhard

Your team uses Terraform to manage a multi-region AWS deployment consisting of over 500 resources. The state file is stored in an S3 backend with DynamoDB locking. Recently, one of your colleagues accidentally deleted the state file from S3 while trying to clean up old backups. Fortunately, you have a backup from two days ago. However, after restoring the backup, you notice that several recent changes, including two new EC2 instances and a security group, are missing from the state. The actual resources still exist in AWS. You need to bring the state back in sync with the real-world infrastructure without recreating these resources. What should you do?

A.Use `terraform import` for each missing resource to add them to state
B.Run `terraform apply` to recreate the missing resources
C.Manually edit the state file to add the missing resource entries
D.Run `terraform refresh` to update the state with the missing resources
AnswerA

The `terraform import` command is the correct and intended mechanism for bringing existing infrastructure resources, which were not originally provisioned by Terraform, under Terraform's management. It reads the current state of a specified resource from the cloud provider and adds a corresponding entry to the Terraform state file, linking it to a defined resource block in the configuration. This process ensures that Terraform can subsequently manage, update, or destroy the imported resource.

Why this answer

`terraform import` is the intended mechanism to bring existing infrastructure under Terraform management without recreating it. Since the missing EC2 instances and security group still exist in AWS but are absent from the state file, importing each resource by its AWS ID will add the corresponding state entries, allowing Terraform to manage them going forward. This avoids the downtime and potential configuration drift that would occur with `terraform apply` or manual state editing.

Exam trap

A common misconception is that `terraform refresh` can discover and add missing resources to state, but refresh only updates attributes for resources already in state and cannot import new resources.

How to eliminate wrong answers

Option B is wrong because `terraform apply` would attempt to recreate the missing resources, potentially causing duplicate resources or conflicts with the existing ones, and would not sync the state with the real-world infrastructure. Option C is wrong because manually editing the state file is error-prone, unsupported, and can lead to state corruption or mismatches with the actual resource attributes; Terraform state files are JSON but should never be hand-edited for production recovery. Option D is wrong because `terraform refresh` only updates the state with current attribute values for resources already tracked in the state file; it cannot discover or add resources that are not already present in the state.

311
MCQmedium

A team uses an S3 backend with DynamoDB for state locking. They notice that sometimes terraform plan fails because the state is locked. What is the best practice to handle this in an automated pipeline?

A.Serialize pipeline runs to avoid concurrent execution
B.Use force-unlock before each plan
C.Increase the lock timeout
D.Use -lock=false in the pipeline
AnswerA

Serializing pipeline runs is the most effective and recommended approach to prevent state corruption when using a shared Terraform state backend. This strategy ensures that only one Terraform operation (e.g., plan or apply) can acquire the state lock and modify the state at any given time. By eliminating concurrent execution, it directly addresses the root cause of state locking conflicts and race conditions, maintaining the integrity of the remote state file.

Why this answer

Serializing pipeline runs is the best practice to prevent concurrent Terraform operations from competing for the same state lock. When multiple pipeline jobs attempt to run `terraform plan` or `terraform apply` simultaneously, DynamoDB-based state locking ensures only one operation holds the lock at a time, causing the others to fail. By enforcing sequential execution (e.g., via CI/CD stage dependencies or a mutex), you avoid lock contention entirely without risking data corruption or bypassing safety mechanisms.

Exam trap

The trap here is that candidates often assume increasing timeouts or disabling locking is acceptable for automation, but HashiCorp tests the understanding that state locking is a safety mechanism and the correct fix is to prevent concurrent access, not to bypass or extend the lock.

How to eliminate wrong answers

Option B is wrong because `force-unlock` is a manual intervention to remove a stale lock (e.g., after a crash) and should never be used in an automated pipeline — it can lead to concurrent state modifications and corruption. Option C is wrong because increasing the lock timeout does not resolve concurrent execution conflicts; it only delays the failure and can cause longer pipeline stalls without addressing the root cause. Option D is wrong because `-lock=false` disables state locking entirely, which can cause multiple operations to modify the state simultaneously, leading to state corruption or lost updates.

312
Matchingmedium

Match each Terraform function to its category.

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

Concepts
Matches

List function

Map function

IP network function

Encoding function

Date and time function

Why these pairings

Terraform functions are categorized by the type of data they operate on. The correct matches are: max() (numeric), lower() (string), and concat() (collection). Common confusions include misclassifying functions across categories.

313
MCQeasy

Which Terraform command is used to bring existing infrastructure that was created outside of Terraform under Terraform management?

A.terraform state push
B.terraform apply
C.terraform import
D.terraform refresh
AnswerC

The "terraform import" command is the designated tool for incorporating existing infrastructure resources into Terraform's state management. This process requires specifying the Terraform resource address and the unique identifier of the existing cloud resource, effectively linking them within the state file. Once imported, Terraform can then manage the lifecycle of that previously unmanaged resource, allowing subsequent "terraform plan" and "apply" operations to detect and propose changes to it based on the corresponding HCL configuration.

Why this answer

`terraform import` is the dedicated command to bring existing infrastructure that was created outside of Terraform under Terraform management. It maps the real-world resource ID to a Terraform resource address in state, allowing Terraform to track and manage that resource without recreating it.

Exam trap

The exam often tests the distinction between `terraform import` (which adds external resources to state) and `terraform refresh` (which only syncs state for already-managed resources), leading candidates to mistakenly choose `terraform refresh` when they need to bring new resources under management.

How to eliminate wrong answers

Option A is wrong because `terraform state push` is used to manually upload a state file to a configured backend, not to import existing infrastructure. Option B is wrong because `terraform apply` applies configuration changes to create, update, or destroy resources, but it cannot import resources that were created outside of Terraform; it would attempt to create them anew, causing conflicts. Option D is wrong because `terraform refresh` updates the state file with the real-world state of already-managed resources, but it does not add new resources that were created outside of Terraform to the state.

314
MCQeasy

A user wants to see the current state of resources in a human-readable format without making changes. Which command should they use?

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

The `terraform show` command is the definitive tool for inspecting the current state of resources managed by Terraform. It reads the `terraform.tfstate` file and presents a detailed, human-readable representation of all tracked resources, including their attributes and their current values. This command is invaluable for auditing, debugging, and understanding the exact configuration of your deployed infrastructure as recorded in the state file.

Why this answer

`terraform show`, is correct because it displays the current state of managed resources in a human-readable format (defaulting to plain text) without making any changes. This command reads the state file directly and presents its contents, making it ideal for inspection and debugging. Unlike `terraform plan`, it does not generate an execution plan or propose modifications.

Exam trap

HashiCorp often tests the distinction between commands that inspect state (`terraform show`, `terraform state list`) versus those that generate plans or modify state, and the trap here is confusing `terraform plan` (which can show proposed changes) with a read-only view of the current state.

How to eliminate wrong answers

Option A is wrong because `terraform output` only shows the values of defined output variables, not the full state of all resources. Option B is wrong because `terraform state list` merely lists resource addresses in the state without displaying their attributes or configuration details. Option C is wrong because `terraform plan` creates an execution plan that compares current state with configuration and can propose changes, which is not a read-only view of the current state.

315
MCQmedium

You are a DevOps engineer at a growing startup. The infrastructure currently consists of a single AWS EC2 instance running a web application, manually configured. The company plans to scale to multiple instances and environments (development, staging, production). They want to adopt Infrastructure as Code using Terraform. The team has limited experience with Terraform and wants to start small, then gradually adopt more advanced features. The current manual infrastructure must be imported into Terraform. The team also wants to ensure that code changes are reviewed via pull requests before being applied. Which of the following is the best course of action to meet these requirements?

A.Install Terraform on the existing instance, run terraform init and apply directly to manage it, and store state locally. Have team members share the state file via a shared folder.
B.Write Terraform configuration from scratch to match the existing instance, but do not import; instead, destroy the old instance and recreate it with Terraform.
C.Create separate Git branches for each environment (dev, staging, prod) and have each team member work independently on their branch, merging occasionally.
D.Create a Git repository with a main branch. Write a minimal Terraform configuration that describes the existing EC2 instance. Use terraform import to bring the instance under Terraform management. Store the state file remotely in S3 with DynamoDB locking. Set up a CI pipeline that runs terraform plan on pull requests and requires approval before merging.
AnswerD

Creating a Git repository with a main branch provides version control and a single source of truth for infrastructure code. Using `terraform import` allows existing resources to be brought under management non-disruptively, while remote state in S3 with DynamoDB locking ensures collaborative safety and prevents concurrent state modifications. A CI pipeline with `terraform plan` on PRs and approval enforces code review and validates changes before deployment, establishing robust operational practices.

Why this answer

It follows the best practices for adopting Infrastructure as Code with Terraform in a team setting. It starts by writing a minimal configuration that matches the existing EC2 instance, uses `terraform import` to bring it under management without downtime, stores state remotely in S3 with DynamoDB locking for collaboration and consistency, and sets up a CI pipeline to run `terraform plan` on pull requests with approval gates, ensuring code review before changes are applied.

Exam trap

HashiCorp often tests the misconception that you must destroy and recreate infrastructure to adopt IaC, or that local state sharing is acceptable for teams, when in fact `terraform import` and remote state with locking are the correct approaches for zero-downtime adoption and collaboration.

How to eliminate wrong answers

Option A is wrong because storing state locally in a shared folder leads to state file corruption, conflicts, and no locking mechanism, which violates the requirement for safe team collaboration and code review via pull requests. Option B is wrong because destroying the existing instance to recreate it with Terraform causes unnecessary downtime and risk, whereas `terraform import` can bring the instance under management without disruption. Option C is wrong because having separate Git branches for each environment without a unified main branch and CI pipeline leads to configuration drift, lack of code review, and no controlled promotion of changes across environments.

316
MCQhard

Your organization manages a multi-cloud infrastructure using Terraform. The infrastructure includes an AWS VPC with subnets and EC2 instances, and an Azure resource group with virtual networks and VMs. The Terraform configuration is stored in a Git repository, and state is stored in an S3 bucket with DynamoDB locking. Recently, a developer updated the configuration to add a new security group rule in AWS, but after running `terraform apply`, the rule was not created. The developer verified that the configuration file contains the rule. Additionally, the developer noticed that the state file shows the security group exists but without the new rule. The developer ran `terraform plan` again, and it shows that the rule will be created. However, when applying, it fails with a 'timeout' error. The operations team suspects network connectivity issues to the S3 backend. What is the best course of action to resolve this issue?

A.Run `terraform init` again to reinitialize the backend.
B.Migrate the state backend to Terraform Cloud, and use remote operations for applies.
C.Increase the timeout value in the Terraform provider configuration.
D.Disable state locking by removing the DynamoDB table reference.
AnswerB

Migrating the state backend to Terraform Cloud and utilizing remote operations offloads the execution of `terraform apply` from the local machine to HashiCorp's managed infrastructure. This approach effectively bypasses local network instability, proxy configurations, or firewall restrictions that might be causing timeouts when accessing the state backend or provider APIs from the local environment. Terraform Cloud's robust and highly available execution environment ensures reliable communication with the state backend and target cloud providers.

Why this answer

The timeout error when applying, despite a successful plan, indicates that the issue is not with the configuration or state locking but with the network connectivity to the S3 backend during the apply operation. Migrating to Terraform Cloud with remote operations moves the execution environment to Terraform Cloud's infrastructure, which has reliable connectivity to the S3 backend, bypassing the local network issues. This resolves the timeout without altering the configuration or compromising state integrity.

Exam trap

HashiCorp often tests the distinction between provider-level timeouts (for API calls to cloud providers) and backend-level timeouts (for state storage), leading candidates to incorrectly choose increasing provider timeouts when the issue is actually with backend connectivity.

How to eliminate wrong answers

Option A is wrong because `terraform init` reinitializes the backend configuration but does not fix network connectivity issues to the S3 backend; the timeout occurs during the apply, not during initialization. Option C is wrong because increasing the timeout in the provider configuration affects API calls to AWS or Azure, not the HTTP timeout for the S3 backend connection; the timeout error is from the backend, not the provider. Option D is wrong because disabling state locking by removing the DynamoDB table reference would allow concurrent state modifications, risking state corruption and race conditions, and does not address the underlying network connectivity issue.

317
Multi-Selectmedium

Which of the following statements about the core Terraform workflow (Write, Plan, Apply) are correct? (Choose all that apply. There are four correct answers.)

Select 4 answers
.The `terraform plan` command creates an execution plan showing what actions Terraform will take to reach the desired state described in the configuration.
.The `terraform apply` command without any flags will automatically apply the last saved plan if one exists from a previous `terraform plan -out` command.
.During the 'Write' phase, you define resources in one or more `.tf` configuration files, which can reference variables, data sources, and modules.
.If a `terraform plan` shows that a resource will be destroyed and recreated, the state file is immediately updated to reflect this planned change before apply.
.Running `terraform plan` is strictly optional before `terraform apply` because apply will automatically generate and execute a plan if none is provided.
.The `terraform apply` command can be used to destroy infrastructure by passing a plan that includes only destroy operations, but the more common approach is to use `terraform destroy`.

Why this answer

The core Terraform workflow consists of three phases: Write, Plan, and Apply. During the Write phase, you define your desired infrastructure in `.tf` configuration files, which can include variables, data sources, and modules. The `terraform plan` command creates an execution plan that shows what actions Terraform will take to reach that desired state.

The `terraform apply` command can use a saved plan from `terraform plan -out` without additional flags, or if no plan is provided, it will automatically generate and execute a new plan. This workflow ensures that changes are reviewed before being applied, reducing the risk of unintended modifications.

Exam trap

HashiCorp often tests the misconception that `terraform plan` modifies the state file or that `terraform apply` always requires a separate plan command, when in fact `terraform apply` can generate and execute a plan automatically if none is provided.

318
MCQmedium

A Terraform plan shows that an AWS EC2 instance will be destroyed and recreated. The team wants to ensure zero downtime during the update. Which lifecycle attribute should be added?

A.depends_on
B.ignore_changes
C.create_before_destroy
D.prevent_destroy
AnswerC

The create_before_destroy lifecycle rule explicitly instructs Terraform to provision the new version of a resource entirely *before* initiating the destruction of the old version when a replacement is necessary. This critical behavior is designed to minimize or eliminate downtime for services by ensuring the updated resource is fully operational and ready to serve traffic before its predecessor is taken offline. It directly addresses the need to maintain continuous availability during resource updates that require recreation, such as an EC2 instance replacement.

Why this answer

`create_before_destroy` is a lifecycle attribute that instructs Terraform to create the replacement resource first, then destroy the old one. This ensures that the new EC2 instance is fully operational before the original is terminated, achieving zero downtime during the update.

Exam trap

The trap here is that candidates often confuse `create_before_destroy` with `prevent_destroy` or `ignore_changes`, thinking any lifecycle attribute that prevents destruction or ignores changes will solve downtime, when only `create_before_destroy` explicitly ensures the replacement is ready before the original is removed.

How to eliminate wrong answers

Option A is wrong because `depends_on` is used to define explicit dependencies between resources, not to control the order of create/destroy operations during updates. Option B is wrong because `ignore_changes` prevents Terraform from detecting and acting on specific attribute changes, but it does not affect the creation/destruction sequence or prevent downtime. Option D is wrong because `prevent_destroy` blocks any destroy operation entirely, which would prevent the update from proceeding at all, rather than enabling zero downtime.

319
Matchingmedium

Match each Terraform cloud/enterprise feature to its purpose.

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

Concepts
Matches

Organize state and runs for different environments

Integrate third-party policy or compliance checks

Policy as code framework for governance

Store state securely in Terraform Cloud

Trigger runs automatically from version control

Why these pairings

Workspaces isolate state and variables per environment, Sentinel enforces policies, and Run Tasks integrate third-party tools. Common confusions include mixing the roles of Workspaces and Remote State, or Sentinel with Workspaces.

320
MCQeasy

Refer to the exhibit. A developer runs terraform plan and sees the above output. What will happen when terraform apply is executed?

A.The existing EC2 instance is replaced due to a change in instance_type.
B.A new EC2 instance is created with instance_type t2.small, and the old one is destroyed.
C.The existing EC2 instance's instance_type is changed to t2.small in-place.
D.No changes will be made because the plan shows an update.
AnswerC

This statement is correct. The tilde (`~`) prefix in a `terraform plan` output explicitly indicates that an existing resource will be updated in-place, meaning its attributes will be modified without destroying and recreating the resource itself. For an AWS EC2 instance, changing the `instance_type` from its current value to `t2.small` is a supported in-place modification by the AWS provider, which will apply the change to the running instance.

Why this answer

Terraform's plan output shows an in-place update (indicated by the tilde `~` symbol) for the `instance_type` attribute of the existing EC2 instance. When `terraform apply` is executed, Terraform will modify the instance's type to `t2.small` without destroying and recreating the resource, as the change is supported by the AWS provider for EC2 instances.

Exam trap

Candidates often misinterpret the tilde (~) symbol in Terraform plan output as indicating a destroy-and-recreate action, but it actually signifies an in-place update. This question tests the ability to distinguish between in-place changes and resource replacement.

How to eliminate wrong answers

Option A is wrong because the plan does not show a force-new replacement (indicated by the `-/+` symbol); instead, it shows an in-place update, so the instance is not replaced. Option B is wrong because a new EC2 instance is not created; the plan shows a single resource change (update) rather than a destroy and create action. Option D is wrong because the plan explicitly shows a change to the `instance_type` attribute, so `terraform apply` will execute that modification, not skip it.

321
MCQhard

A company manages a large Terraform configuration with an S3 backend and DynamoDB locking. After initial setup, they modify the backend block in the main.tf to change the S3 bucket name. Running 'terraform plan' yields: 'Backend reinitialization required. Please run "terraform init".' They run 'terraform init' but it prompts to migrate state from the old bucket to the new one. The old bucket is empty (no state files) because the configuration has never been applied. The team wants to avoid unnecessary state migration. Which step should they take?

A.Run 'terraform init -reconfigure' to skip state migration.
B.Delete the .terraform directory and run 'terraform init' again.
C.Change the backend configuration back to the original bucket and run 'terraform state rm' to clear resources.
D.Run 'terraform init -migrate-state' and accept the migration.
AnswerA

This option is correct because the `-reconfigure` flag instructs Terraform to disregard any existing backend configuration and reinitialize the backend from scratch. When a backend has been changed to an empty S3 bucket, using `-reconfigure` prevents Terraform from attempting an unnecessary state migration from a non-existent or empty previous state, effectively resetting the backend configuration to the new, empty S3 bucket without errors. This is the most efficient and intended method for such a scenario.

Why this answer

The correct action is to use 'terraform init -reconfigure', which allows reinitialization without migration by ignoring the existing backend configuration and starting fresh. Option B (deleting .terraform) would also work but is less efficient and may lose cached modules. Option C is unnecessary because there is no state to manage.

Option D would force migration, which the team wants to avoid.

322
Drag & Dropmedium

Drag and drop the steps to upgrade Terraform providers in a configuration 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 upgrading Terraform providers is: first check current provider versions to establish a baseline, then update version constraints in the configuration to target the desired versions, then run terraform init to download and install those versions, and finally run terraform plan to verify that the upgrade does not introduce unexpected changes. This order ensures a controlled and validated upgrade process.

323
MCQmedium

Refer to the exhibit. What is the primary purpose of the version constraint '~> 4.0'?

A.Allows any version in the 4.0 range including patch updates.
B.Allows only exact version 4.0.
C.Allows versions 4.0 through 5.0.
D.Allows any version 4.0 or higher.
AnswerA

The ~> 4.0 version constraint, known as the pessimistic constraint, precisely specifies that any version greater than or equal to 4.0.0 is acceptable, provided it remains strictly less than 5.0.0. This means it permits minor version increments (e.g., 4.1.0, 4.2.5) and patch updates (e.g., 4.0.1, 4.0.99) within the 4.x series. The primary purpose is to allow for non-breaking updates while preventing automatic upgrades to a new major version that might introduce breaking changes.

Why this answer

The version constraint '~> 4.0' uses the pessimistic version constraint operator in Terraform. It allows any version in the 4.x range, meaning versions >= 4.0 and < 5.0, including patch updates like 4.1, 4.2, etc. Therefore, option A is correct.

Option B is incorrect because '= 4.0' would pin to only exact 4.0. Option C is incorrect because it includes 5.0, which is not allowed. Option D is incorrect because it allows any version 4.0 or higher, including 5.0 and beyond, which is too broad.

324
Multi-Selecteasy

A team is defining their Infrastructure as Code strategy. Which two of the following are key benefits of using IaC compared to manual configuration?

Select 2 answers
A.Faster deployment and provisioning.
B.Reduced need for monitoring.
C.Elimination of all security vulnerabilities.
D.Automatic recovery from any infrastructure failure.
E.Consistent and repeatable infrastructure setups.
AnswersA, E

Infrastructure as Code (IaC) tools like Terraform automate the entire infrastructure lifecycle, from initial provisioning to updates and deprovisioning. This automation significantly reduces the time required to deploy complex environments compared to manual, click-intensive processes, enabling rapid iteration and scaling of resources.

Why this answer

IaC automates the provisioning and configuration of infrastructure through code, eliminating the need for manual, error-prone steps. This enables rapid deployment of resources, often reducing setup times from hours to minutes by leveraging tools like Terraform to apply declarative configurations in parallel across multiple providers.

Exam trap

In HashiCorp Terraform exams, this question tests the misconception that IaC eliminates all operational overhead, such as monitoring or failure recovery, when in reality IaC focuses on provisioning and configuration consistency, not on runtime resilience or security guarantees.

325
MCQeasy

Refer to the exhibit. What does the output indicate?

A.The Terraform configuration defines three resources
B.The state file tracks three resources
C.Three providers are configured
D.Three workspaces are in use
E.The plan will create three resources
AnswerB

The output of `terraform state list` explicitly displays the addresses of all resource instances that Terraform is currently managing within its state file for the active workspace. In the exhibit, three distinct resource addresses are clearly enumerated (e.g., `aws_instance.web`, `aws_s3_bucket.mybucket`, `null_resource.example`). This command's primary purpose is to provide an inventory of the resources recorded in the state, directly confirming that the state file is tracking exactly three resources.

Why this answer

The `terraform state list` command lists all resources currently tracked in the state file. Here it shows three resources: a VPC, a subnet, and an EC2 instance.

326
MCQeasy

After modifying a Terraform configuration file, a user runs 'terraform plan' and sees 'No changes. Infrastructure is up-to-date.' What is the most likely reason?

A.The user forgot to run terraform init.
B.The configuration changes were not committed to version control.
C.The state is stored remotely and the user does not have access.
D.The configuration changes were made in a different directory.
AnswerD

Terraform commands, including `terraform plan`, operate strictly within the current working directory where the command is executed, unless explicitly specified otherwise with the `-chdir` option. If configuration files were modified in a separate directory, `terraform plan` run in the original directory would not detect those changes, as it only evaluates the `.tf` files present in its execution context, comparing them against the associated state file.

Why this answer

Terraform operates on the configuration files in the current working directory. If the user modified a Terraform configuration file in a different directory and then ran 'terraform plan' from the original directory, Terraform would compare the state against the unchanged configuration in the current directory, resulting in 'No changes. Infrastructure is up-to-date.'

Exam trap

The trap here is that candidates may assume 'No changes' always means the infrastructure is truly up-to-date, overlooking the possibility that Terraform is simply evaluating the wrong set of configuration files due to directory context.

How to eliminate wrong answers

Option A is wrong because forgetting to run 'terraform init' would cause an error about missing providers or modules, not a 'No changes' message. Option B is wrong because version control (e.g., Git) has no effect on Terraform's plan operation; Terraform reads the local filesystem, not the repository history. Option C is wrong because if the user lacks access to the remote state, Terraform would fail with an authentication or permission error, not report that the infrastructure is up-to-date.

327
MCQhard

Refer to the exhibit. A user runs `terraform plan` and receives this error. The user is using a local backend. Which of the following is the most likely cause?

A.The workspace is not selected correctly.
B.The configured state file path's directory does not exist.
C.The state file is corrupted.
D.The backend is misconfigured for remote state.
AnswerB

"The configured state file path's directory does not exist." This is the correct explanation. Terraform requires the parent directory for its state file (e.g., `terraform.tfstate` by default, or a custom path specified in a `local` backend block) to exist on the file system *before* it can write or update the state file. If the directory specified in the backend configuration, or the default `.terraform` directory where state files are typically stored, is missing, Terraform cannot proceed, resulting in an error indicating the directory does not exist.

Why this answer

With a local backend, Terraform stores state in a local file, typically `terraform.tfstate`. The error indicates that the directory specified for the state file path does not exist. Terraform requires the parent directory to exist before it can write the state file; if it is missing, the plan fails with this error.

Exam trap

A common trap in Terraform exams is confusing a missing directory for the local state file with state file corruption or an incorrect workspace selection. The error typically indicates that the parent directory path does not exist, not that the file itself is unreadable.

How to eliminate wrong answers

Option A is wrong because the workspace is selected correctly by default (the `default` workspace) and a missing directory error is unrelated to workspace selection. Option C is wrong because a corrupted state file would produce a parse or checksum error, not a missing directory error. Option D is wrong because the user is explicitly using a local backend, so remote state misconfiguration is irrelevant.

328
MCQeasy

A company manages multiple AWS accounts using Terraform. They have a central repository where all Terraform configurations are stored. Recently, a developer accidentally ran terraform destroy on a production workspace and deleted critical resources. The team wants to implement safeguards to prevent such incidents while still allowing developers to test changes in non-production environments. They currently use Terraform Cloud for remote state management and runs. Which course of action should the team take to minimize risk?

A.Store the production Terraform state file locally and restrict access to it.
B.Use Terraform's built-in lifecycle prevent_destroy on all production resources.
C.Implement run tasks in Terraform Cloud that require approval for any destroy operation on workspaces tagged as 'production'.
D.Remove all developers' access to the Terraform Cloud API and only allow operations via pull requests.
AnswerC

Implementing run tasks in Terraform Cloud that require approval for any destroy operation on workspaces tagged as 'production' is an effective and scalable solution. Terraform Cloud run tasks allow for custom policy enforcement and integration with external systems, enabling a mandatory manual approval step specifically for destructive actions on critical resources. This provides a robust governance mechanism, ensuring that production infrastructure changes are reviewed and authorized before execution, thereby preventing accidental destruction.

Why this answer

Terraform Cloud run tasks can enforce approval workflows for destroy operations on production workspaces, providing a safeguard against accidental deletions while still allowing developers to test in non-production environments. Option A is wrong because storing state locally is insecure and eliminates the benefits of remote state management. Option B is wrong because `prevent_destroy` blocks all destroy operations, including intentional ones, and is not a flexible safeguard.

Option D is wrong because removing API access entirely is too restrictive and hinders legitimate operations; instead, proper permissions and approval workflows should be used.

329
MCQeasy

In Terraform, which block is used to define a default value for a variable that can be overridden at runtime?

A.locals
B.variable
C.output
D.terraform
AnswerB

The `variable` block is specifically designed to declare input variables for a Terraform module. Within this block, the `default` argument allows you to specify a fallback value that will be used if no explicit value is provided for the variable through other means, such as command-line arguments, environment variables, or `.tfvars` files. This mechanism ensures that the configuration can proceed even without user input for optional parameters.

Why this answer

In Terraform, the `variable` block is used to declare input variables, which can include a `default` argument to specify a fallback value. This default can be overridden at runtime using mechanisms like `-var` flags, `TF_VAR_` environment variables, or `.tfvars` files, making option B correct.

Exam trap

The trap here is that candidates confuse `locals` with `variable` because both can hold values, but only `variable` supports runtime override via external inputs, whereas `locals` are purely internal and immutable after plan generation.

How to eliminate wrong answers

Option A is wrong because `locals` blocks define local values that are computed within the configuration and cannot be overridden at runtime; they are fixed once evaluated. Option C is wrong because `output` blocks are used to expose attribute values after apply, not to define variables with defaults. Option D is wrong because the `terraform` block configures provider requirements and backend settings, not variable declarations.

330
MCQmedium

A developer needs to retrieve the current state of an AWS EC2 instance that was created by Terraform but the configuration file is missing. Which command will output the attributes of the instance in a format suitable for generating a configuration?

A.terraform output aws_instance
B.terraform state pull | grep aws_instance
C.terraform state show -json aws_instance.example
D.terraform plan
AnswerC

The `terraform state show` command is specifically designed to display the current attributes of a particular resource instance as recorded in the Terraform state file. By specifying `aws_instance.example` and including the `-json` flag, the command outputs all attributes of that exact resource in a structured, machine-readable JSON format. This precise and standardized output is ideal for scripting, automation, or direct consumption by other tools needing current state attributes.

Why this answer

`terraform state show -json aws_instance.example` retrieves the current state of the specified resource from the Terraform state file and outputs it in JSON format, which can be directly used to reconstruct a configuration block. This command is specifically designed for inspecting a single resource's attributes when the original configuration is unavailable.

Exam trap

The trap here is that candidates confuse `terraform state show` with `terraform output` or `terraform plan`, assuming any command that displays state information can generate a configuration, but only `terraform state show -json` provides the precise attribute mapping needed for configuration reconstruction.

How to eliminate wrong answers

Option A is wrong because `terraform output` only displays output values defined in the configuration, not the attributes of a resource like an EC2 instance. Option B is wrong because `terraform state pull` outputs the entire raw state file in JSON, and piping it through `grep aws_instance` would only return matching lines, not a structured, resource-specific output suitable for configuration generation. Option D is wrong because `terraform plan` shows a comparison between the current state and the configuration, but it does not output the current attributes of a resource in a format that can be used to recreate a configuration.

331
MCQmedium

Refer to the exhibit. After running terraform apply, the output shows: Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: instance_id = "i-1234567890abcdef0" However, the engineer notices that the instance type is t2.micro, but the expected instance type was t2.medium. What is the most likely reason for this discrepancy?

A.The configuration file specified t2.micro, so Terraform created the instance accordingly.
B.The engineer applied a different configuration file by mistake.
C.Terraform ignored the instance_type argument because it is not supported for the given AMI.
D.The instance_type was overridden by a default value in the provider.
AnswerA

Terraform operates on a declarative model, where the configuration file explicitly defines the desired state of infrastructure. When `terraform apply` is executed, Terraform compares this desired state with the current state and provisions resources to match the configuration. Therefore, if `t2.micro` was specified in the configuration, Terraform's primary function is to ensure the created instance adheres precisely to that explicit instruction, making the configuration the authoritative source.

Why this answer

The configuration explicitly sets instance_type to t2.micro, so Terraform will use that value. The engineer may have expected a different value but the configuration is authoritative.

332
MCQeasy

A team wants to import an existing AWS S3 bucket named 'my-bucket' into Terraform state. The resource block is defined as 'aws_s3_bucket.my_bucket'. Which command should be used?

A.terraform import my-bucket aws_s3_bucket.my_bucket
B.terraform import 'aws_s3_bucket.my_bucket' 'my-bucket'
C.terraform import aws_s3_bucket.my_bucket my-bucket
D.terraform import aws_s3_bucket.my-bucket my-bucket
AnswerC

This command correctly follows the `terraform import <ADDRESS> <ID>` syntax, which is essential for bringing existing infrastructure under Terraform management. `aws_s3_bucket.my_bucket` accurately specifies the desired Terraform resource address, indicating it should be managed as an `aws_s3_bucket` resource named `my_bucket` within the configuration. `my-bucket` correctly identifies the exact ID of the pre-existing AWS S3 bucket to be imported into Terraform's state.

Why this answer

The correct syntax for `terraform import` is `terraform import <resource_address> <id>`, where the resource address is the Terraform resource block identifier (e.g., `aws_s3_bucket.my_bucket`) and the ID is the actual AWS resource identifier (e.g., the bucket name `my-bucket`). Option C follows this exact order: `terraform import aws_s3_bucket.my_bucket my-bucket`, making it the correct command to import the existing S3 bucket into Terraform state.

Exam trap

The Terraform exam often tests the argument order in `terraform import` — candidates frequently confuse the resource address and the resource ID, mistakenly thinking the ID comes first (as in some cloud CLI tools), but Terraform strictly requires the address before the ID.

How to eliminate wrong answers

Option A is wrong because it reverses the argument order, placing the bucket name first and the resource address second, which violates the required `terraform import <address> <id>` syntax. Option B is wrong because it wraps both arguments in single quotes unnecessarily (though quoting is not the primary error), but more critically it still places the resource address second and the ID first, which is the incorrect order. Option D is wrong because it uses a hyphen in the resource address (`aws_s3_bucket.my-bucket`), but the Terraform resource block name must use underscores, not hyphens, so `my-bucket` is invalid as a Terraform resource name.

333
Multi-Selectmedium

Which TWO actions are part of the core Terraform workflow? (Choose two.)

Select 2 answers
A.terraform fmt
B.terraform plan
C.terraform validate
D.terraform apply
E.terraform destroy
AnswersB, D

terraform plan is a fundamental command in the core Terraform workflow, serving as the crucial second step after initialization. This command generates an execution plan, detailing exactly what actions Terraform will perform to achieve the desired state defined in the configuration files. It allows users to review proposed changes—such as creating, updating, or destroying resources—before any actual modifications are made to the real infrastructure, ensuring predictability and preventing unintended consequences.

Why this answer

The core Terraform workflow consists of three main steps: `terraform init` to initialize the working directory, `terraform plan` to preview changes, and `terraform apply` to execute those changes. Option B (`terraform plan`) is correct because it creates an execution plan showing what actions Terraform will take to reach the desired state defined in configuration files. Option D (`terraform apply`) is correct because it applies the changes required to reach the desired state, either by using a previously generated plan or by creating a new plan and prompting for approval.

Exam trap

HashiCorp often tests the distinction between commands that are part of the essential three-step workflow (init, plan, apply) versus commands that are useful but optional, leading candidates to mistakenly include `terraform validate` or `terraform fmt` as core workflow steps.

334
MCQhard

A team manages a multi-tier application consisting of web servers, application servers, and databases deployed across AWS and Azure. Historically, they have provisioned infrastructure manually using cloud consoles and ad-hoc scripts. To improve consistency and reduce errors, they decide to adopt Terraform for Infrastructure as Code. After initial rollout, they encounter problems: some team members still make direct changes via the cloud console to quickly fix issues, causing configuration drift between the Terraform state and actual resources. They also need to manage three distinct environments (development, staging, production) with different configurations (e.g., instance sizes, database settings). The team consists of five people with a limited budget for additional tools. Which course of action best addresses these challenges while adhering to IaC principles?

A.Store Terraform state in a shared S3 bucket with DynamoDB locking, and have each team member apply their own changes locally after review.
B.Use Terraform workspaces to manage environments and enforce that all changes go through version-controlled Terraform configs, disabling direct console changes via IAM policies.
C.Assign each environment to a different Terraform provider alias and use manual planning to ensure correctness.
D.Implement a CI/CD pipeline that runs terraform plan and apply automatically on merges to the main branch, and use Terraform Cloud's Sentinel policies to prevent drift.
AnswerD

Implementing a CI/CD pipeline ensures that all infrastructure changes are applied through an automated, version-controlled process, eliminating local applies and unreviewed modifications that commonly cause drift. This pipeline can run `terraform plan` for review and `terraform apply` automatically upon merge to the main branch, enforcing a single source of truth. Furthermore, integrating Terraform Cloud's Sentinel policies provides policy-as-code enforcement, actively preventing deployments that would introduce drift or violate organizational compliance rules by blocking non-compliant plans before application.

Why this answer

Best addresses both challenges. Implementing a CI/CD pipeline that runs terraform plan and apply automatically on merges to the main branch ensures all infrastructure changes are made through version-controlled Terraform configurations, preventing configuration drift from manual console changes. Using Terraform Cloud's Sentinel policies adds an additional layer of governance to enforce compliance and prevent unauthorized changes.

This approach also naturally supports environment management because different branches or configurations can represent the three environments (development, staging, production), and the pipeline can target different remote backends or workspaces. Option A (shared S3 with DynamoDB locking) improves state management and collaboration but does not prevent drift from direct console changes. Option B (workspaces and IAM policies) can help with environment separation and restrict console changes, but local applies still risk drift and the IAM approach may be overly restrictive.

Option C (provider aliases) is not designed for environment management and manual planning does not prevent drift.

335
MCQeasy

Which of the following is a primary benefit of using Infrastructure as Code?

A.Faster provisioning through automation
B.Removes dependency on cloud providers
C.Guarantees zero downtime during updates
D.Eliminates the need for cloud credentials
AnswerA

Terraform, as an Infrastructure as Code (IaC) tool, automates the entire infrastructure lifecycle, from initial provisioning to subsequent updates and deletion. By defining infrastructure in declarative configuration files, repetitive manual tasks are eliminated, significantly reducing the time required to deploy complex environments. This automation ensures consistency and dramatically accelerates the delivery of infrastructure resources compared to traditional manual processes, making provisioning much faster.

Why this answer

Faster provisioning through automation (A) is a core benefit because IaC enables quick and repeatable deployments via code, reducing manual effort and time. Option B is false: IaC does not remove dependency on cloud providers; you still rely on them for infrastructure services. Option C is false: IaC helps manage updates but does not guarantee zero downtime.

Option D is false: credentials are still required to authenticate with cloud providers.

336
MCQmedium

A team is using a module from the Terraform Registry. When they run 'terraform init', they receive an error stating that the module source cannot be downloaded. The module source is correct. What is the most likely cause?

A.The module output variable names are misspelled.
B.The provider version in the module conflicts with the root provider version.
C.The internet connection is down.
D.The user forgot to run 'terraform init' before 'terraform plan' or 'apply'.
AnswerC

Terraform init is the command responsible for downloading modules from their specified sources, including the public Terraform Registry. If the internet connection is down or unstable, Terraform cannot establish a connection to the registry to fetch the module's source code. This network connectivity issue directly prevents the initialization process from completing successfully, resulting in an error indicating a failure to download the module.

Why this answer

The error 'module source cannot be downloaded' occurs during terraform init when Terraform tries to fetch the module from the registry but cannot reach it. Since the module source is correct, the most likely cause is a network connectivity issue, such as the internet being down. The other options are less likely: A (output variable misspellings) would not prevent downloading; B (provider version conflict) would cause a different error later; D (forgotten init) is illogical because the error occurs while running init.

Exam trap

The trap is that candidates might think the issue is a typo in the source or a version conflict, but in this case the source is correct and the error occurs during init, so network issues are the primary suspect. Do not confuse this with forgetting to run init, as the error message itself indicates that init is being executed.

How to eliminate wrong answers

Option A is wrong because misspelled output variable names cause errors during 'terraform apply' when referencing outputs, not during 'terraform init' which handles module source downloads. Option B is wrong because provider version conflicts between root and module configurations are detected during 'terraform init' but result in a version constraint error, not a 'cannot be downloaded' error. Option C is wrong because while a down internet connection could prevent downloading, the question states the module source is correct and does not mention network issues; the most likely cause given the context is the missing 'terraform init' step.

337
MCQeasy

Refer to the exhibit. A developer runs `terraform apply` and the operation succeeds. Later, they manually terminate the EC2 instance through the AWS console. What will happen when the developer runs `terraform apply` again?

A.Terraform will recreate the EC2 instance and reassociate the Elastic IP
B.The Elastic IP will be disassociated and the instance will be recreated
C.Terraform will only recreate the EC2 instance without reassociating the Elastic IP
D.The apply will fail because the Elastic IP is still attached to the terminated instance
AnswerA

When an EC2 instance managed by Terraform is manually terminated, Terraform detects this as drift during the `plan` phase. The `aws_instance` resource will be marked for recreation. Since the `aws_eip_association` resource explicitly depends on the `id` of the EC2 instance, Terraform will also identify that the existing Elastic IP needs to be reassociated with the *new* instance. Consequently, Terraform will first provision a new EC2 instance and then update the `aws_eip_association` to link the existing Elastic IP to this newly created instance, restoring the desired state.

Why this answer

Terraform maintains the Elastic IP (EIP) association in its state file. When the EC2 instance is manually terminated outside of Terraform, the state still records the EIP as associated with that instance ID. On the next `terraform apply`, Terraform detects that the instance is missing (drift) and plans to recreate it, then reassociates the EIP to the new instance as defined in the configuration, ensuring the public IP remains attached.

Exam trap

The trap here is that candidates assume Terraform will fail or skip the EIP reassociation because the instance is terminated, but Terraform's state-driven reconciliation ensures it recreates and reassociates all resources to match the configuration, regardless of manual changes.

How to eliminate wrong answers

Option B is wrong because Terraform does not disassociate the EIP before recreating the instance; it simply reassociates it to the new instance after creation, as the state still holds the association. Option C is wrong because Terraform will reassociate the EIP because the configuration explicitly defines the `aws_eip_association` resource or `aws_eip` with `instance` attribute, and Terraform reconciles the full desired state. Option D is wrong because the EIP is not 'attached' to a terminated instance in a way that blocks apply; AWS allows EIPs to remain allocated and can be reassociated, and Terraform will not fail—it will proceed with recreation and reassociation.

338
MCQeasy

A developer runs `terraform init` in a directory containing Terraform configuration files. After initialization, they notice that a provider plugin was installed. Where are provider plugins stored locally by default?

A.In a `.terraform` subdirectory of the current working directory
B.In the system-wide plugin directory `/usr/share/terraform/plugins`
C.In the user's home directory under `~/.terraform.d/plugins`
D.In a temporary directory that is deleted after `terraform init` completes
AnswerA

Correct! Provider plugins are stored in `.terraform/providers/`.

Why this answer

By default, `terraform init` downloads and installs provider plugins into a `.terraform` subdirectory within the current working directory. This local directory acts as the plugin cache for the specific configuration, ensuring that each Terraform project has its own isolated set of provider binaries. The `.terraform` directory is created automatically during initialization and is managed by Terraform to store plugins, modules, and state data.

Exam trap

The trap here is that candidates confuse the legacy `~/.terraform.d/plugins` directory (used in Terraform versions before 0.13) with the modern default `.terraform` directory, leading them to select Option C instead of A.

How to eliminate wrong answers

Option B is wrong because Terraform does not use a system-wide plugin directory like `/usr/share/terraform/plugins`; provider plugins are stored per-project in the `.terraform` directory, not in a global system path. Option C is wrong because `~/.terraform.d/plugins` is a legacy plugin directory used in older versions of Terraform (prior to v0.13) and is not the default location for provider plugins in modern Terraform; the default is now the `.terraform` directory within the project. Option D is wrong because provider plugins are not stored in a temporary directory that is deleted after `terraform init` completes; they are persisted in the `.terraform` directory for subsequent `terraform plan` and `terraform apply` operations.

339
Matchingmedium

Match each Terraform meta-argument to its purpose.

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

Concepts
Matches

Create multiple instances from one resource block

Create multiple instances from a map or set of strings

Explicitly specify hidden resource dependencies

Control resource creation/destruction behavior

Select a non-default provider configuration

Why these pairings

Terraform meta-arguments are available across all resource types. depends_on declares hidden dependencies, count creates N copies, for_each creates copies from a collection, and lifecycle controls behavior like create_before_destroy. Common confusions include mixing the purposes of count and depends_on, or associating lifecycle with instance creation.

340
MCQmedium

A team uses a remote backend (S3) with state locking via DynamoDB. One team member runs terraform apply and it fails mid-way. Another team member immediately tries to run terraform plan. What is likely to happen?

A.The plan will run successfully because the lock is automatically released after failure.
B.The plan will run but the state file will be corrupted.
C.The plan will fail with an error indicating the state is locked.
D.The plan will run successfully and show any partial changes.
AnswerC

When a Terraform state is locked, any subsequent `terraform plan` command will fail with an explicit error message indicating that the state is currently locked. This mechanism, facilitated by DynamoDB for S3 backends, prevents concurrent operations that could lead to inconsistent infrastructure or state file corruption. The plan cannot proceed because it requires a stable, consistent view of the state, which the lock protects.

Why this answer

Terraform's remote backend with DynamoDB state locking acquires a lock at the start of `terraform apply` and does not release it until the operation completes or is explicitly unlocked. If the apply fails mid-way, the lock remains held (it is not automatically released on failure). Therefore, when another team member immediately runs `terraform plan`, the plan command will attempt to acquire the lock, fail, and return an error indicating the state is locked.

Exam trap

A common misconception is that a failed Terraform operation automatically releases the state lock, leading candidates to incorrectly choose Option A, when in fact the lock persists until explicit release or timeout.

How to eliminate wrong answers

Option A is wrong because the lock is not automatically released after failure; it remains held until the process terminates or the lock is manually removed via `terraform force-unlock`. Option B is wrong because the plan will not run at all—it will fail with a lock error—so there is no opportunity for state corruption from a concurrent plan. Option D is wrong because the plan will not run successfully; it will be blocked by the lock, and partial changes from the failed apply are not visible to a plan that cannot access the state.

341
MCQeasy

A DevOps team is integrating Terraform into a CI/CD pipeline using Jenkins. They want to ensure that the pipeline fails if the Terraform plan contains destructive changes. Which approach best achieves this?

A.Run terraform apply and parse the output for destroy messages.
B.Run terraform validate and check output for errors.
C.Run terraform destroy --target and fail if any resources are destroyed.
D.Run terraform plan -detailed-exitcode and fail pipeline if exit code is 2.
AnswerD

Executing `terraform plan -detailed-exitcode` is the correct approach because it generates an execution plan and signals the outcome through a specific exit code, ideal for CI/CD automation. An exit code of `2` explicitly indicates that a non-empty plan was generated, meaning there are proposed infrastructure changes. Failing the pipeline on this exit code ensures that any intended or unintended modifications are halted for review before an `apply` operation can proceed.

Why this answer

`terraform plan -detailed-exitcode` returns exit code 2 when there are any changes, including destructive changes. While it does not specifically detect only destructive changes, failing on any changes ensures that destructive changes are caught before apply, which is a common safety practice in CI/CD pipelines. Options A, B, and C are incorrect because A requires applying changes first, B does not detect changes, and C would actually destroy resources.

Exam trap

A common misconception is that `terraform plan -detailed-exitcode` only signals destructive changes; in reality, exit code 2 indicates any changes (additions, modifications, or deletions). However, failing on all changes is often acceptable to prevent unintended infrastructure changes.

How to eliminate wrong answers

Option A is wrong because parsing the output of `terraform apply` for destroy messages is unreliable (output format can change) and runs the apply before detecting destruction, which defeats the purpose of failing early. Option B is wrong because `terraform validate` only checks syntax and configuration validity, not whether the plan will destroy resources. Option C is wrong because `terraform destroy --target` is used to selectively destroy resources, not to detect destructive changes in a plan; it would actually perform destruction, not just report it.

342
MCQmedium

An organization uses Terraform Cloud for team collaboration. They have a workspace that manages production infrastructure. Due to a security policy, they must ensure that all changes go through a peer review process before they are applied. How can they enforce this requirement?

A.Enable 'apply on merge' and set the workspace to require approval before applying.
B.Require all changes to be submitted via a VCS pull request.
C.Use run triggers to automatically apply after a successful plan in another workspace.
D.Lock the workspace and only unlock it for approved changes.
AnswerA

Enabling 'apply on merge' configures the workspace to automatically initiate a Terraform run (plan) whenever code is merged into the configured VCS branch. By additionally setting the workspace to require explicit approval before applying, Terraform Cloud ensures that the planned changes are reviewed and approved by an authorized user within the TFC UI before they are actually provisioned. This combination provides a robust, automated, yet controlled deployment pipeline, aligning VCS changes with a mandatory human gate.

Why this answer

Enabling 'apply on merge' combined with requiring approval before applying enforces a peer review process: changes must be merged via a VCS pull request (triggering the plan), and then a separate approval step is needed before Terraform Cloud applies the changes. This ensures that no change is applied without explicit human approval after the plan is reviewed.

Exam trap

The trap here is that candidates confuse 'requiring a VCS pull request' (option B) with enforcing peer review, but without the approval step, the apply can still happen automatically after merge, bypassing the intended review gate.

How to eliminate wrong answers

Option B is wrong because requiring all changes to be submitted via a VCS pull request alone does not enforce peer review before apply; it only ensures changes are proposed via PR, but the apply could still happen automatically without manual approval. Option C is wrong because run triggers automatically apply after a successful plan in another workspace, bypassing any peer review or approval step for the target workspace. Option D is wrong because locking the workspace and only unlocking it for approved changes is a manual, error-prone process that does not enforce a consistent peer review workflow and does not integrate with VCS or Terraform Cloud's native approval mechanisms.

343
MCQmedium

Refer to the exhibit. A user applies this configuration and then runs 'terraform state list'. Which resource addresses would appear in the output?

A.aws_instance.web and aws_eip.web
B.aws_instance.web only
C.aws_instance.web and aws_eip.web (but aws_eip.web might not appear if the EIP fails to associate)
D.aws_eip.web only
AnswerA

Upon a successful `terraform apply`, all resources defined in the configuration and successfully provisioned by Terraform are recorded in the Terraform state file. Since both `aws_instance.web` and `aws_eip.web` are distinct resources specified in the configuration and are successfully created, both will have corresponding entries in the state file, reflecting their current attributes and IDs in the cloud provider.

Why this answer

The configuration defines two resources: aws_instance.web and aws_eip.web. Both will be in the state after apply. Option A lists both correct addresses.

344
MCQhard

An organization uses Terraform modules to provision multiple environments. They have a module 'vpc' that uses a for_each argument in the root module to create VPCs per environment. Each VPC requires a unique CIDR block passed via variable. What is the best practice to pass different CIDRs per instance?

A.Define a map variable with environment names as keys and CIDRs as values, then pass the entire map to the module.
B.Hardcode the CIDR within each module block.
C.Use a list variable for CIDRs and reference them with count.index and element().
D.Use a module output to fetch the CIDR from a data source.
AnswerA

This approach is ideal for provisioning multiple module instances, especially when using `for_each` on the module block. By defining a map variable, each key (e.g., "dev", "prod") can represent a distinct environment, and its corresponding value (the CIDR) can be passed directly to that specific module instance. This method ensures clear association, promotes reusability, and allows for dynamic scaling and configuration of environments without modifying the module's source code. It aligns perfectly with Terraform's declarative nature for managing distinct, yet similar, infrastructure components.

Why this answer

Using a map variable with environment names as keys and CIDRs as values allows Terraform's `for_each` to iterate over the map, creating one VPC per environment with its specified CIDR. This approach is clear, scalable, and maintains a direct key-value association. Option B (hardcoding) is not scalable and violates infrastructure as code best practices.

Option C uses `count.index` and `element()` on a list, which works but is less explicit and can lead to errors if list order changes. Option D is irrelevant because module outputs are read after creation and cannot be used to define input CIDRs.

Exam trap

The most common trap is to use `count` with a list and `element()` instead of `for_each` with a map. While both can work, `for_each` with a map is preferred because it creates a clear association between the key (environment name) and the value (CIDR), making the configuration more readable and less error-prone.

345
MCQmedium

A company uses Terraform with remote state stored in an S3 bucket. An operator accidentally runs 'terraform destroy' on a production workspace and wants to recover the state before the operation. What is the best course of action?

A.Re-run 'terraform apply' to recreate resources.
B.Restore the state file from a DynamoDB backup.
C.Use 'terraform state pull' to retrieve the last known state.
D.Restore the state file from the S3 bucket's versioning if enabled.
AnswerD

If S3 bucket versioning is enabled, every modification or deletion of the Terraform state file creates a new version, preserving previous states. This feature allows an administrator to easily retrieve and restore a previous, known-good version of the state file directly from the S3 bucket's version history. This is the most robust and recommended method for recovering from accidental state file deletion or corruption when using the S3 backend.

Why this answer

S3 bucket versioning, when enabled, automatically retains all versions of an object, including overwrites and deletions. By restoring the previous version of the state file (e.g., via the AWS console, CLI, or SDK), the operator can recover the exact state that existed before the 'terraform destroy' command was run, allowing Terraform to resume managing the infrastructure correctly.

Exam trap

A common misconception in the Terraform exam is that 'terraform state pull' can recover a previous state, but it only fetches the current state from the backend, which after a destroy is the empty state, not a historical version.

How to eliminate wrong answers

Option A is wrong because re-running 'terraform apply' without a valid state file would cause Terraform to attempt to recreate all resources from scratch, which may fail or create duplicate resources, and it does not recover the previous state. Option B is wrong because DynamoDB is used for state locking and consistency checks, not for storing state file backups; restoring from DynamoDB would not recover the state file itself. Option C is wrong because 'terraform state pull' retrieves the current state from the configured backend (the S3 bucket), which after 'terraform destroy' would reflect the destroyed state (empty or minimal), not the last known state before the operation.

346
MCQmedium

Refer to the exhibit. A developer runs `terraform plan -out=tfplan` and then `terraform apply "tfplan"`. During apply, network fails and apply is interrupted. The developer then runs `terraform apply` again (without a plan file). What will happen?

A.It will automatically use the previously saved plan file `tfplan`
B.It will fail because the state is locked from the previous apply
C.It will create a new plan and apply only the changes that are still needed
D.It will resume the previous apply from where it left off
AnswerC

When `terraform plan` is executed, it first performs a state refresh, comparing the current configuration against the actual state of resources in the cloud and the Terraform state file. If a previous `apply` was incomplete, this refresh will accurately identify which resources were successfully created or modified. Consequently, the new plan will only propose actions for the remaining resources that are either missing, require further modification, or need to be destroyed according to the desired state defined in the configuration.

Why this answer

When `terraform apply` is run without a plan file, Terraform automatically creates a new plan based on the current state and configuration, then applies only the changes that are still needed. Since the previous apply was interrupted, the state file reflects the partial progress, and the new plan will detect any remaining resources that still need to be created, updated, or destroyed, ensuring idempotent behavior.

Exam trap

HashiCorp often tests the misconception that Terraform can resume or automatically reuse a plan file after an interruption, when in fact it always re-plans from the current state to ensure consistency.

How to eliminate wrong answers

Option A is wrong because `terraform apply` without a plan file does not automatically use a previously saved plan file; the `-out=tfplan` flag is required to specify a plan file, and it must be explicitly passed as an argument. Option B is wrong because the state lock is released when the apply is interrupted (either by network failure or manual interruption), so the state is not locked; Terraform uses a lock in the backend (e.g., DynamoDB) that is released after the operation ends. Option D is wrong because Terraform does not resume a partially completed apply; it re-evaluates the configuration against the current state and creates a fresh plan, as the apply operation is not transactional and does not support checkpointing.

347
MCQeasy

A junior DevOps engineer is asked to explain the primary purpose of Terraform. Which statement best describes Terraform's purpose?

A.Terraform is a monitoring tool that tracks infrastructure changes.
B.Terraform is a scripting tool for automating manual tasks in cloud environments.
C.Terraform is a configuration management tool that installs and configures software on servers.
D.Terraform is an infrastructure provisioning tool that manages cloud and on-premises resources using declarative configuration.
AnswerD

Terraform is indeed a powerful infrastructure provisioning tool, enabling users to define and manage cloud and on-premises resources through a declarative configuration language. By describing the desired state of infrastructure in HashiCorp Configuration Language (HCL), Terraform automatically plans and applies the necessary changes to create, update, or destroy resources. This approach ensures consistent, repeatable deployments and efficient lifecycle management across diverse infrastructure providers.

Why this answer

Terraform is an infrastructure provisioning tool that uses declarative configuration (HashiCorp Configuration Language, HCL) to define and manage both cloud and on-premises resources. Its primary purpose is to provision infrastructure—such as virtual machines, networks, and storage—across multiple providers (e.g., AWS, Azure, GCP) by maintaining a desired state and applying changes via execution plans. Unlike configuration management or scripting tools, Terraform focuses on the lifecycle of infrastructure resources, not on configuring software within those resources.

Exam trap

In the HashiCorp Terraform exam, candidates often choose Option C because they confuse infrastructure provisioning (Terraform) with configuration management (e.g., Ansible, Chef, Puppet). Terraform's primary purpose is to provision infrastructure resources declaratively, not to configure software on servers.

How to eliminate wrong answers

Option A is wrong because Terraform is not a monitoring tool; it does not track infrastructure changes in real-time or provide metrics, alerts, or dashboards—those functions belong to tools like Prometheus or CloudWatch. Option B is wrong because Terraform is not a scripting tool for automating manual tasks; it uses declarative configuration, not imperative scripts, and its purpose is provisioning infrastructure, not automating ad-hoc operational tasks. Option C is wrong because Terraform is not a configuration management tool; it does not install or configure software on servers—tools like Ansible, Chef, or Puppet handle software configuration, while Terraform provisions the underlying infrastructure.

348
Multi-Selectmedium

Which THREE of the following are best practices for Terraform state management in a team environment?

Select 3 answers
A.Use separate state files for different environments (dev, prod)
B.Store state files in a version control repository
C.Enable state locking to prevent concurrent modifications
D.Store state files in a remote backend shared by the team
E.Manually edit the state file to correct drift
AnswersA, C, D

Utilizing distinct state files for each environment, such as development and production, is a critical best practice. This isolation significantly reduces the "blast radius" of potential errors or accidental changes, preventing a misconfiguration in one environment from impacting another. It ensures that infrastructure changes are applied only to their intended target, enhancing stability and operational safety.

Why this answer

Best practices for Terraform state management in a team environment include using separate state files for different environments (dev, prod) to isolate changes, enabling state locking to prevent concurrent modifications and conflicts, and storing state files in a remote backend shared by the team to enable collaboration and persistence. Option B (storing state in a version control repository) is not recommended because state files can contain sensitive data and are prone to conflicts when multiple team members apply changes concurrently. The correct options are A, C, and D.

349
MCQmedium

A user runs 'terraform plan' and it shows 'No changes. Infrastructure is up-to-date.' However, the user knows they added a new resource block to the configuration. What could explain this?

A.The resource block has a count parameter set to 0.
B.The resource block is inside an output block.
C.The user ran terraform validate before plan.
D.The resource block was added after running terraform fmt.
AnswerA

The `count` meta-argument in a resource block controls the number of identical resource instances Terraform should manage. When `count` is explicitly set to `0`, Terraform is instructed to manage zero instances of that specific resource. Consequently, if the resource does not currently exist in the state, `terraform plan` will show no changes because it is not intended to be created. If the resource *did* exist, setting `count` to `0` would cause `terraform plan` to propose its destruction.

Why this answer

When a resource block has `count = 0`, Terraform evaluates the count meta-argument and determines that zero instances of that resource should be created. As a result, the resource is effectively absent from the state, and `terraform plan` sees no changes because there is nothing to add, modify, or remove. This is a common cause of a 'No changes' result despite adding a new resource block.

Exam trap

HashiCorp often tests the subtle behavior of `count = 0` causing a resource to be completely ignored by Terraform, leading candidates to mistakenly think the resource would still appear in the plan as 'to be added' or that other workflow commands like `validate` or `fmt` are responsible for the discrepancy.

How to eliminate wrong answers

Option B is wrong because resource blocks cannot be placed inside output blocks; outputs are separate blocks that reference resource attributes, and Terraform would produce a syntax error, not a silent 'No changes'. Option C is wrong because `terraform validate` only checks configuration syntax and internal consistency; it does not affect the plan's detection of new resources. Option D is wrong because `terraform fmt` only reformats configuration files for style consistency; it does not alter the logical content or cause Terraform to ignore new resources.

350
Multi-Selectmedium

Which TWO of the following are best practices when using Terraform in a CI/CD pipeline? (Choose two.)

Select 2 answers
A.Run terraform apply automatically after plan
B.Use version control for configurations
C.Store state in the source repository
D.Use remote state with locking
E.Use terraform import to manage existing resources
AnswersB, D

Using version control systems like Git for Terraform configurations is a fundamental best practice for managing infrastructure as code. It provides a complete, auditable history of all infrastructure code changes, enabling teams to track who made what modifications and when. This facilitates seamless collaboration among multiple developers, allows for easy rollback to previous stable states, and supports robust auditing and compliance requirements by maintaining an immutable record of infrastructure evolution.

Why this answer

Remote state with locking ensures consistency and prevents corruption. Version control tracks changes. Storing state in source repo is not secure.

Auto-applying after plan is risky without approval. terraform import is for importing existing resources, not a CI/CD best practice.

351
MCQmedium

A developer runs `terraform apply` and receives the error: 'Error acquiring the state lock'. Another engineer is currently running `terraform plan`. What should the developer do?

A.Run terraform init to reinitialize the backend
B.Wait for the lock to be released automatically
C.Run terraform force-unlock with the lock ID
D.Run terraform plan with -lock=false to bypass the lock
E.Delete the lock file from the S3 bucket
AnswerB

The lock will be released when the other engineer's plan completes. Waiting is the safest approach.

Why this answer

Terraform uses a state locking mechanism to prevent concurrent modifications that could corrupt the state file. When another engineer is running `terraform plan`, the lock is held for the duration of the plan to ensure consistency. The lock will be automatically released once the plan completes or times out, so waiting is the appropriate action.

Exam trap

A common misconception is that running `terraform force-unlock` is the standard way to resolve a lock error. In reality, this command should only be used to clear orphaned locks after confirming no other process is using the state. When another engineer is actively running `terraform plan`, the lock will be released automatically upon completion.

How to eliminate wrong answers

Option A is wrong because `terraform init` reinitializes the backend configuration but does not release or bypass an active state lock; it would fail with the same lock error. Option C is wrong because `terraform force-unlock` should only be used as a last resort when the lock is orphaned (e.g., due to a crash), not when another legitimate process holds the lock. Option D is wrong because `terraform plan -lock=false` bypasses the lock for the plan itself, but the developer is trying to run `terraform apply`, and using `-lock=false` on apply risks state corruption if another operation modifies state concurrently.

Option E is wrong because deleting the lock file from the S3 bucket is a manual, unsafe action that can lead to state corruption; Terraform manages the lock via DynamoDB (for S3 backends) and deleting it does not properly release the lock.

352
Multi-Selecteasy

Which TWO statements accurately describe the purpose of Terraform? (Choose two.)

Select 2 answers
A.Terraform allows users to define infrastructure resources in a declarative configuration language.
B.Terraform can be used to create, modify, and destroy infrastructure resources.
C.Terraform is designed to work exclusively with AWS.
D.Terraform is a configuration management tool used for installing software on existing servers.
E.Terraform is a continuous integration and deployment tool.
AnswersA, B

Terraform utilizes HashiCorp Configuration Language (HCL) to allow users to express their desired infrastructure state in a human-readable format. This declarative approach means users describe *what* they want, such as a VPC or an EC2 instance, rather than providing imperative step-by-step instructions on *how* to create it. Terraform then intelligently determines the necessary actions to achieve this specified configuration, making infrastructure definition intuitive, versionable, and auditable.

Why this answer

Terraform uses HashiCorp Configuration Language (HCL) to define infrastructure as code in a declarative manner, meaning users specify the desired end state of resources without scripting the step-by-step process. This declarative approach allows Terraform to automatically determine the necessary actions to reach that state, making infrastructure management predictable and repeatable.

Exam trap

The trap here is that candidates often confuse Terraform's provisioning role with configuration management (Option D) or mistakenly assume it is cloud-specific (Option C), because many introductory examples focus on AWS, but Terraform's multi-provider support is a core design principle.

353
Multi-Selectmedium

Which TWO statements about Terraform provisioners are correct?

Select 2 answers
A.Provisioners can only be used with the 'local-exec' and 'remote-exec' provisioners.
B.Provisioners should be used as a last resort when no other Terraform resource or data source fits.
C.Provisioners are the primary way to configure resources after creation.
D.Provisioners run only once during initial creation by default.
E.Provisioners can be used with the 'null_resource' to run arbitrary actions.
AnswersB, E

This statement is correct and reflects a fundamental best practice in Terraform. Provisioners introduce imperative steps into a declarative infrastructure-as-code workflow, making configurations less idempotent and harder to manage. Terraform's strength lies in its ability to manage resources declaratively through providers, so provisioners should only be employed when no native resource, data source, or external configuration management tool can achieve the desired outcome.

Why this answer

Terraform provisioners are considered a last resort for tasks that cannot be accomplished with Terraform's declarative resource model. The official Terraform documentation explicitly states that provisioners should be used sparingly, as they introduce procedural logic and can cause state drift or failures that are hard to debug. This aligns with the principle of keeping configurations idempotent and relying on native resource attributes or data sources first.

Exam trap

HashiCorp often tests the misconception that provisioners are the standard way to configure resources, when in fact they are explicitly documented as a last resort, and candidates may also incorrectly assume that only 'local-exec' and 'remote-exec' exist.

354
MCQmedium

A company wants to use Terraform to manage resources across AWS and Azure. They need a single workflow that can apply changes to both providers. What is the best practice?

A.Use separate Terraform configurations for each provider
B.Use Terraform Cloud workspaces with different providers
C.Use Terraform workspaces to separate providers
D.Define both providers in a single configuration
AnswerD

Defining multiple providers within a single Terraform configuration allows for a truly unified infrastructure as code workflow. This approach enables the declaration and management of resources from different cloud providers (e.g., AWS and Azure) within the same set of `.tf` files, facilitating the creation of cross-provider dependencies and ensuring that `terraform plan` and `apply` operations consider the entire infrastructure holistically.

Why this answer

Terraform allows multiple providers to be defined in a single configuration, enabling a unified workflow to manage resources across AWS and Azure. By declaring both providers in the same root module, a single `terraform apply` can create, update, or destroy resources from both clouds in the correct order, leveraging Terraform's dependency graph to handle cross-provider dependencies. This is the recommended best practice for multi-cloud management with a single workflow.

Exam trap

The trap here is that candidates confuse workspaces (which isolate state for different environments) with provider separation, leading them to choose option C, when in fact workspaces do not change the provider definitions in a configuration.

How to eliminate wrong answers

Option A is wrong because using separate configurations for each provider would require separate `terraform apply` runs, breaking the single workflow requirement and introducing manual coordination or external orchestration. Option B is wrong because Terraform Cloud workspaces are designed to manage multiple environments (e.g., dev, prod) with the same provider configuration, not to separate providers; using different workspaces for different providers would still require separate configurations or state files, not a single workflow. Option C is wrong because Terraform workspaces are a state isolation mechanism for the same configuration, not a way to separate providers; they cannot change which providers are used in a single configuration, and using workspaces to separate providers would still require multiple configurations or manual switching.

355
MCQmedium

A module outputs a map of security group IDs keyed by name. In the root module, a resource needs to reference the security group ID for the name 'web-sg'. How should the root configuration access this value?

A.module.sg["web-sg"]
B.module.sg.web-sg
C.data.module.sg["web-sg"]
D.module.sg[0]
AnswerA

This syntax correctly accesses an element within a map output named "sg" from a module. Terraform maps are key-value collections, and individual values are retrieved by enclosing their string key, such as "web-sg", in square brackets. This method is the standard and explicit way to reference a specific item when the key is known, ensuring the correct security group ID is retrieved.

Why this answer

To access a map output from a module, use the standard map index syntax with brackets and the key name. Option A correctly uses module.sg["web-sg"] to retrieve the security group ID for 'web-sg'. Option B is invalid because dot notation cannot be used with a map key containing a hyphen.

Option C incorrectly uses data source syntax; module outputs are accessed via module.<name>.<output> directly. Option D uses an index, which is only valid for list-type outputs, not maps.

356
Multi-Selectmedium

Which TWO of the following are benefits of using Terraform Cloud Run Tasks?

Select 2 answers
A.Integrate with third-party tools for security scanning.
B.Simplify state management by offloading to Terraform Cloud.
C.Provide an approval gate for manual intervention.
D.Enforce custom policies before allowing an apply.
E.Automatically reduce costs by identifying unused resources.
AnswersA, D

Terraform Cloud Run Tasks enable seamless integration with third-party security scanning tools by allowing them to execute as part of the `terraform plan` or `terraform apply` workflow. These tasks can invoke external services to perform static analysis, vulnerability checks, or compliance scans on the planned infrastructure. If the security tool identifies issues, the Run Task can fail the Terraform run, preventing the deployment of non-compliant or insecure resources.

Why this answer

Terraform Cloud Run Tasks allow integration with third-party tools for security scanning, policy enforcement, or other validations during the plan/apply lifecycle. This is achieved by configuring run tasks that call external services via webhooks, enabling automated checks before provisioning proceeds.

Exam trap

The exam often tests the distinction between Run Tasks (automated, third-party integrations) and other Terraform Cloud features like Sentinel policies (custom policy enforcement) or manual approvals, leading candidates to confuse Run Tasks with approval gates or cost-saving features.

357
Multi-Selectmedium

Which four of the following statements about interacting with Terraform modules are correct? (Choose four.)

Select 4 answers
.A module can reference outputs from another module using the syntax module.<MODULE_NAME>.<OUTPUT_NAME>.
.The source attribute in a module block can reference a local file path, a Git repository, the Terraform Registry, or an HTTP URL.
.Terraform automatically downloads module dependencies when running terraform init, including nested modules from the root module.
.Module inputs are defined as variables in the module's root directory, and outputs are defined as output values that can be consumed by the calling configuration.
.To use a module from a private registry, you must always specify a version constraint in the source attribute of the module block.
.A module can be used to create resources only in the same provider configuration as the root module; it cannot define its own provider configurations.

Why this answer

This statement is correct because Terraform modules expose outputs that can be referenced by the calling configuration using the syntax `module.<MODULE_NAME>.<OUTPUT_NAME>`. This allows values computed inside a module to be used elsewhere in the root module, enabling modular composition and data sharing between modules.

Exam trap

HashiCorp often tests the distinction between `source` and `version` attributes in module blocks, and the misconception that modules cannot override provider configurations, which leads candidates to incorrectly select the two wrong options.

358
Multi-Selecteasy

Which THREE of the following are valid methods to manage Terraform state in a team environment? (Choose three.)

Select 3 answers
A.Storing state in a version control system
B.Using a remote backend like S3 with DynamoDB locking
C.Using Terraform workspaces with a remote backend
D.Storing state locally and sharing via network drive
E.Using Terraform Cloud to manage state
AnswersB, C, E

Using a remote backend like Amazon S3 for state storage, combined with DynamoDB for state locking, is a highly recommended and standard practice for collaborative Terraform environments. S3 provides durable, highly available, and versioned storage for the state file, while DynamoDB ensures mutual exclusion, preventing multiple users or processes from concurrently modifying the state and thereby avoiding corruption during `terraform apply` operations.

Why this answer

Options B, C, and E are all valid methods for managing Terraform state in a team environment. Option B uses a remote backend like S3 with DynamoDB locking to centralize state and prevent concurrent modifications. Option C leverages Terraform workspaces with a remote backend to isolate state for different environments while maintaining a single backend configuration.

Option E uses Terraform Cloud, which provides a managed state backend with built-in locking and versioning, simplifying team collaboration. Option A is incorrect because version control systems lack state locking and can lead to corruption. Option D is incorrect because storing state locally on a network drive introduces consistency and locking issues, making it unsuitable for concurrent team access.

Exam trap

HashiCorp often tests the misconception that version control systems like Git can safely manage Terraform state, but they lack the locking and atomicity required for concurrent team workflows.

359
MCQhard

Refer to the exhibit. What is the purpose of the data source?

A.To create a new AMI
B.To fetch an existing AMI ID
C.To define a variable
D.To output the AMI name
AnswerB

The primary purpose of this `data "aws_ami"` block is to dynamically query the AWS API and retrieve the unique identifier (ID) of an existing Amazon Machine Image that matches the specified criteria. By filtering for `ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*`, `architecture = "x86_64"`, and `virtualization_type = "hvm"`, and then selecting the latest image, the data source efficiently fetches the most current AMI ID for Ubuntu 20.04, making it available for use in other resource configurations.

Why this answer

In Terraform, a data source allows you to fetch or compute information from external sources that is not defined within the current configuration. The correct answer is B because the data source in the exhibit (e.g., `aws_ami`) is used to query and retrieve the ID of an existing AMI that matches specified filters, such as name, owner, or tag, without creating a new AMI. This enables dynamic referencing of pre-existing resources in your infrastructure.

Exam trap

A common trap in the Terraform exam is confusing data sources with resources: data sources are read-only and fetch existing information, while resources provision new infrastructure. Here, the `aws_ami` data source fetches an existing AMI ID, not creating a new one.

How to eliminate wrong answers

Option A is wrong because a data source does not create resources; it only reads existing data, whereas creating a new AMI would require a resource block like `aws_ami` with a `name` and `root_device_name`. Option C is wrong because defining a variable is done with a `variable` block, not a data source; data sources fetch runtime data, not define input variables. Option D is wrong because outputting the AMI name would require an `output` block referencing the data source's attribute, but the data source itself does not produce output; it only retrieves the AMI ID (or other attributes) for use elsewhere.

360
MCQeasy

A new user is learning Terraform. They write a configuration file and run terraform apply expecting to provision resources. However, they forgot to run terraform init first. What will happen?

A.Terraform will successfully apply the configuration because validate is enough.
B.Terraform will automatically run init before applying.
C.Terraform will prompt to run init and then continue.
D.Terraform will return an error stating that the working directory is not initialized.
AnswerD

When "terraform apply" is executed in a working directory that has not been initialized, Terraform cannot proceed with the requested operation. The "apply" command fundamentally depends on the presence of downloaded provider plugins, a configured state backend, and potentially installed modules, all of which are established during the "terraform init" phase. Consequently, Terraform will halt execution and output a specific error message, clearly indicating that the working directory requires initialization before the "apply" command can be successfully executed.

Why this answer

Terraform requires the working directory to be initialized with `terraform init` before any plan or apply can be executed. The `init` command downloads the necessary provider plugins and sets up the backend state storage. Without it, Terraform has no knowledge of the providers or state configuration, so it returns an error stating that the working directory is not initialized.

Exam trap

The trap here is that candidates may assume Terraform is self-sufficient and will auto-initialize, or confuse `validate` with `init`, not realizing that provider plugins and backend state are prerequisites for any execution.

How to eliminate wrong answers

Option A is wrong because `terraform validate` only checks syntax and internal consistency of the configuration, but does not download providers or initialize the backend; without `init`, apply will fail. Option B is wrong because Terraform does not automatically run `init` before `apply`; the user must explicitly run `init` first. Option C is wrong because Terraform does not prompt to run `init` and then continue; it simply returns an error and stops.

361
MCQmedium

A team is using Terraform workspaces to manage multiple environments with a single configuration. They store state in an S3 backend. Which statement about Terraform workspaces is true?

A.There is a limit of 10 workspaces per configuration
B.The default workspace is named "default" and cannot be deleted
C.Workspaces can only be used with the local backend
D.Workspaces automatically isolate variable values and provider configurations
AnswerB

The "default" workspace is a fundamental component of Terraform's workspace management, automatically created when `terraform init` is first run in a directory. This workspace serves as the initial and fallback environment for state management. It cannot be deleted using `terraform workspace delete default` because Terraform requires at least one active workspace to manage state, ensuring continuity and preventing accidental loss of the primary state file.

Why this answer

The default workspace in Terraform is always named 'default' and cannot be deleted. This workspace is created automatically when you initialize a configuration, and it serves as the baseline workspace for state management. The S3 backend fully supports workspaces, and each workspace stores its state under a separate path in the S3 bucket, enabling environment isolation without changing the configuration.

Exam trap

The trap here is that candidates often assume workspaces isolate variables and provider configurations, but Terraform workspaces only isolate state; variable values and provider configurations must be managed separately, which is a common source of confusion in the exam.

How to eliminate wrong answers

Option A is wrong because Terraform does not impose a hard limit of 10 workspaces per configuration; you can create up to 256 workspaces (depending on the backend) and the actual limit is determined by the backend's capabilities, not by Terraform itself. Option C is wrong because workspaces are supported by many backends, including S3, AzureRM, GCS, and Consul, not just the local backend; the local backend is only one of many. Option D is wrong because workspaces only isolate state files, not variable values or provider configurations; to isolate those, you must use separate directories, separate configurations, or separate variable files.

362
MCQeasy

Which of the following is NOT a valid backend type for storing Terraform state?

A.terraform cloud
B.local
C.kubernetes
D.s3
E.http
AnswerC

Kubernetes is not a supported Terraform backend for state storage.

Why this answer

Kubernetes is not a valid backend type for storing Terraform state. Terraform backends determine where state is stored and how operations are executed; the officially supported backends include local, remote backends like S3, HTTP, and Terraform Cloud, but Kubernetes is not among them. While Kubernetes can be used to run Terraform in a pod, it does not serve as a state storage backend.

Exam trap

A common misconception is that Kubernetes can be used as a Terraform backend because it is a container orchestration platform, but Terraform backends are specific storage mechanisms (e.g., local, S3, HTTP, Terraform Cloud) and Kubernetes is not one of them.

How to eliminate wrong answers

Option A is wrong because Terraform Cloud is a fully supported remote backend that stores state and runs operations, with features like state locking and versioning. Option B is wrong because local is the default backend that stores state on the local filesystem, and is valid for single-user or testing scenarios. Option D is wrong because S3 is a standard remote backend that stores state in an AWS S3 bucket, often paired with DynamoDB for locking.

Option E is wrong because HTTP is a valid backend that stores state via a RESTful HTTP endpoint, allowing custom state storage solutions.

363
Multi-Selecthard

Which of the following are valid ways to pass input variables to a Terraform configuration? (Select all that apply.)

Select 3 answers
A.Use the '-var' flag on the command line to set a single variable.
B.Create a file named 'terraform.tfvars' with variable assignments.
C.Use the '-var-file' flag to specify a JSON file with variable definitions.
AnswersA, B, C

The '-var' flag sets a single variable, but the question asks for ways to pass variables (multiple ways). This is a valid way, but it's not a file. The question says 'valid ways to pass input variables' and does not specify 'file'. So both A and B are correct? Let's rethink: Option B: '-var-file' is indeed a valid way to pass a file. Option C: '-var' is also valid. But the instruction says exactly 2 correct. I need to ensure only two are correct. I'll adjust: Option B should be something else that is incorrect. Let me correct the options.

Why this answer

Terraform automatically loads variable definitions from a file named 'terraform.tfvars' (or 'terraform.tfvars.json') in the current directory when you run a plan or apply. This allows you to define input variables in a structured, reusable way without needing to specify them on every command invocation.

Exam trap

HashiCorp often tests the distinction between 'terraform.tfvars' (auto-loaded) and '-var-file' (explicitly loaded), and the trap here is that candidates may think '-var-file' can load any JSON file, but Terraform requires the file to have a .tfvars or .tfvars.json extension and proper variable assignment syntax.

How to eliminate wrong answers

Option A is wrong because while the '-var' flag is valid for passing a single variable, the question asks for valid ways to pass input variables to a configuration, and the '-var' flag is indeed a valid method — but it is not listed as correct in the answer set because the question requires selecting TWO correct options, and A is actually a valid method; however, the provided correct answer set includes B and C, so A is considered wrong in this context because the question's intended correct pair is B and C. Option C is wrong because the '-var-file' flag is used to specify a file containing variable definitions, but the file must be in HCL format (with .tfvars extension) or JSON format (with .tfvars.json extension); specifying a plain JSON file without the correct extension or using '-var-file' with a JSON file that is not properly formatted as Terraform variable definitions is not a valid way to pass input variables.

364
MCQmedium

An organization uses a remote backend (S3) with DynamoDB for state locking. A developer runs `terraform plan` and gets the error: "Error acquiring the state lock: ConditionalCheckFailedException". What is the most likely cause?

A.Another Terraform process is currently holding the state lock
B.The S3 bucket does not exist
C.The DynamoDB table is not yet created
D.The Terraform version is incompatible with the backend
AnswerA

When Terraform attempts to acquire a state lock using DynamoDB, it performs a conditional write operation to a specific item in the lock table. A "conditional check fails" error specifically indicates that this write could not proceed because the expected conditions were not met, typically meaning another process has already written a lock item or the version ID does not match. This mechanism prevents concurrent state modifications, signifying that another Terraform process is actively holding the lock to protect state integrity and avoid race conditions.

Why this answer

The error 'ConditionalCheckFailedException' occurs when Terraform attempts to acquire a lock in DynamoDB but the conditional write fails because the lock item already exists with a different lock ID. This indicates another Terraform process (or a stale lock) is currently holding the state lock, preventing concurrent operations to protect state integrity.

Exam trap

HashiCorp often tests the distinction between DynamoDB-specific errors (ConditionalCheckFailedException) versus S3 or configuration errors, trapping candidates who confuse state locking failures with backend connectivity issues.

How to eliminate wrong answers

Option B is wrong because if the S3 bucket does not exist, Terraform would return an error like 'NoSuchBucket' or 'AccessDenied', not a DynamoDB conditional check failure. Option C is wrong because if the DynamoDB table is not created, Terraform would throw a 'ResourceNotFoundException' when trying to write the lock item, not a conditional check failure. Option D is wrong because version incompatibility typically causes backend configuration errors or unsupported features, not a DynamoDB conditional check exception.

365
MCQhard

Given the following Terraform configuration: resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" } If you change the instance_type to "t2.small" and run terraform apply, what will happen?

A.The plan will fail due to missing variables.
B.The instance will be destroyed and recreated.
C.The instance will be modified in-place, potentially causing a reboot.
D.The instance type will be changed without downtime.
AnswerC

The tilde symbol (`~`) in a Terraform plan output explicitly indicates that an existing resource attribute will be modified in-place without destroying and recreating the entire resource. When changing an AWS EC2 `instance_type`, the underlying cloud provider typically performs a stop and start operation on the instance to apply the new configuration. This stop/start cycle inherently causes a temporary interruption in service, which often manifests as a system reboot from the operating system's perspective.

Why this answer

Modifying an instance's type is an in-place update in Terraform (shown as a tilde ~ in the plan). This update typically requires a stop and start of the instance, which causes a reboot but not a full destroy and recreate. Option A is incorrect because the question does not indicate any missing variables; the configuration is assumed to be valid.

Option B is incorrect because a destroy and recreate would be shown as a -/+ in the plan, whereas an instance type change is an in-place update. Option D is incorrect because changing the instance type usually requires a reboot, causing downtime, so there is no 'no downtime' guarantee.

366
MCQeasy

A developer wants to use the output of one Terraform configuration as input to another. Which Terraform feature should they use?

A.local values
B.remote state data source
C.data sources
D.variables
AnswerB

The `terraform_remote_state` data source is specifically designed to read outputs from a Terraform state file stored in a remote backend. By configuring this data source with the appropriate backend type and configuration, a separate Terraform configuration can securely access and utilize the output values defined in another, previously applied, Terraform configuration. This enables modularity and dependency management across distinct infrastructure deployments.

Why this answer

The remote state data source (terraform_remote_state) is the correct feature because it allows one Terraform configuration to read the output values from another configuration's state file, enabling cross-configuration data sharing without manual intervention. This is the idiomatic way to consume outputs from a separate Terraform root module, such as retrieving a VPC ID from a networking configuration to use in an application configuration.

Exam trap

Candidates often mistakenly choose 'data sources' as a catch-all answer, but the terraform_remote_state data source specifically reads outputs from another Terraform state, not provider resources.

How to eliminate wrong answers

Option A is wrong because local values are scoped to a single Terraform configuration and cannot read outputs from another configuration's state. Option C is wrong because while data sources fetch information from providers (e.g., AWS, Azure), they do not read Terraform state files from other configurations; terraform_remote_state is a specialized data source for that purpose. Option D is wrong because variables are inputs to a configuration, not a mechanism for consuming outputs from a separate configuration's state.

367
MCQhard

In Terraform, the `terraform plan` command compares the current state with the configuration. This is an example of which IaC principle?

A.Version control integration
B.Continuous delivery
C.Modular architecture
D.Desired state enforcement
AnswerD

The `terraform plan` command is central to desired state enforcement in Terraform. It meticulously compares the infrastructure's current state, as recorded in the state file and potentially observed live, against the desired configuration defined in the Terraform files. The resulting plan details all the actions (creations, updates, destructions) required to reconcile any discrepancies, thereby showing precisely what is needed to achieve the desired infrastructure state.

Why this answer

The `terraform plan` command compares the current state (what is deployed) with the configuration (what is declared) and computes the changes needed to align the real-world infrastructure with the declared configuration. This is the essence of desired state enforcement: the tool continuously reconciles the actual state toward the user-defined desired state, rather than executing imperative steps. Option D is correct because Terraform's core loop—plan, apply, refresh—is built around this declarative, state-driven model.

Exam trap

HashiCorp often tests the distinction between declarative (desired state enforcement) and imperative (step-by-step) approaches, and the trap here is that candidates confuse the `plan` command's output with a simple diff report rather than recognizing it as the core mechanism of Terraform's declarative state reconciliation model.

How to eliminate wrong answers

Option A is wrong because version control integration refers to storing Terraform configurations in Git or similar systems, not to the behavior of `terraform plan`. Option B is wrong because continuous delivery is a software engineering practice for automating deployments through pipelines, not a principle demonstrated by a single command that compares state. Option C is wrong because modular architecture is about organizing configurations into reusable modules (e.g., using `module` blocks), which is unrelated to the state-comparison mechanism of `terraform plan`.

368
MCQhard

In the configuration, what is the likely result of the resource block 'aws_flow_log'?

A.Terraform will error because for_each cannot be used with module outputs.
B.The resource will be created only for the last module instance due to overwriting.
C.It will create one flow log per network module instance, using the vpc_id output from each.
D.It will create one flow log for each VPC using a count based on length of module.networks.
AnswerC

for_each = module.networks iterates over each module instance, allowing access to its outputs via each.value.

Why this answer

`for_each` in Terraform iterates over each element in a map or set, creating one resource instance per element. When `for_each` is used with `module.networks`, it iterates over each module instance, and `each.value.vpc_id` references the `vpc_id` output from that specific module instance. This results in one `aws_flow_log` resource per network module instance, each associated with its respective VPC.

Exam trap

The TF-003 exam often tests the distinction between `for_each` and `count` in module contexts, trapping candidates who assume `for_each` cannot consume module outputs or that `count` is the only way to iterate over module instances.

How to eliminate wrong answers

Option A is wrong because `for_each` can be used with module outputs; Terraform supports `for_each` on any collection, including a map derived from module outputs, as long as the output values are known during planning. Option B is wrong because `for_each` does not overwrite resources; it creates distinct resource instances for each key in the map, unlike `count` which uses integer indices and can cause confusion with ordering. Option D is wrong because using `count` with `length(module.networks)` would create a flat list of resources indexed by number, but the correct approach for mapping to specific module instances is `for_each` with a map keyed by a unique identifier (e.g., module.networks).

369
MCQmedium

A DevOps engineer manages infrastructure with Terraform using an S3 backend with DynamoDB locking. During a `terraform apply`, the engineer's network connection drops. After reconnecting, they run `terraform plan` and get an error: "Error acquiring the state lock." The lock is from the previous session. The engineer has verified that no other operations are running. What is the appropriate next step to proceed?

A.Delete the DynamoDB table and recreate it
B.Wait 15 minutes for the lock to expire automatically
C.Use `terraform force-unlock <lock_id>` to remove the stale lock
D.Run `terraform init` to reset the backend connection
AnswerC

When a Terraform operation fails or is interrupted, it can leave behind a stale state lock in the remote backend, such as an entry in the DynamoDB table. The `terraform force-unlock <lock_id>` command is specifically designed to remove such persistent, but no longer active, lock entries. By providing the unique `lock_id`, this command directly instructs the backend to clear the specific lock, enabling subsequent Terraform operations to proceed safely.

Why this answer

`terraform force-unlock` is the intended mechanism to manually remove a stale lock from the DynamoDB table when the process that held the lock has terminated abnormally. The engineer has confirmed no other operations are running, so the lock is orphaned and safe to remove. This command requires the specific lock ID, which is provided in the error message.

Exam trap

Candidates often mistakenly think that Terraform locks have a timeout or that `terraform init` can reset backend state issues, leading them to choose waiting or reinitializing instead of using the explicit `force-unlock` command.

How to eliminate wrong answers

Option A is wrong because deleting and recreating the DynamoDB table would destroy all lock records and potentially other metadata, and is an unnecessarily destructive action that violates infrastructure-as-code best practices. Option B is wrong because Terraform's DynamoDB locks do not have a built-in expiry timeout; they persist until explicitly released or removed, so waiting 15 minutes would not resolve the issue. Option D is wrong because `terraform init` reinitializes the backend configuration and downloads providers, but does not interact with or release existing locks in DynamoDB.

370
MCQhard

Which Terraform feature helps manage dependencies between resources?

A.data source
B.output
C.depends_on
D.provisioner
AnswerC

The `depends_on` meta-argument is Terraform's explicit mechanism for defining a direct dependency between resources that cannot be inferred automatically through attribute references. When Terraform's implicit dependency graph, built by referencing resource attributes, is insufficient to ensure a specific creation, update, or destruction order, `depends_on` forces one resource to be fully created or updated before another resource begins its lifecycle operations. This ensures proper sequencing for complex or non-obvious inter-resource relationships.

Why this answer

The `depends_on` argument explicitly specifies dependencies, ensuring resources are created or destroyed in the correct order.

371
MCQmedium

A Terraform configuration uses a module from the Terraform Registry. The module's documentation states it requires Terraform version >= 0.14. The team is using Terraform 0.12. What should the developer do to use this module?

A.Upgrade Terraform to a supported version.
B.Fork the module and modify it to be compatible.
C.Add a version constraint in the module block to pin to an older compatible version.
D.Use the module as-is; the version requirement is only a recommendation.
AnswerA

Terraform modules declare their minimum required Terraform version using the `terraform` block's `required_version` argument. If the current Terraform CLI version is older than this specified requirement, the `terraform init` command will fail with an explicit error, preventing any further operations. Upgrading the Terraform CLI to a version that meets or exceeds the module's `required_version` is the most straightforward and intended solution to resolve this compatibility issue, allowing the configuration to initialize successfully.

Why this answer

The module explicitly requires Terraform >= 0.14, and the team is using Terraform 0.12, which lacks features or syntax changes introduced in later versions. Terraform modules from the Registry enforce version constraints via the `required_version` setting; using an incompatible version will cause a clear error during `terraform init` or `terraform plan`. The only reliable solution is to upgrade Terraform to a version that satisfies the module's requirement.

Exam trap

A common misconception is that version constraints in a module block can override the module's own required_version, but in Terraform the module's internal constraint is absolute and cannot be bypassed by the caller.

How to eliminate wrong answers

Option B is wrong because forking and modifying the module is unnecessary overhead and introduces maintenance burden; the module's version requirement is a hard constraint, not a suggestion, and modifying it could break functionality or introduce subtle bugs. Option C is wrong because adding a version constraint in the module block cannot override the module's own `required_version` setting; the constraint in the calling configuration only controls which module versions to fetch, not the Terraform version compatibility. Option D is wrong because the version requirement is not a recommendation—it is enforced by Terraform's version resolution logic; using the module as-is with Terraform 0.12 will result in an error during initialization.

372
MCQhard

A company uses Terraform Cloud with a remote state backend and runs infrastructure as code through a CI/CD pipeline (GitHub Actions). The pipeline executes 'terraform plan' and 'terraform apply' using a service account with appropriate permissions. Recently, the team introduced a Sentinel policy to enforce that all AWS resources have mandatory tags (Environment, Owner, Project). The policy passes when runs are triggered manually from the Terraform Cloud UI, but fails consistently when the CI/CD pipeline runs the plan. The infrastructure configuration files are identical in both cases. The team verifies that the service account used by CI/CD has the same workspace permissions as the UI user. What is the most likely cause of the failure?

A.The Sentinel policy is checking the wrong workspace.
B.The CI/CD pipeline is using a different set of variables that override the tags.
C.The Sentinel policy is configured to fail on all plans regardless of compliance.
D.The CI/CD pipeline is using an older version of Terraform that does not support Sentinel.
AnswerB

Terraform Cloud allows variables to be set at various levels, with a specific order of precedence. A CI/CD pipeline often initiates runs via the Terraform Cloud API, which can include `TF_VAR_` environment variables or `terraform.tfvars` content that overrides variables configured directly in the workspace UI. If the pipeline injects different tag values through these mechanisms, the resulting Terraform plan will differ, causing the Sentinel policy to detect a non-compliant resource configuration.

Why this answer

The Sentinel policy enforces mandatory tags on AWS resources. When the CI/CD pipeline runs, it may use different variable definitions (e.g., from environment variables or variable files) that override the Terraform variables for tags. If the pipeline sets missing or incorrect tag values, the policy fails.

Manual UI runs likely use the workspace's default variable values, which satisfy the policy. Since the configuration files are identical, the discrepancy is due to variable overrides from the pipeline, making Option B correct.

373
MCQmedium

A team uses an S3 backend with DynamoDB locking. They accidentally delete the DynamoDB table used for state locking. What is the immediate consequence?

A.Terraform commands that require state locking will fail with a locking error.
B.State operations will continue without locking, risking corruption.
C.Terraform will automatically create a new DynamoDB table.
D.The state file will be migrated to local storage.
AnswerA

When the configured DynamoDB table for state locking is unavailable or missing, Terraform cannot acquire the necessary lock before executing state-modifying commands like `terraform apply` or `terraform plan`. This immediately results in a locking error, preventing any operation that could potentially corrupt the remote state file. Terraform prioritizes state integrity by failing explicitly rather than proceeding unsafely.

Why this answer

When the DynamoDB table is deleted, Terraform cannot acquire or release locks, so any command needing locking (apply, plan, destroy) will fail. Option A is correct. Option B is incorrect because Terraform will not proceed without lock; it returns an error.

Options C and D are not automatic behaviors.

374
MCQhard

A module requires a specific provider configuration with aliases. The root module has two provider configurations: provider 'aws' (default) and provider 'aws' with alias = 'uswest'. The module uses the us-west alias. How should the module block be configured to ensure the correct provider is used?

A.Set required_providers inside the module to include the alias.
B.Use the providers argument in the module block: providers = { aws = aws.uswest }.
C.Include a provider block inside the module block with alias = 'uswest'.
D.Do nothing; Terraform automatically uses the default provider.
AnswerB

The `providers` argument within a `module` block is the correct and explicit mechanism for passing specific provider configurations from the calling module to a child module. By using `providers = { aws = aws.uswest }`, the child module's expectation for an `aws` provider is satisfied by the `uswest` aliased `aws` provider configuration defined in the root module. This ensures the module operates with the intended, aliased provider configuration.

Why this answer

Terraform uses the `providers` argument in a module block to explicitly map provider configurations from the root module into the module. Since the root module has two AWS provider configurations (default and `uswest` alias), and the module requires the us-west alias, the mapping `providers = { aws = aws.uswest }` ensures the module uses the aliased provider. Without this explicit mapping, Terraform would default to the root module's default provider, which may not have the correct region or settings.

Exam trap

A common misconception is that required_providers inside a module can select an alias, when in fact it only declares provider requirements and version constraints.

How to eliminate wrong answers

Option A is wrong because `required_providers` inside a module only declares which providers the module needs and their version constraints, but does not map root-level aliased providers into the module; it cannot specify which alias to use. Option C is wrong because you cannot nest a `provider` block inside a `module` block; provider blocks are only valid at the top level of a configuration or in a `terraform` block, and modules inherit providers from the calling module. Option D is wrong because Terraform does not automatically use the default provider when a module requires a specific alias; without explicit mapping, the module will use the default provider, which may not match the intended region or configuration.

375
MCQmedium

A company wants to manage its infrastructure as code using Terraform. The team has a mix of on-premises servers and cloud resources in AWS and Azure. Which of the following best describes Terraform's purpose in this scenario?

A.Terraform is a configuration management tool for installing software on existing servers.
B.Terraform is a cloud-specific orchestration tool that only works with AWS.
C.Terraform is a monitoring and logging tool for cloud resources.
D.Terraform is an infrastructure-as-code tool for provisioning and managing any infrastructure across multiple providers.
AnswerD

This statement accurately describes Terraform's fundamental purpose. As an infrastructure-as-code tool, Terraform enables users to define infrastructure declaratively using HCL, allowing for version-controlled, repeatable, and automated provisioning and management of resources. Its robust provider framework supports a vast array of platforms, including major cloud providers, on-premises virtualization, and SaaS applications, facilitating consistent infrastructure deployment across diverse environments.

Why this answer

Terraform is explicitly designed as an infrastructure-as-code tool that uses declarative configuration files to provision and manage resources across multiple providers, including on-premises servers (via providers like vSphere or Hyper-V) and cloud platforms like AWS and Azure. Its provider model allows it to abstract away the underlying APIs, making it provider-agnostic and suitable for hybrid environments.

Exam trap

HashiCorp often tests the misconception that Terraform is a configuration management tool (like Ansible) or that it is limited to a single cloud provider, so candidates must remember that Terraform is a provisioning tool for infrastructure resources across multiple providers, not for software configuration or monitoring.

How to eliminate wrong answers

Option A is wrong because Terraform is not a configuration management tool like Ansible, Puppet, or Chef; it does not install software or manage state on existing servers—it provisions infrastructure resources. Option B is wrong because Terraform is not cloud-specific; it supports over 100 providers, including AWS, Azure, GCP, and on-premises solutions, through its plugin-based architecture. Option C is wrong because Terraform does not perform monitoring or logging; tools like CloudWatch, Azure Monitor, or Prometheus handle those tasks, while Terraform focuses on the lifecycle (create, read, update, delete) of infrastructure resources.

Page 4

Page 5 of 6

Page 6

All pages