Courseiva

HashiCorp Terraform Associate TF-004 (TF-004) — Questions 1–75

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

Page 1 of 6

Page 2
1
MCQeasy

A company wants to manage both on-premises and cloud infrastructure with a single tool. Which feature of Terraform makes this possible?

A.Provider plugins
B.State files
C.Provisioners
D.Workspaces
AnswerA

Provider plugins let Terraform interact with distinct APIs through a common workflow. Separate providers for on-premises platforms and cloud services translate Terraform configuration into each environment's native calls, so one tool and language manage both infrastructures, satisfying the single-tool requirement.

Why this answer

Terraform uses provider plugins as the abstraction layer that allows it to interact with different infrastructure platforms. Each provider plugin (e.g., AWS, Azure, vSphere) implements the necessary API calls to manage resources on that platform. By using multiple provider plugins in the same configuration, Terraform can manage both on-premises infrastructure (e.g., VMware vSphere) and cloud infrastructure (e.g., AWS EC2) with a single tool.

Exam trap

The trap here is that candidates often confuse provider plugins with state files or workspaces, thinking that state files enable multi-cloud management, when in fact provider plugins are the core mechanism that allows Terraform to interface with any infrastructure API.

How to eliminate wrong answers

Option B is wrong because state files store the mapping between Terraform resources and real-world infrastructure, but they do not enable multi-platform management; they are a data store, not an integration mechanism. Option C is wrong because provisioners are used to execute scripts or configuration management tools on local or remote machines after resource creation, not to manage different infrastructure platforms. Option D is wrong because workspaces allow you to manage multiple distinct sets of infrastructure (e.g., dev, staging, prod) within the same configuration, but they do not provide the ability to interact with different infrastructure providers.

2
MCQhard

A team uses Terraform with remote state in an S3 backend and DynamoDB for state locking. A user runs 'terraform apply' and receives the error: 'Error acquiring the state lock'. The lock info shows a lock ID and caller. What is the best immediate course of action?

A.Check if another Terraform process is running; if not, use 'terraform force-unlock' with the lock ID.
B.Delete the state file from S3 and re-run apply.
C.Manually delete the DynamoDB lock table item.
D.Wait for 15 minutes and re-run apply.
AnswerA

This is the correct and safest approach. Before attempting to unlock, it's crucial to confirm that no legitimate Terraform process is actively holding the lock, which could lead to state corruption if prematurely released. If the lock is indeed orphaned due to a crashed or terminated process, `terraform force-unlock <LOCK_ID>` explicitly releases it, allowing subsequent operations to proceed without manual intervention in the backend.

Why this answer

The error indicates a state lock is held, typically by another Terraform process or a stale lock. The best immediate course is to verify no other process is running (e.g., via 'ps' or task manager), then use 'terraform force-unlock -lock-id=<LOCK_ID>' to release the lock. This is the safe, documented procedure that preserves the state file and DynamoDB lock table integrity.

Exam trap

HashiCorp often tests the misconception that deleting the state file or DynamoDB item is a valid fix, but the trap here is that candidates confuse state file management with lock management, leading them to choose destructive actions instead of the proper unlock command.

How to eliminate wrong answers

Option B is wrong because deleting the state file from S3 destroys all tracked infrastructure state, causing Terraform to lose track of resources and potentially attempt to recreate everything, leading to duplication or errors. Option C is wrong because manually deleting the DynamoDB lock table item bypasses Terraform's lock consistency checks and can corrupt the lock state, leaving the lock ID in an inconsistent state. Option D is wrong because waiting 15 minutes does not address the root cause; if the lock is stale, it will persist indefinitely, and if another process is running, it may still hold the lock after waiting.

3
MCQeasy

A team needs to share a Terraform module across multiple projects within their organization. What is the best practice?

A.Use a remote module source such as a Git repository.
B.Copy the module code into each project's directory.
C.Use 'terraform state push' to share state.
D.Use workspace variables to store module code.
AnswerA

Leveraging a remote Git repository as a module source allows teams to centralize module definitions, promoting reusability and consistency across multiple projects. This approach enables robust version control, ensuring that all consuming projects can pin to specific module versions, facilitating controlled updates and preventing unexpected changes. Terraform's `source` attribute directly supports Git URLs, making this a standard and highly effective method for module sharing and management.

Why this answer

Using a remote module source such as a Git repository is the best practice because it allows the module to be versioned, centrally maintained, and consumed by multiple projects without duplication. Terraform's module system supports sources like Git, Mercurial, and HTTP URLs, enabling teams to pin specific versions via tags or refs, ensuring consistency across environments.

Exam trap

A common pitfall is confusing state sharing or workspaces with module distribution. State and workspaces are runtime constructs, not code sharing mechanisms, whereas a remote module source allows centralized version control.

How to eliminate wrong answers

Option B is wrong because copying module code into each project's directory leads to configuration drift, duplicated maintenance, and violates the DRY (Don't Repeat Yourself) principle; Terraform modules are designed to be sourced remotely, not copied. Option C is wrong because 'terraform state push' is used to manually upload state to a configured backend, not to share module code; state files contain resource metadata, not module definitions. Option D is wrong because workspace variables store input values for workspaces, not module code; module code must be sourced from a defined module source, not from variable assignments.

4
MCQeasy

A team is using a shared backend for Terraform state. After running terraform apply, the state file is locked for an extended period, causing other team members to fail with 'Error acquiring the state lock'. What is the most likely cause?

A.A previous terraform apply command was interrupted or crashed, leaving a stale lock.
B.Another team member is actively running terraform apply on the same state.
C.The backend configuration was changed without running terraform init.
D.The state file contains resources that no longer exist in the cloud provider.
AnswerA

When a `terraform apply` command is interrupted unexpectedly, such as due to a process crash, network failure, or manual termination, Terraform might fail to release the state lock it acquired at the beginning of the operation. This leaves a "stale" lock entry in the backend, preventing any subsequent Terraform commands from acquiring the necessary lock to modify the state. Terraform's state locking mechanism is designed to prevent concurrent modifications, so a persistent stale lock effectively blocks all further state-modifying operations until it is manually released, directly causing an "Error acquiring state lock" message.

Why this answer

Terraform uses a locking mechanism (typically via DynamoDB for AWS S3 backends) to prevent concurrent state modifications. If a `terraform apply` is interrupted or crashes, the lock may not be released, leaving a stale lock entry. This causes subsequent operations to fail with 'Error acquiring the state lock' until the lock is manually removed or expires (if TTL is configured).

Exam trap

HashiCorp often tests the distinction between a legitimate lock held by another user (Option B) and a stale lock from a crashed process (Option A), where candidates mistakenly think any lock error means someone else is actively working.

How to eliminate wrong answers

Option B is wrong because if another team member is actively running `terraform apply`, the lock is legitimate and not 'stale' — the error message is expected behavior, not a misconfiguration or bug. Option C is wrong because changing the backend configuration without `terraform init` would cause a backend initialization error, not a state lock error; the lock mechanism is backend-specific and would not be triggered by a config mismatch. Option D is wrong because resources that no longer exist in the cloud provider cause drift or refresh errors during `terraform plan` or `apply`, but do not affect the state locking mechanism, which operates at the backend level independently of resource state.

5
Multi-Selecthard

Which two statements accurately describe the difference between declarative and imperative IaC approaches? (Choose two.)

Select 2 answers
A.Imperative is only used for scripting, not IaC
B.Declarative tools are always faster than imperative tools
C.Declarative focuses on the desired outcome, while imperative specifies step-by-step commands
D.Imperative can lead to configuration drift because steps may cause unintended states
E.Declarative eliminates the need for idempotency
AnswersC, D

Declarative IaC defines the target end state and lets the tool determine execution, whereas imperative IaC encodes explicit sequential commands. This outcome-versus-steps axis is the defining distinction between the two approaches, directly matching the question's requirement.

Why this answer

Option C is correct because declarative IaC (e.g., Terraform HCL, CloudFormation templates) defines the desired end state of the infrastructure and lets the tool determine the execution path, whereas imperative IaC (e.g., shell scripts, AWS CLI command sequences) explicitly lists the ordered commands needed to reach that state. Option D is correct because imperative approaches execute fixed steps without inherently reconciling actual versus desired state, so re-running or partially failing scripts can leave resources in unintended configurations, producing configuration drift. Option A is wrong because imperative techniques are widely used in IaC, such as provisioning with AWS CLI or Ansible ad-hoc commands.

Option B is wrong because speed depends on implementation, provider APIs, and parallelism, not on whether the approach is declarative or imperative. Option E is wrong because declarative tools still rely on idempotency mechanisms (state files, resource providers, or reconciliation loops) to avoid duplicate changes; declarative syntax alone does not eliminate the need for idempotent behavior.

Exam trap

HashiCorp often tests the misconception that declarative IaC eliminates the need for idempotency, but in reality, declarative tools enforce idempotency through state management and plan generation, making it a key feature rather than an omission.

6
MCQeasy

What is the purpose of the 'terraform validate' command?

A.To check the validity of provider credentials.
B.To format Terraform configuration files.
C.To check syntax and internal consistency of configuration files.
D.To run unit tests on Terraform modules.
AnswerC

The `terraform validate` command performs a crucial static analysis of the Terraform configuration files in the current working directory. It meticulously checks for correct HashiCorp Configuration Language (HCL) syntax, ensuring all required arguments are present and correctly typed. Furthermore, it verifies the internal consistency of the configuration, confirming that all references between resources, variables, and outputs are resolvable and adhere to the provider's schema without needing to connect to any remote state or cloud provider APIs.

Why this answer

The 'terraform validate' command checks the syntax and internal consistency of Terraform configuration files, ensuring that the code is syntactically valid and that references between resources, data sources, and variables are correctly formed. It does not interact with providers or cloud APIs, so it cannot verify credentials or run tests.

Exam trap

HashiCorp often tests the distinction between 'validate' (syntax/consistency check) and 'plan' (which actually contacts providers and checks real-world state), leading candidates to mistakenly think 'validate' verifies credentials or remote resources.

How to eliminate wrong answers

Option A is wrong because 'terraform validate' does not check provider credentials; credential validation occurs during 'terraform init' or 'terraform plan' when the provider attempts to authenticate with the cloud API. Option B is wrong because formatting Terraform files is the purpose of 'terraform fmt', not 'validate'. Option D is wrong because 'terraform validate' does not execute unit tests; testing modules is done with external tools like Terratest or the 'terraform test' command (introduced in later versions), not with 'validate'.

7
MCQhard

A Terraform configuration includes a module from the Terraform Registry. After running `terraform init`, the module is downloaded. However, a subsequent `terraform plan` fails with an error that a required provider is not installed, even though it is declared in the module. What is the most likely cause?

A.The module uses a different Terraform version
B.The provider version constraint is incompatible
C.The `required_providers` block is not declared in the root module
D.The module source URL is incorrect
AnswerC

Terraform's provider installation mechanism primarily relies on the `required_providers` block within the root module to determine which providers need to be downloaded and configured. Even if a child module internally declares a provider, Terraform will not install it unless the root module explicitly includes that provider in its own `required_providers` block. This omission leads to a "provider not found" error when Terraform attempts to use the provider during `plan` or `apply`.

Why this answer

In Terraform, the `required_providers` block must be declared in the root module to ensure all providers are installed during `terraform init`. When a module from the Registry declares a provider but the root module does not, `terraform init` may not automatically install that provider, leading to a 'required provider not installed' error during `terraform plan`. The root module acts as the top-level configuration that aggregates all provider requirements.

Exam trap

HashiCorp often tests the misconception that provider declarations in child modules are automatically inherited by the root module, leading candidates to overlook the necessity of a root-level `required_providers` block.

How to eliminate wrong answers

Option A is wrong because a Terraform version mismatch would typically cause a different error (e.g., 'Unsupported Terraform version') during `terraform init` or `plan`, not a missing provider error. Option B is wrong because an incompatible provider version constraint would produce a version conflict error (e.g., 'no available releases match the given constraints'), not a 'not installed' error. Option D is wrong because an incorrect module source URL would cause a download failure during `terraform init`, not a provider installation issue after the module is successfully downloaded.

8
Matchingmedium

Match each Terraform command to its primary function.

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

Concepts
Matches

Initialize a working directory with provider plugins

Create an execution plan

Execute the actions proposed in a plan

Destroy previously-created infrastructure

Check configuration for syntax and internal consistency

Why these pairings

The correct matches are: init initializes the workspace, plan creates an execution plan, apply executes changes, destroy tears down resources. Common mistakes include confusing init with apply or plan with destroy.

9
MCQmedium

Refer to the exhibit. An operator runs terraform plan and gets the following output. They have not modified the Terraform configuration since the last successful apply. What is the most likely cause of the planned changes?

A.Terraform provider was updated to a new version.
B.The instance was terminated and recreated.
C.Terraform state was corrupted.
D.The instance was modified manually via the AWS console.
AnswerD

When an infrastructure resource managed by Terraform is altered directly through the cloud provider's console or API, its actual state diverges from the desired state defined in the Terraform configuration and the last known state recorded in the Terraform state file. Running `terraform plan` detects this 'drift' by comparing the actual infrastructure's current attributes with the desired state, then proposing actions to reconcile them, such as updating the attribute back to its configured value.

Why this answer

When terraform plan shows changes but the configuration was not modified, the most common cause is out-of-band drift — someone changed the resource directly in the AWS console (or via CLI/another tool), so the real infrastructure no longer matches the recorded state. Terraform compares desired config to state, and state to real resources, so manual changes surface as planned updates to bring the resource back to the declared configuration.

Exam trap

TF-004 often tests the assumption that any unexpected plan change must be a Terraform bug or state corruption, when the far more common cause is manual out-of-band modification of the resource.

How to eliminate wrong answers

Option A is wrong because a provider version update alone does not change resource attributes unless the schema or defaults changed, and it would not typically produce this drift pattern. Option B is wrong because if the instance had been terminated and recreated, Terraform would show a destroy/create or replacement plan, not a simple in-place update. Option C is wrong because a corrupted state file usually produces errors, missing resources, or a full re-create plan — not a clean, targeted diff on one attribute.

10
Multi-Selecthard

Which THREE of the following are capabilities of Terraform Cloud's Sentinel policy framework? (Choose three.)

Select 3 answers
A.Block Terraform runs based on the time of day
B.Enforce that resources have mandatory tags
C.Check that resources comply with security best practices
D.Restrict the creation of certain resource types
E.Estimate the cost of infrastructure changes
AnswersB, C, D

Sentinel can inspect planned resource attributes and reject configurations lacking required tags, enforcing the stem's tagging mandate before apply. This is a policy-as-code capability operating on the Terraform plan, not a runtime or post-deployment control.

Why this answer

Sentinel is a policy-as-code framework embedded in Terraform Cloud that evaluates plan data before apply, so option B is correct because a policy can inspect planned resource attributes and fail the run when required tags (e.g., CostCenter, Environment) are missing. Option C is correct because Sentinel policies can encode organizational security rules—such as requiring encrypted S3 buckets, private subnets, or approved instance types—and reject non-compliant plans. Option D is correct because Sentinel can match on resource type (e.g., aws_instance, azurerm_virtual_machine) and forbid or conditionally allow their creation.

Option A is not a Sentinel capability because policies evaluate Terraform configuration/plan data, not wall-clock scheduling; time-based run control would come from CI/CD or API triggers. Option E is not a Sentinel capability because cost estimation in Terraform Cloud is provided by the separate cost estimation feature (run tasks/infracost-style integrations), not by Sentinel policy logic.

Exam trap

The trap here is that candidates may confuse Sentinel's policy enforcement with Terraform Cloud's other features, such as cost estimation or run triggers, and incorrectly assume Sentinel can handle time-based or cost-related logic natively.

11
MCQmedium

An operator wants to pass output values from one Terraform configuration to another as input variables. Which approach is recommended?

A.Hardcode the output values in a variables file for the second configuration.
B.Store outputs in a shared file and use 'file()' function to read them.
C.Use a remote state data source to read the outputs from the first configuration's state.
D.Use environment variables to pass the output values.
AnswerC

Using a `terraform_remote_state` data source is the standard and recommended method for consuming outputs from a separate Terraform configuration. This data source securely reads the specified remote state file, allowing the second configuration to access the first's outputs directly and consistently. It establishes an implicit dependency, ensuring that the source configuration's state is available and up-to-date before the consuming configuration applies changes.

Why this answer

Terraform's remote state data source (e.g., `terraform_remote_state`) allows one configuration to securely read output values from another configuration's state file stored in a shared backend (like S3, Azure Storage, or Consul). This avoids duplication, manual errors, and ensures that the second configuration always uses the latest outputs from the first, without requiring direct file access or environment variables.

Exam trap

The trap here is that candidates often choose Option B (shared file with `file()`) because it seems simple and familiar, but they overlook that Terraform's `file()` function reads a static file at plan time and does not integrate with state management, leading to stale or inconsistent values across runs.

How to eliminate wrong answers

Option A is wrong because hardcoding output values in a variables file creates a manual, error-prone process that breaks automation and requires updates whenever the first configuration changes. Option B is wrong because using `file()` to read outputs from a shared file introduces a dependency on a static file path, lacks state locking, and does not automatically reflect changes in the first configuration's state; it also bypasses Terraform's native state management. Option D is wrong because environment variables are ephemeral, not tied to Terraform state, and require external orchestration to set them correctly, making them unsuitable for reliable, repeatable infrastructure-as-code workflows.

12
MCQhard

An organization uses Terraform with the AzureRM backend. The team recently split a large configuration into multiple smaller configurations, each with its own state file. They want to share outputs from one configuration (networking) as inputs to another (compute). Which approach should they use to reference the networking state from the compute configuration without duplicating data?

A.Define output values in the networking configuration and they will be automatically available in the compute configuration.
B.Run 'terraform output' on the networking state and save the values to a JSON file, then use 'terraform_remote_state' to read them.
C.Use a 'data' 'terraform_remote_state' block in the compute configuration to read the networking state.
D.Hardcode the subnet IDs from the networking configuration into the compute configuration.
AnswerC

The `data "terraform_remote_state"` block is the standard and recommended method for sharing information, specifically output values, between separate Terraform configurations. By configuring this data source in the compute configuration to point to the networking configuration's remote state, it can securely and dynamically retrieve the defined output values, such as subnet IDs, for use in creating compute resources. This establishes a clear dependency and promotes modularity.

Why this answer

The `terraform_remote_state` data source allows one Terraform configuration to read the root-level output values from another configuration's state file stored in the AzureRM backend. This enables sharing of networking outputs (e.g., subnet IDs) into the compute configuration without duplicating data or manually exporting values. The data source retrieves the state directly from the configured backend, ensuring the compute configuration always uses the latest networking outputs.

Exam trap

HashiCorp often tests the misconception that `terraform output` or automatic sharing between configurations is sufficient, but the correct approach is always to use the `terraform_remote_state` data source to read outputs from a separate state file.

How to eliminate wrong answers

Option A is wrong because Terraform does not automatically share outputs between separate configurations; each configuration has its own state file and outputs must be explicitly referenced. Option B is wrong because while `terraform output` can produce a JSON file, the `terraform_remote_state` data source reads the state file directly from the backend, not from a local JSON file; saving to a JSON file introduces manual steps and risks stale data. Option D is wrong because hardcoding subnet IDs violates the principle of infrastructure as code, creates duplication, and requires manual updates whenever networking changes.

13
MCQhard

You have two modules that create resources in different providers. Module A creates a VPC in AWS, Module B creates a Kubernetes cluster that requires the VPC ID. You want to ensure Module B runs after Module A but avoid hardcoding the VPC ID. Which approach is most appropriate?

A.Use a data source in Module B to look up the VPC.
B.Output the VPC ID from Module A and pass it as input to Module B.
C.Use terraform graph to order modules.
D.Use module dependency via depends_on in the root module.
AnswerB

The correct approach involves Module A exposing the VPC ID through an `output` block, making it accessible to the root module. This output is then referenced in the root module and explicitly passed as an `input variable` to Module B. Terraform's dependency graph automatically infers that Module A must successfully provision the VPC before Module B can consume its ID, ensuring both correct data flow and proper execution order.

Why this answer

It establishes an explicit data dependency between modules without hardcoding values. By outputting the VPC ID from Module A and passing it as an input variable to Module B, Terraform's dependency graph automatically ensures Module A is created before Module B, and the VPC ID is dynamically available at plan time.

Exam trap

Candidates often confuse dependency ordering (via depends_on) with data passing (via outputs/inputs). In Terraform, depends_on only ensures creation order but does not pass data; outputs and input variables are required to share values between modules.

How to eliminate wrong answers

Option A is wrong because using a data source to look up the VPC assumes the VPC already exists outside of Terraform management, which contradicts the requirement that Module A creates the VPC; data sources cannot create dependencies on resources defined in the same configuration. Option C is wrong because terraform graph only visualizes the dependency graph and does not enforce execution order or pass data between modules. Option D is wrong because depends_on only ensures ordering but does not pass the VPC ID value; Module B would still need the VPC ID as an input, which depends_on alone cannot provide.

14
Multi-Selecthard

Which THREE of the following are necessary steps to configure OIDC (OpenID Connect) for authenticating Terraform in a CI/CD pipeline?

Select 3 answers
A.Generate a long-lived API token and store it as a secret.
B.Set up an OIDC provider in the target cloud (e.g., AWS IAM OIDC provider).
C.Configure remote backend with static credentials.
D.Add a provider block with assume_role and web_identity_token attributes in Terraform configuration.
E.Create an IAM role in the cloud that the CI job can assume.
AnswersB, D, E

Setting up an OIDC provider in the target cloud, such as an AWS IAM OIDC provider, is a foundational step. This establishes a trust relationship where the cloud environment explicitly trusts identity tokens issued by your CI/CD system (the OIDC issuer). Without this configured trust anchor, the cloud would have no mechanism to verify the authenticity or validity of the identity tokens presented by your CI/CD pipeline.

Why this answer

To authenticate Terraform in a CI/CD pipeline using OIDC, you must first establish trust between the CI platform and the cloud provider by creating an OIDC identity provider (e.g., an AWS IAM OIDC provider). This provider validates the JSON Web Token (JWT) issued by the CI platform (e.g., GitHub Actions, GitLab CI) and maps it to an IAM role, enabling token-based authentication without long-lived secrets.

Exam trap

HashiCorp often tests the misconception that OIDC requires storing a long-lived token (Option A) or that the remote backend must use static credentials (Option C), when in fact OIDC replaces both with a trust-based, token-exchange mechanism that uses the `assume_role` and `web_identity_token` attributes.

15
Multi-Selectmedium

Which of the following accurately describe core purposes and benefits of using Terraform in a cloud infrastructure environment? Choose all that apply. (There are four correct answers.)

Select 4 answers
.Enables infrastructure as code by allowing users to define resources in declarative configuration files.
.Automates the provisioning and lifecycle management of infrastructure across multiple cloud providers.
.Provides a built-in drift detection mechanism that automatically reverts unauthorized manual changes to infrastructure.
.Supports state management to track the current state of infrastructure and plan changes incrementally.
.Generates real-time billing and cost optimization recommendations for deployed resources.
.Facilitates collaboration through remote state backends and version-controlled configuration files.

Why this answer

Terraform's core purpose is to enable Infrastructure as Code (IaC) by allowing users to define cloud resources in declarative HCL (HashiCorp Configuration Language) files. It automates provisioning and lifecycle management across multiple providers (AWS, Azure, GCP, etc.) using a single workflow. State management is fundamental: Terraform maintains a state file to track real-world resources, enabling incremental planning and safe updates.

Collaboration is facilitated by storing state remotely (e.g., in S3, Terraform Cloud) and using version control for configuration files, ensuring team consistency and auditability.

Exam trap

HashiCorp often tests the misconception that Terraform automatically reverts drift or provides cost optimization, when in fact drift detection is read-only and cost management is outside Terraform's scope.

16
MCQmedium

You have a list of VPC configurations and want to create multiple VPCs using a single module block with for_each. Which statement is true?

A.for_each on a module is not supported.
B.You can use for_each on a module block only if the module is published in the registry.
C.When using for_each, the module's outputs will be a map of output values for each instance.
D.for_each on a module block requires the module to support count.
AnswerC

With `for_each`, Terraform instantiates one module per map key, so each instance's outputs are collected into a map keyed by those same keys, letting you reference values per VPC. This satisfies the stem's single-module-block requirement, since outputs remain addressable individually rather than being flattened into a single list.

Why this answer

When you use `for_each` on a module block, Terraform creates multiple instances of the module, and the module's outputs become a map of output values keyed by the `for_each` key. This allows you to access each instance's outputs via the map, enabling iteration over the created resources.

Exam trap

A common misconception tested on the Terraform certification exam is that `for_each` on modules is unsupported or requires special conditions, when in fact it is a standard feature since Terraform 0.13. The key behavior to remember is that outputs become a map.

How to eliminate wrong answers

Option A is wrong because `for_each` on a module block is fully supported in Terraform 0.13 and later, allowing you to create multiple module instances from a single module block. Option B is wrong because `for_each` on a module block does not require the module to be published in the registry; it works with any module source, including local paths and Git repositories. Option D is wrong because `for_each` on a module block does not require the module to support `count`; `for_each` and `count` are independent meta-arguments, and a module can use either without the other.

17
MCQeasy

Refer to the exhibit. What is the purpose of this output block?

A.To store the public IP in a local file.
B.To set the public IP as a variable for use in other configurations.
C.To create a DNS record with the public IP.
D.To display the public IP address of the instance after apply.
AnswerD

The primary purpose of a Terraform `output` block is to define values that will be displayed to the user's console upon successful completion of a `terraform apply` operation. This allows operators to easily retrieve important information, such as an instance's public IP address, connection strings, or URLs, without needing to inspect the state file directly. Additionally, these outputs are stored in the state file and can be programmatically accessed by other Terraform configurations via remote state data sources.

Why this answer

The output block shown in the exhibit is a Terraform output value, which is defined using the `output` block in a configuration file. Its purpose is to display the public IP address of the instance in the terminal after `terraform apply` completes, providing a quick reference for the user. Option D correctly identifies this behavior, as outputs are designed to surface resource attributes to the user without storing them or creating external records.

Exam trap

The TF-003 exam often tests the distinction between Terraform outputs and other mechanisms like variables or resource declarations, and the trap here is that candidates confuse the display-only purpose of outputs with the ability to store data in files or create external resources, leading them to select options A, B, or C.

How to eliminate wrong answers

Option A is wrong because Terraform output blocks do not store values in a local file by default; they only display values in the CLI or make them available for `terraform output` command, and storing to a file would require a separate `local_file` resource or a provisioner. Option B is wrong because output values are not variables for use in other configurations within the same root module; they are read-only values exposed to the user or to other modules via module outputs, but they cannot be referenced as variables in the same configuration. Option C is wrong because creating a DNS record requires a dedicated resource (e.g., `aws_route53_record`), and an output block alone does not interact with DNS providers or create any records.

18
MCQhard

An organization stores their Terraform modules in a private Git repository. They need to reference a module that resides in a subdirectory called 'modules/rds' within the repository 'infra-modules' on the main branch. Which source argument should be used?

A.source = "git::https://github.com/org/infra-modules.git//modules/rds"
B.source = "git::https://github.com/org/infra-modules.git"
C.source = "git::https://github.com/org/infra-modules.git:modules/rds"
D.source = "git::https://github.com/org/infra-modules.git//rds"
AnswerA

This module source declaration is correctly formatted for a Git repository. The `git::` prefix explicitly tells Terraform to use the Git protocol. Crucially, the double-slash `//` acts as the required delimiter, separating the main repository URL from the subdirectory path `modules/rds` where the actual module code resides. This ensures Terraform fetches the specific module from its intended location within the repository.

Why this answer

Terraform's module source syntax for Git repositories uses a double slash (`//`) to specify a subdirectory within the repository. The format `git::https://github.com/org/infra-modules.git//modules/rds` tells Terraform to clone the repository at the main branch and then use the module located in the `modules/rds` subdirectory. This is the standard way to reference a module in a subdirectory of a Git repository.

Exam trap

The key trap in this question is that candidates confuse the double-slash (`//`) syntax with a colon (`:`) or forget to include the subdirectory path entirely, leading them to pick options that either point to the root or use incorrect separators.

How to eliminate wrong answers

Option B is wrong because it references the root of the repository, not the subdirectory `modules/rds`, so Terraform would look for the module in the repository root, which is incorrect. Option C is wrong because it uses a colon (`:`) to separate the repository URL from the subdirectory path, but Terraform requires a double slash (`//`) for subdirectory references in Git sources. Option D is wrong because it specifies `//rds` instead of `//modules/rds`, which would point to a non-existent subdirectory named `rds` at the repository root, not the correct path.

19
MCQmedium

A consultant is writing a reusable module that provisions an AWS VPC. Callers are complaining that they cannot tell which inputs are required and which have defaults, and the module's README is frequently out of date. Which practice most directly improves the module's self-documenting interface without adding external tooling?

A.Move all variable declarations into a separate `variables.tf` file and reference them from a single `main.tf`.
B.Add a `description` argument to every variable and output declaration, and provide defaults only where a value is genuinely optional.
C.Set `sensitive = true` on all variables so callers are forced to inspect the module source before using it.
D.Convert the module to use `terraform_remote_state` data sources so callers can read the VPC attributes directly.
AnswerB

Descriptions on variables and outputs are surfaced by `terraform-docs`, the registry, and `terraform plan` diagnostics, so callers see the intended purpose and whether a default exists. Variables without defaults are visibly required. This keeps the interface accurate at the source and avoids the drift that separate README files suffer, which is exactly the complaint the consultant needs to resolve.

Why this answer

Descriptions on variables and outputs are the primary in-configuration documentation surface. Tools and the registry read them, and the presence or absence of a default communicates required versus optional. Keeping defaults only for genuinely optional inputs prevents callers from supplying meaningless placeholder values and makes the module interface predictable.

Exam trap

The trap here is thinking that reorganising variables into separate files changes what callers must supply, when all .tf files in a directory form one configuration.

20
Multi-Selecteasy

Which TWO statements about Terraform data sources are correct?

Select 2 answers
A.Data sources can be used in count and for_each.
B.Data sources can fetch information from external systems.
C.Data sources are only available after applying the configuration.
D.Data sources are used to create new infrastructure.
E.Data sources cannot be used inside modules.
AnswersA, B

Data sources are evaluated during the plan phase, making their output available to Terraform's meta-arguments. This allows their attributes, such as a list of IDs or names fetched from an external system, to dynamically drive the `count` or `for_each` argument of a resource or module. Consequently, you can provision multiple instances of infrastructure based on existing external data, enabling highly dynamic and data-driven configurations. This is a powerful pattern for managing infrastructure that adapts to external state.

Why this answer

Terraform data sources are regular resources that support the `count` and `for_each` meta-arguments, allowing you to dynamically fetch data for multiple instances or conditional logic. This enables patterns like iterating over a list of external IDs to retrieve corresponding data from a provider, such as fetching multiple AMI IDs for different regions.

Exam trap

The trap here is that candidates confuse data sources with managed resources, assuming they require an apply to be available or that they create infrastructure, when in fact they are read-only and resolved during planning.

21
MCQeasy

What is the primary purpose of Terraform's state file?

A.Provide a GUI
B.Execute scripts
C.Map configurations to real-world resources
D.Store secrets
AnswerC

The Terraform state file is the definitive source of truth that precisely maps the logical resource definitions within your Terraform configuration to their corresponding physical instances in the real world. This crucial mapping includes unique identifiers, attributes, and dependencies of each managed resource. By maintaining this comprehensive record, Terraform can accurately understand the current state of your infrastructure, enabling it to intelligently plan and apply changes to achieve the desired configuration.

Why this answer

Terraform's state file is the authoritative record that maps resources declared in configuration to the actual real-world objects (e.g., AWS instance IDs, Azure resource IDs). Without it, Terraform cannot know what it has already created, what to update, or what to destroy.

Exam trap

TF-004 often tests the misconception that the state file stores secrets or executes code — candidates must remember its core purpose is the mapping between configuration and real infrastructure, not secret management or script execution.

How to eliminate wrong answers

Option A is wrong because Terraform is a CLI-driven IaC tool; the state file has nothing to do with providing a GUI. Option B is wrong because the state file does not execute scripts — it is a JSON data store describing resource metadata and attributes. Option D is wrong because while state can incidentally contain sensitive values (which is why remote backends with encryption are recommended), storing secrets is not its purpose and it should never be treated as a secrets manager.

22
MCQeasy

A developer is new to Terraform and wants to understand the core workflow. Which sequence of commands correctly represents the basic Terraform workflow?

A.terraform init, terraform apply
B.terraform plan, terraform init, terraform apply
C.terraform init, terraform plan, terraform apply
D.terraform validate, terraform plan, terraform destroy
AnswerC

This sequence represents the standard and recommended Terraform core workflow for provisioning infrastructure. `terraform init` first prepares the working directory by downloading necessary provider plugins and initializing the backend. Subsequently, `terraform plan` generates a detailed execution plan outlining all proposed changes, allowing for review, before `terraform apply` then executes that plan to create, update, or delete resources.

Why this answer

The basic Terraform workflow follows a strict three-step sequence: `terraform init` to initialize the working directory and download required providers/modules, `terraform plan` to preview the changes Terraform will make against the current state, and `terraform apply` to execute the planned changes. Skipping `init` or `plan` would either fail due to missing providers or apply changes without a reviewable execution plan, violating the standard workflow.

Exam trap

HashiCorp often tests the misconception that `terraform plan` is optional or that `terraform init` can be skipped if providers are already cached, but the exam requires strict adherence to the documented workflow sequence.

How to eliminate wrong answers

Option A is wrong because it omits `terraform plan`, which is essential for reviewing proposed infrastructure changes before applying them; running `terraform apply` without a plan can lead to unintended modifications. Option B is wrong because it places `terraform plan` before `terraform init`, but `init` must run first to download providers and set up the backend; without `init`, `plan` will fail with a 'no provider' error. Option D is wrong because it includes `terraform destroy` instead of `terraform apply`, and `destroy` is a separate workflow for tearing down infrastructure, not part of the basic creation/update workflow; additionally, `validate` is optional and not a core step.

23
Multi-Selecteasy

Which two are benefits of using Infrastructure as Code? (Choose two.)

Select 2 answers
A.Guaranteed cost optimization
B.Removes need for cloud providers
C.Reproducible environments
D.Automated documentation
E.Elimination of all manual errors
AnswersC, D

Infrastructure as Code (IaC) ensures highly reproducible environments by defining infrastructure configurations in declarative code, which can be version-controlled and applied consistently across different stages. This means that development, testing, and production environments can be provisioned with identical resource specifications, reducing "it works on my machine" issues and ensuring predictable behavior. The ability to recreate an entire infrastructure stack from a known state is a core benefit, facilitating disaster recovery and consistent deployments.

Why this answer

Option C (Reproducible environments) is correct because IaC defines infrastructure in versioned template/code files (e.g., Terraform HCL, CloudFormation YAML), so the same configuration can be applied repeatedly to produce identical, consistent environments across dev, test, and prod. Option D (Automated documentation) is correct because the declarative code itself serves as living documentation of the infrastructure's desired state, and tools can generate diagrams or docs directly from those definitions, keeping documentation in sync with reality. Option A is wrong because IaC does not guarantee cost optimization—it enables consistent, auditable provisioning, but cost savings depend on design choices and rightsizing.

Option B is wrong because IaC still relies on cloud providers (or other target platforms) to actually host the resources; it automates how they are provisioned, not whether a provider is needed. Option E is wrong because IaC reduces configuration drift and many manual errors, but it cannot eliminate all errors—mistakes in the code, parameters, or logic can still be deployed.

Exam trap

TF-004 often tests the misconception that IaC eliminates all errors or guarantees cost savings; candidates must recognize that IaC improves consistency and documentation but does not remove human error or cloud provider dependency.

24
MCQhard

An organization manages multiple environments (dev, staging, prod) using Terraform. They want to minimize code duplication while allowing environment-specific variable values. Which approach best achieves this goal?

A.Use a separate Git branch for each environment, each with its own Terraform configuration.
B.Write a single Terraform configuration that uses count and conditional expressions to create resources based on environment variable.
C.Use Terraform workspaces with a single configuration and define all variable values in one .tfvars file.
D.Organize the repository with a shared modules directory and separate subdirectories for each environment that call the same modules with environment-specific .tfvars files.
AnswerD

Organizing the repository with a shared modules directory and separate subdirectories for each environment is a best practice that maximizes code reuse and maintains clear separation of concerns. Common infrastructure patterns are encapsulated in reusable modules, while each environment's subdirectory instantiates these modules using its own dedicated `.tfvars` files. This structure ensures consistency, simplifies environment-specific parameter management, and enhances overall maintainability and scalability.

Why this answer

It leverages Terraform's module system to define reusable infrastructure components in a shared directory, while each environment (dev, staging, prod) has its own subdirectory with a root configuration that calls those modules and passes environment-specific `.tfvars` files. This minimizes code duplication by keeping the module logic in one place, and allows per-environment variable values without mixing concerns. It follows the recommended pattern for multi-environment management in Terraform, avoiding the pitfalls of branches, workspaces, or conditional logic that can lead to complexity or state corruption.

Exam trap

HashiCorp often tests the misconception that Terraform workspaces are the correct way to manage multiple long-lived environments, but workspaces are actually designed for short-lived or temporary infrastructure, not for permanent dev/staging/prod separation, because they share the same backend configuration and can lead to accidental state corruption if not carefully isolated.

How to eliminate wrong answers

Option A is wrong because using separate Git branches for each environment leads to configuration drift, merge conflicts, and makes it difficult to promote changes consistently across environments; Terraform state is not designed to be managed across branches. Option B is wrong because using `count` and conditional expressions within a single configuration to create resources based on an environment variable results in a monolithic state file, making it hard to apply changes to one environment without affecting others, and it violates the principle of separating environments for safety and isolation. Option C is wrong because Terraform workspaces share the same configuration and backend, but defining all variable values in one `.tfvars` file forces all workspaces to use the same variable file, which defeats the purpose of environment-specific values; workspaces are better suited for temporary or testing scenarios, not for managing distinct environments like dev, staging, and prod with different variable sets.

25
MCQhard

A company uses Terraform to manage multi-cloud infrastructure. They have separate Terraform configurations for AWS and Azure, each with its own state file. They want to share a common set of networking variables (e.g., allowed IP ranges) between these configurations without duplicating data. Which approach best achieves this?

A.Create a module that contains the variable definitions and reference it in both configurations.
B.Define the variables in a 'terraform.tfvars' file and copy it to each configuration directory.
C.Store the variables in a JSON file and use the 'jsondecode' function in each configuration.
D.Use a remote state data source to read the outputs from a dedicated 'globals' workspace.
AnswerD

Using a remote state data source to read outputs from a dedicated 'globals' workspace is the most robust solution for sharing common configuration values. A 'globals' workspace can define and manage these shared parameters as its outputs, which are then securely stored in a remote state backend. Other Terraform configurations can then use the `terraform_remote_state` data source to directly consume these outputs, establishing a single, version-controlled source of truth and eliminating data duplication.

Why this answer

Using a remote state data source allows you to read outputs from a dedicated 'globals' Terraform workspace that stores shared networking variables. This approach avoids data duplication and ensures that both AWS and Azure configurations can dynamically consume the same canonical set of values without manual copying or file sharing. It leverages Terraform's native remote state mechanism to securely and consistently share data across separate configurations.

Exam trap

HashiCorp often tests the misconception that modules or variable files can share actual runtime data between separate configurations, when in fact they only define structure or require manual distribution, whereas remote state data sources provide dynamic, centralized sharing without duplication.

How to eliminate wrong answers

Option A is wrong because creating a module with variable definitions only provides a reusable template for declaring variables; it does not share actual values between configurations, so each configuration would still need to supply its own data. Option B is wrong because copying a 'terraform.tfvars' file to each configuration directory duplicates the data, violating the requirement to avoid duplication and introducing drift risk. Option C is wrong because storing variables in a JSON file and using 'jsondecode' still requires the file to be present in each configuration's working directory, leading to duplication and synchronization challenges.

26
MCQeasy

Refer to the exhibit. A developer runs `terraform init` and then `terraform plan`. The plan output shows that Terraform will create the AWS instance. However, the state file is expected to be stored in S3 under the key "prod/terraform.tfstate". Which statement is true?

A.The state will be stored locally because the S3 backend configuration is invalid
B.The state will be stored in S3 in the us-west-2 region because the provider overrides the backend region
C.The state will be stored in S3 in the us-east-1 region, and the EC2 instance will be created in us-west-2
D.The `terraform plan` will fail because the S3 bucket is not created yet
AnswerC

The `backend "s3"` configuration explicitly defines `region = "us-east-1"`, which means Terraform will store its state file in an S3 bucket located within the `us-east-1` AWS region. Concurrently, the `provider "aws"` block specifies `region = "us-west-2"`, directing all AWS resources managed by this provider, such as the EC2 instance, to be provisioned within the `us-west-2` AWS region. These two region settings operate entirely independently, serving distinct purposes within the Terraform workflow.

Why this answer

The backend configuration specifies the S3 bucket and key 'prod/terraform.tfstate' for state storage, and the AWS provider region (us-west-2) is independent of the backend region. The backend block does not include a 'region' argument, so Terraform defaults to us-east-1 for state storage, while the EC2 instance is created in the provider's configured region (us-west-2).

Exam trap

HashiCorp often tests the misconception that the provider region automatically applies to the backend, leading candidates to incorrectly assume the backend uses the provider's region instead of the default us-east-1.

How to eliminate wrong answers

Option A is wrong because the S3 backend configuration is valid; the backend block specifies bucket and key, and Terraform will use the default region (us-east-1) if no region is explicitly set in the backend. Option B is wrong because the provider region does not override the backend region; the backend region is determined by the backend configuration or defaults to us-east-1, not the provider's region. Option D is wrong because `terraform plan` does not fail if the S3 bucket does not exist; the plan runs locally and only attempts to access the backend during `terraform apply` or `terraform init` (if partial configuration is used), but `terraform plan` can proceed with a local state if the backend is unreachable.

27
MCQmedium

A user wants to import an existing AWS EC2 instance into Terraform state so it can be managed. After writing the resource block matching the instance, what is the correct next step?

A.Run 'terraform import' with the resource address and ID of the instance.
B.Run 'terraform plan' to see if the import is necessary.
C.Run 'terraform refresh' to sync state with the existing resource.
D.Run 'terraform apply' directly; Terraform will detect the existing resource and import it.
AnswerA

The `terraform import` command is the designated tool for bringing pre-existing infrastructure resources, like an AWS EC2 instance, under Terraform's management. It requires both the resource's address as defined in the Terraform configuration (e.g., `aws_instance.my_server`) and its unique ID from the cloud provider (e.g., `i-0123456789abcdef0`). Upon successful execution, Terraform records the resource's current state into the `terraform.tfstate` file, allowing subsequent `terraform plan` and `apply` operations to manage it.

Why this answer

After writing the resource block that matches the existing EC2 instance, the correct next step is to run 'terraform import' with the resource address and the instance ID. This command maps the real-world infrastructure to the Terraform state, allowing Terraform to manage the resource without destroying or recreating it. Without this explicit import, Terraform has no knowledge of the existing instance in its state file.

Exam trap

HashiCorp often tests the misconception that 'terraform apply' or 'terraform refresh' can automatically discover and import existing resources, when in fact only 'terraform import' explicitly maps external resources into state.

How to eliminate wrong answers

Option B is wrong because 'terraform plan' compares the current state with the configuration, but if the resource is not yet in state, it will show that the resource needs to be created, not that an import is needed. Option C is wrong because 'terraform refresh' updates the state with real-world attributes for resources already in state, but it cannot import a resource that is not yet tracked in state. Option D is wrong because 'terraform apply' will attempt to create a new resource from scratch, not detect and import an existing one; Terraform has no built-in auto-discovery or import-on-apply behavior.

28
MCQhard

A Terraform configuration uses a for_each expression to create multiple subnets. After applying, one subnet's configuration needs to be modified. The engineer updates the resource block's map key for that subnet. What will terraform plan show?

A.No changes because the subnet configuration is the same.
B.Only deletion of the old subnet.
C.An in-place update to the subnet.
D.Destruction of the existing subnet and creation of a new one.
AnswerD

This is the correct outcome. The `for_each` key is an integral part of a resource's unique address in the Terraform state. When this key changes, Terraform no longer finds the resource instance identified by the *old* key in the current configuration, marking it for destruction. Concurrently, it identifies a *new* resource instance, defined by the *new* key, which it plans to create. This process ensures that the desired state, reflecting the updated `for_each` keys, is accurately achieved through a destroy-and-create operation.

Why this answer

When a for_each expression is used, Terraform identifies each resource instance by its map key. Changing the map key for a subnet causes Terraform to treat the old key as a resource to be destroyed and the new key as a resource to be created, because the key is part of the resource's identity. Even if the configuration inside the block is identical, the change in key results in a destroy-and-create action, not an in-place update.

Exam trap

The trap here is that candidates often confuse a change in the for_each key with a change in the resource's arguments, assuming that identical configuration means no changes, when in fact the key itself is part of the resource identity and forces replacement.

How to eliminate wrong answers

Option A is wrong because changing the map key alters the resource's identity in the state, so Terraform detects a change even if the subnet configuration values are the same. Option B is wrong because Terraform will also create a new subnet for the new key, not just delete the old one. Option C is wrong because an in-place update only occurs when the resource address (including the for_each key) remains the same; changing the key forces a replacement.

29
Multi-Selectmedium

Which THREE of the following are best practices for Terraform state management?

Select 3 answers
A.Manually edit state files to fix configuration drift.
B.Commit state files to version control.
C.Use workspaces to manage different environments.
D.Store state file in a remote backend with locking enabled.
E.Use 'terraform state rm' to remove resources from state when needed.
AnswersC, D, E

Terraform workspaces provide a robust mechanism for managing multiple distinct environments, such as development, staging, and production, using the same configuration code. Each workspace maintains its own isolated state file, preventing resource conflicts and accidental modifications across environments. This isolation ensures that changes intended for one environment do not inadvertently affect another, promoting safer and more organized infrastructure deployments without duplicating configuration files.

Why this answer

Terraform workspaces allow you to manage multiple distinct state files for the same configuration, enabling environment separation (e.g., dev, staging, prod) without duplicating code or backends. Each workspace maintains its own state, preventing cross-environment interference and simplifying infrastructure lifecycle management.

Exam trap

HashiCorp often tests the misconception that state files should be version-controlled like code, but the trap is that state files contain sensitive data and are not idempotent, making remote backends with locking the correct practice.

30
MCQhard

A company has a monolithic Terraform configuration that manages all of its AWS infrastructure. They want to break it into smaller, manageable configurations without causing downtime or resource duplication. Which approach best follows the core Terraform workflow?

A.Create separate configurations from scratch and manually recreate all resources by running `terraform apply`
B.Use `terraform state mv` to move resources from the monolithic state to new state files for the smaller configurations
C.Import all existing resources into the new configurations before removing the old configuration
D.Delete the monolithic state and apply all new configurations at once
AnswerB

The `terraform state mv` command is the correct and safest approach for refactoring a monolithic configuration into smaller, independent ones. It allows specific resource instances to be moved from one Terraform state file to another without modifying or recreating the actual infrastructure resources. This enables an incremental migration strategy, where resources are logically reassigned to new configurations, preserving their existing state and avoiding any service disruption or resource recreation.

Why this answer

`terraform state mv` allows you to move resources from the monolithic state file into separate state files for the new, smaller configurations without destroying or recreating resources. This adheres to the core Terraform workflow by preserving the existing infrastructure state, avoiding downtime, and preventing resource duplication. The command updates the state mapping so that Terraform continues to manage the same real-world resources under the new configuration structure.

Exam trap

HashiCorp often tests the misconception that you must destroy and recreate resources to reorganize configurations, when in fact Terraform's state manipulation commands allow safe refactoring without impacting live infrastructure.

How to eliminate wrong answers

Option A is wrong because creating configurations from scratch and running `terraform apply` would attempt to create duplicate resources, causing conflicts or requiring manual deletion of existing resources, which risks downtime and violates the principle of state-driven management. Option C is wrong because importing existing resources into new configurations before removing the old configuration would result in duplicate state entries for the same resources, leading to Terraform attempting to manage them twice and potentially causing errors or resource duplication. Option D is wrong because deleting the monolithic state breaks Terraform's tracking of existing resources; applying new configurations would then try to create new resources, ignoring the existing ones, which can cause downtime or resource conflicts.

31
Multi-Selectmedium

Which THREE actions should be taken when migrating Terraform state from local to a remote backend?

Select 3 answers
A.Remove the local state file before running terraform init.
B.Run terraform init to initialize the backend and migrate state.
C.Manually import all existing resources into the remote state.
D.Confirm migration by typing 'yes' when prompted.
E.Add a backend block to the configuration.
AnswersB, D, E

After adding the backend block, terraform init detects the existing local state and offers to copy it into the configured remote backend. Running init satisfies the migration requirement by performing the actual state transfer and reconfiguring the working directory.

Why this answer

Option E is correct because you must declare a backend block (for example, backend "s3" or backend "azurerm") in the Terraform configuration so Terraform knows which remote backend to use. Option B is correct because after adding the backend block you run terraform init, which initializes the backend and, when existing local state is detected, offers to copy it to the new remote backend. Option D is correct because terraform init prompts 'Do you want to copy existing state to the new backend?' and you must confirm by typing 'yes' to complete the migration.

Option A is wrong because deleting the local state file first would destroy the state that needs to be migrated. Option C is wrong because terraform import is used for bringing existing infrastructure under management, not for migrating an already-tracked state file to a remote backend.

Exam trap

HashiCorp often tests the misconception that you must manually delete or move the local state file before initializing a remote backend, when in fact `terraform init` handles the migration automatically and safely.

32
MCQmedium

Your team stores Terraform state in an AWS S3 bucket and uses DynamoDB for state locking. A junior engineer runs `terraform apply` locally while a CI pipeline is also running `terraform apply` against the same state. The apply succeeds in both cases, but the resulting infrastructure is inconsistent and resources are missing from state. What is the most likely cause?

A.The `terraform apply` command was run with the `-parallelism=1` flag, which disabled locking.
B.The DynamoDB table was created in a different region than the S3 bucket, so locking was not enforced.
C.The S3 backend was configured without `dynamodb_table`, so state locking was not enabled.
D.The S3 bucket versioning was disabled, so Terraform could not read the latest state file.
AnswerC

Without the `dynamodb_table` argument in the S3 backend configuration, Terraform cannot acquire a lock, allowing concurrent applies to overwrite each other's state. Both applies succeed independently, but the final state reflects only one run's view, leaving resources untracked. This matches the symptom of inconsistent infrastructure and missing resources after simultaneous applies.

Why this answer

State locking prevents concurrent operations from modifying the same state file simultaneously. When the S3 backend is configured without a `dynamodb_table`, Terraform cannot acquire a lock, so two applies can run at once. Each apply reads the state, plans changes, and writes back, overwriting the other's updates.

This leads to a state file that does not reflect all created resources, causing drift and inconsistencies.

Exam trap

The trap here is assuming that S3 backend automatically provides locking, when in fact locking requires an explicitly configured DynamoDB table.

33
MCQhard

Refer to the exhibit. An engineer runs the commands shown in sequence. After executing 'terraform state rm', the next 'terraform plan' shows that the resource will be created. What is the most likely reason?

A.The 'terraform state rm' command only removes the resource from the state file, not the actual infrastructure. The next plan sees the configuration and attempts to create a new resource.
B.The 'terraform state rm' command triggers an automatic recreation of the resource.
C.The resource was destroyed by a separate process.
D.The state file was corrupted after removal.
AnswerA

The 'terraform state rm' command specifically targets the Terraform state file, removing the record of a managed resource without interacting with the actual cloud provider API to destroy the resource itself. When 'terraform plan' is subsequently executed, it compares the current configuration (which still declares the resource) against the modified state file (which no longer contains the resource's record). This discrepancy leads Terraform to identify the resource as "missing" from its management, prompting a plan to create a new instance to align the infrastructure with the desired configuration.

Why this answer

'terraform state rm' removes the resource from the Terraform state file but does not destroy or modify the actual infrastructure. On the next 'terraform plan', Terraform sees the resource in the configuration but not in state, so it plans to create a new resource — even though the original still exists in the cloud.

Exam trap

The trap is assuming 'terraform state rm' destroys the resource — candidates confuse state manipulation commands with 'terraform destroy', missing that state commands only affect the state file, not the actual infrastructure.

How to eliminate wrong answers

Option B is wrong because 'terraform state rm' does not trigger any API calls to the provider; it only edits the local or remote state file. Option C is wrong because there is no evidence of an external process destroying the resource — the plan shows creation because state no longer tracks it, not because it was destroyed. Option D is wrong because the state file is not corrupted; the command intentionally and cleanly removes the resource entry, leaving a valid state file.

34
MCQmedium

A company uses Terraform Cloud and wants to enforce policy checks before any apply. They have a set of Sentinel policies. Where should they configure these policies to run automatically on all runs?

A.In the terraform apply command with -policy flag.
B.Configure a webhook in the VCS to run policy checks.
C.Create a Policy Set in Terraform Cloud and attach to workspaces.
D.Deploy a Terraform Enterprise instance with custom policy.
AnswerC

Terraform Cloud enforces policies through Policy Sets, which are collections of Sentinel or OPA policies designed to evaluate infrastructure plans. To enforce a specific policy, an administrator must create a Policy Set, add the desired policy to it, and then attach that Policy Set to the relevant workspaces. During a Terraform Cloud run, these policies are evaluated after the plan phase and before the apply phase, blocking non-compliant infrastructure changes from being provisioned.

Why this answer

Terraform Cloud uses Policy Sets to group Sentinel policies and enforce them automatically on all runs for attached workspaces. When a Policy Set is associated with one or more workspaces, the policies are evaluated during the plan phase before any apply, blocking the run if any policy fails. This is the native mechanism in Terraform Cloud for automated policy enforcement without manual intervention.

Exam trap

The trap here is that candidates confuse the VCS webhook trigger (which starts a run) with the policy enforcement mechanism, or mistakenly think Sentinel policies can be invoked via CLI flags, when in fact Terraform Cloud requires Policy Sets attached to workspaces for automatic policy checks.

How to eliminate wrong answers

Option A is wrong because the `terraform apply` command does not support a `-policy` flag; Sentinel policies are evaluated server-side in Terraform Cloud, not via CLI flags. Option B is wrong because webhooks in the VCS trigger runs but do not execute policy checks; policy enforcement is handled by Terraform Cloud's built-in policy engine, not external webhooks. Option D is wrong because deploying a Terraform Enterprise instance is unnecessary when Terraform Cloud already provides Sentinel policy enforcement; the question specifies the company uses Terraform Cloud, so a separate TFE deployment is not required.

35
MCQmedium

A team uses Terraform to manage multiple AWS EC2 instances with a 'count' meta-argument. They need to reference the ID of the third instance in another resource's configuration. Which expression should they use?

A.aws_instance.example[1].id
B.aws_instance.example[2].id
C.element(aws_instance.example.*.id, 3)
D.aws_instance.example[3].id
AnswerB

This expression correctly references the ID of the third EC2 instance in a collection named `aws_instance.example`. Terraform consistently uses zero-based indexing for lists and resource collections created with `count`. Consequently, an index of `2` precisely targets the third element in the sequence, making `aws_instance.example[2].id` the correct way to retrieve its unique identifier.

Why this answer

In Terraform, the 'count' meta-argument creates a list of resources indexed starting from 0. To reference the third instance, you use index 2 (0, 1, 2). Option B correctly uses `aws_instance.example[2].id` to access the ID of the third EC2 instance.

Exam trap

The trap here is that candidates often forget Terraform uses zero-based indexing and mistakenly pick option D (index 3) or option A (index 1), confusing the ordinal position with the index number.

How to eliminate wrong answers

Option A is wrong because `aws_instance.example[1].id` references the second instance (index 1), not the third. Option C is wrong because `element(aws_instance.example.*.id, 3)` uses the splat expression with `element()` and index 3, which would attempt to access the fourth element (index 3), not the third; also, the splat expression returns a list, but the correct index for the third instance is 2. Option D is wrong because `aws_instance.example[3].id` uses index 3, which references the fourth instance, not the third.

36
MCQhard

A large organization uses Terraform to manage infrastructure across multiple AWS accounts. They have a shared module for VPC stored in a private Git repository (git::https://github.com/org/terraform-aws-vpc.git?ref=v1.0.0). After updating the module source to ref=v1.2.0, they run terraform init and then terraform plan. The plan still shows the old module's resources and behavior. They confirm the new tag exists and the module code has changed. The root module source line is correct. What is the most likely cause?

A.They forgot to run terraform get.
B.The module source URL is incorrect.
C.Terraform cached the previous module version and did not download the new one.
D.The module's outputs changed and they need to update the root module.
AnswerC

Terraform caches downloaded modules under .terraform/modules, keyed by source and version. Running terraform init alone may reuse the cached v1.0.0 copy rather than fetching v1.2.0; use terraform init -upgrade to force re-download of the updated ref.

Why this answer

Terraform caches modules in the `.terraform/modules` directory after `terraform init`. When the module source version is updated (e.g., from `ref=v1.0.0` to `ref=v1.2.0`), Terraform does not automatically re-download the module unless the lock file changes or `terraform init -upgrade` is used. Running `terraform init` without the `-upgrade` flag will not overwrite the cached module, so the plan still reflects the old version's resources and behavior.

Exam trap

Terraform caches modules in the `.terraform/modules` directory after `terraform init`. Running `terraform init` without the `-upgrade` flag will not re-download the module even if the source version has changed. You must use `terraform init -upgrade` to force a fresh download and update the lock file.

How to eliminate wrong answers

Option A is wrong because `terraform get` is used to download and update modules in a configuration, but it is essentially a subset of `terraform init`; the core issue is not about running a separate command but about the caching mechanism that prevents re-downloading. Option B is wrong because the question explicitly states the module source line is correct and the new tag exists, so the URL is not incorrect. Option D is wrong because changes to module outputs do not affect the plan's resource behavior; outputs are only used for root module references and do not cause the plan to show old resources.

37
Drag & Dropmedium

Drag and drop the steps to destroy infrastructure managed by Terraform in the correct order.

Drag or tap steps into the slots.

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

Why this order

Destroy plan previews removal; destroy command with confirmation tears down infrastructure.

38
Multi-Selecthard

Which TWO statements are correct about Terraform state when using the S3 backend with DynamoDB for state locking?

Select 2 answers
A.The DynamoDB table must exist before running terraform init
B.The S3 bucket should be versioned to provide consistency checks and recovery options
C.State can be stored without specifying a key in the backend configuration
D.State is encrypted at rest by default using SSE
E.State locking prevents any read operations on the state file
AnswersA, B

Terraform's S3 backend verifies and acquires the lock via DynamoDB during init and subsequent operations, so the table must already exist with the correct key schema. Terraform does not create it automatically, making prior table creation a genuine prerequisite for the backend to initialise.

Why this answer

Option A is correct because Terraform's S3 backend with DynamoDB locking requires the DynamoDB table (with a partition key of LockID) to already exist before terraform init, since init validates and configures the backend and will fail if the table is missing. Option B is correct because enabling versioning on the S3 bucket is a recommended practice that supports state recovery and consistency, allowing you to roll back to a previous state version if corruption or accidental deletion occurs. Option C is incorrect because the S3 backend configuration requires a key parameter specifying the path to the state file within the bucket.

Option D is incorrect because S3 server-side encryption is not enabled by default for Terraform state; you must explicitly configure encrypt = true or apply bucket-level encryption. Option E is incorrect because DynamoDB state locking prevents concurrent write operations that could corrupt state, not read operations.

Exam trap

TF-004 often tests whether candidates assume S3 encrypts state by default or that locking blocks reads — the trap is confusing default behaviours with required explicit configurations, and misunderstanding what locking actually prevents.

39
MCQhard

Refer to the exhibit. A user encounters this error while running 'terraform plan'. What is the best course of action?

A.Run 'terraform force-unlock' with the lock ID after verifying no other process holds the lock
B.Change the backend to local and run plan again
C.Delete the state file and run terraform init
D.Wait for 5 minutes and retry
AnswerA

When Terraform encounters a state lock, it prevents concurrent operations that could corrupt the state file. If a previous operation failed or was interrupted, the lock might persist, becoming "stale." The `terraform force-unlock <LOCK_ID>` command is specifically designed to release such a stale lock, but it must only be used after confirming that no other legitimate Terraform process is actively holding the lock to prevent state corruption.

Why this answer

The error indicates that the state file is locked, which prevents concurrent operations to avoid corruption. Running 'terraform force-unlock' with the lock ID is the correct recovery step, but only after verifying that no other Terraform process is actively using the state. This command releases the lock from the backend (e.g., S3, Consul, or Terraform Cloud), allowing subsequent plans or applies to proceed.

Exam trap

Terraform exams often test the misconception that waiting or changing backends is a safe workaround, when in fact only verifying the lock holder and then using 'force-unlock' is the proper recovery procedure.

How to eliminate wrong answers

Option B is wrong because changing the backend to local would bypass the remote state lock but also lose the shared state, potentially causing state conflicts or data loss in a team environment. Option C is wrong because deleting the state file destroys all tracked infrastructure state, leading to orphaned resources or requiring a full re-import; it does not address the lock itself. Option D is wrong because the lock does not automatically expire after a fixed time; it persists until explicitly released via 'force-unlock' or the holding process completes, so waiting is ineffective.

40
Multi-Selectmedium

Which TWO module source types support version constraints in Terraform?

Select 2 answers
A.HTTP URL to a zip archive
B.Terraform Public Registry
C.Local file path
D.Git URL with a branch reference
E.Terraform Cloud Private Registry
AnswersB, E

The Terraform Public Registry is purpose-built to host and serve modules with robust semantic versioning. When a module is sourced from the registry, Terraform utilizes the `version` argument to evaluate and select the highest compatible module version based on the specified constraint, such as `~> 1.0` or `>= 2.0.0`. This integral feature allows for controlled updates and dependency management.

Why this answer

The Terraform Public Registry supports version constraints via the `source` argument using the `registry.terraform.io` namespace, allowing you to specify a version range (e.g., `~> 1.0`) in the module block. Option E is correct because the Terraform Cloud Private Registry also supports version constraints, enabling you to pin or constrain module versions from private repositories using the same syntax as the public registry.

Exam trap

A common misconception is that Git URLs with branch or tag references support version constraints, but in reality, they only support fixed references and cannot enforce semantic version ranges like `~>` or `>=`.

41
MCQhard

You are managing a Terraform configuration for a multi-tier application that includes AWS EC2 instances, an RDS database, and an Application Load Balancer. The configuration uses multiple modules and remote state stored in an S3 bucket with DynamoDB locking. Recently, a colleague made changes to the configuration and applied them successfully. However, you now need to make additional changes and, when you run 'terraform plan', you receive an error: "Error: Error acquiring the state lock". The error message indicates that the lock is held by a different user. You have confirmed that your colleague is not currently running Terraform. What is the most appropriate course of action to proceed with your changes?

A.Edit the state file to remove the lock metadata.
B.Run 'terraform init -reconfigure' to reset the backend and release the lock.
C.Delete the lock file from the S3 bucket manually.
D.Run 'terraform force-unlock <lock_id>' to remove the stale lock.
AnswerD

The `terraform force-unlock <lock_id>` command is the correct and recommended method for releasing a stale state lock that was not automatically released after a failed or interrupted operation. This command safely interacts with the backend's locking mechanism, ensuring that the lock is properly removed and the state is accessible for subsequent operations. Requiring the `<lock_id>` adds a crucial layer of safety, preventing accidental unlocking of an active or incorrect lock.

Why this answer

Terraform uses DynamoDB for state locking to prevent concurrent modifications. When a lock becomes stale (e.g., due to a crash or network interruption), `terraform force-unlock <lock_id>` is the proper command to manually release it. This preserves the integrity of the state file and avoids manual S3 or DynamoDB edits, which could corrupt the state or break the locking mechanism.

Exam trap

HashiCorp often tests the misconception that manual S3 or DynamoDB manipulation is acceptable, when in fact Terraform provides a safe, built-in command (`force-unlock`) to handle stale locks without risking state corruption.

How to eliminate wrong answers

Option A is wrong because editing the state file directly to remove lock metadata is unsafe; it can corrupt the state and bypass Terraform's consistency checks. Option B is wrong because `terraform init -reconfigure` reinitializes the backend configuration but does not release an existing lock; it may even fail if the lock is still present. Option C is wrong because deleting the lock file from the S3 bucket manually does not remove the DynamoDB lock entry, so the lock remains active and the error persists.

42
Multi-Selecthard

Which THREE are considered Terraform's best practices?

Select 3 answers
A.Use variables to parameterize configurations
B.Use latest version of all modules
C.Store state securely
D.Use remote state locking
E.Use provisioners for all software installs
AnswersA, C, D

Using variables to parameterize configurations is a fundamental best practice, enabling dynamic values to be passed into modules and resources. This approach promotes reusability by allowing the same core configuration to be deployed across different environments (e.g., development, staging, production) with varying inputs, significantly reducing code duplication and enhancing maintainability. Variables make configurations flexible and adaptable to changing requirements without modifying the underlying HCL code.

Why this answer

A is correct because using variables to parameterize configurations is a core Terraform best practice that enables reusability, flexibility, and separation of concerns. By defining input variables in `variables.tf` and passing values via `terraform.tfvars` or environment variables, you avoid hardcoding values like instance types or region names, making configurations portable across environments (dev, staging, prod). This aligns with Terraform's principle of writing infrastructure as code that is modular and maintainable.

Exam trap

A common pitfall in Terraform is assuming that always using the latest module version is a best practice. In reality, for reproducibility and stability, you should pin module versions to specific, tested releases.

43
MCQmedium

An organization wants to use Terraform to manage infrastructure in multiple environments (dev, staging, prod) with the same configuration but different variable values. Which approach should they use?

A.Create separate directories with duplicated configurations
B.Use Terraform workspaces and separate variable files
C.Use a single state file with environment variables
D.Use different versions of Terraform for each environment
AnswerB

Terraform workspaces allow for managing multiple distinct states for a single configuration, effectively isolating environments like `dev`, `staging`, and `prod` within the same codebase. By combining workspaces with separate `*.tfvars` files for each environment, organizations can reuse the core infrastructure definition while providing environment-specific values for variables. This method ensures state isolation and parameter differentiation without duplicating the underlying configuration, promoting consistency and maintainability.

Why this answer

Terraform workspaces allow you to manage multiple distinct sets of infrastructure resources within the same configuration by maintaining separate state files. By combining workspaces with separate variable definition files (e.g., `dev.tfvars`, `prod.tfvars`), you can reuse the same configuration code while applying environment-specific variable values, avoiding duplication and ensuring consistency across environments.

Exam trap

HashiCorp often tests the misconception that workspaces are the only way to manage multiple environments, but the trap here is that candidates may overlook the need for separate variable files alongside workspaces, or incorrectly think that a single state file with environment variables is sufficient for isolation.

How to eliminate wrong answers

Option A is wrong because creating separate directories with duplicated configurations violates the DRY (Don't Repeat Yourself) principle, leading to configuration drift and increased maintenance overhead. Option C is wrong because using a single state file with environment variables would cause all environments to share the same state, resulting in conflicts and potential corruption when applying changes concurrently. Option D is wrong because using different versions of Terraform for each environment introduces unnecessary complexity and version incompatibility risks, and Terraform version does not solve the need for separate state or variable isolation.

44
MCQhard

A DevOps team manages Terraform configurations for a multi-environment infrastructure (dev, staging, prod). They maintain a central repository of reusable modules stored in a Git repository. Developers often update modules in the master branch to add features or fix bugs. Recently, after a developer updated the 'vpc' module in the master branch, the staging environment's infrastructure was destroyed and recreated during a terraform apply, causing an outage. The team needs to prevent such unintended changes across environments. They currently reference modules using the source argument with a git URL pointing to the master branch: source = "git::https://github.com/org/terraform-modules//vpc?ref=master". The team is looking for a solution that allows controlled updates and ensures each environment uses a fixed version of a module until explicitly upgraded.

A.Use module version constraints in the configuration, such as source = "git::https://github.com/org/terraform-modules//vpc?ref=v1.0.0" and update the ref tag when ready.
B.Create separate Git branches for each environment and reference the branch in the module source.
C.Use Terragrunt to manage module dependencies and lock versions.
D.Use the Terraform Registry to host modules with semantic versioning and pin versions.
AnswerA

This approach directly pins the module source to an immutable Git tag (e.g., "v1.0.0"). By referencing a specific tag, each environment's configuration explicitly declares the exact module version it requires, preventing unintended updates when the main branch or other tags evolve. Updates to the module are then a deliberate action, requiring a change to the `ref` attribute in the configuration, ensuring controlled and predictable deployments across environments. This provides strong version control without external tools.

Why this answer

Pinning the module source to an immutable Git tag (e.g., ref=v1.0.0) instead of a mutable branch (ref=master) ensures each environment uses a fixed, known version of the module until the team explicitly bumps the tag. This gives controlled updates: staging and prod stay on v1.0.0 while dev can test v1.1.0, and promotion is a deliberate change to the ref. It directly prevents the outage scenario where a master-branch commit silently changed the vpc module and caused terraform apply to destroy/recreate resources.

Exam trap

TF-004 often tests the difference between mutable branch refs and immutable tag/commit refs in module sources, so candidates who think 'separate branches per environment' solves version drift pick B, missing that branches are still mutable and do not pin versions.

How to eliminate wrong answers

Option B (separate Git branches per environment) is wrong because branches are still mutable — a commit to the staging branch changes what staging deploys, so it does not provide immutable version pinning and reintroduces the same drift risk. Option C (Terragrunt to manage dependencies and lock versions) is wrong because Terragrunt is an orchestration wrapper; it does not by itself pin module versions unless you also use immutable refs, and it adds tooling complexity without solving the core issue of mutable master. Option D (Terraform Registry with semantic versioning) is wrong because it requires publishing modules to the registry and changing the source, which is a larger migration than needed; the team already uses Git and can achieve the same immutability with tags, so this is over-engineered for the stated requirement.

45
Multi-Selectmedium

Which THREE are valid methods to create and manage Terraform workspaces?

Select 3 answers
A.Using version control branches
B.Using tags in AWS
C.Using 'terraform workspace' commands (new, select, delete)
D.Using the Terraform Cloud API
E.Using the Terraform Cloud web UI
AnswersC, D, E

The `terraform workspace` CLI commands provide direct, granular control over local and remote Terraform workspaces. Specifically, `terraform workspace new <name>` creates a new workspace, `terraform workspace select <name>` switches the current working context to an existing one, and `terraform workspace delete <name>` removes a workspace. These commands are fundamental for isolating different environments or stages of infrastructure within a single Terraform configuration, managing their respective state files.

Why this answer

Option C is correct because the Terraform CLI provides the native 'terraform workspace' subcommands — 'terraform workspace new', 'terraform workspace select', and 'terraform workspace delete' — which create, switch between, and remove workspaces within a working directory, storing state per workspace. Option D is correct because Terraform Cloud exposes a REST API that lets you programmatically create, list, and delete workspaces (e.g., via the /organizations/:organization_name/workspaces endpoints), enabling automation and CI/CD integration. Option E is correct because the Terraform Cloud web UI allows users to create and manage workspaces through the graphical interface, including setting variables, VCS connections, and team access.

Option A is not a valid Terraform mechanism: version control branches are a general Git practice and are not tied to Terraform workspace state management. Option B is not valid either: AWS tags are metadata applied to cloud resources and have no role in creating or managing Terraform workspaces.

Exam trap

The Terraform exam often tests the distinction between Terraform's native workspace commands and external tools like version control or cloud provider tags, trapping candidates who confuse code management with state management.

46
MCQmedium

A company is managing multiple cloud environments (dev, test, prod) using Terraform. They want to ensure consistent configurations across environments while allowing environment-specific values. Which IaC practice best supports this?

A.Using data sources only
B.Hardcoding values
C.Duplicating configuration files
D.Using variables and workspaces
AnswerD

Using variables allows the Terraform configuration to be parameterized, enabling different values (e.g., resource sizes, region names, environment tags) to be supplied dynamically for distinct environments without altering the core .tf files. Concurrently, Terraform workspaces provide isolated state files for each environment (e.g., dev, test), allowing a single, consistent configuration to manage multiple independent deployments. This powerful combination ensures flexibility, prevents state file conflicts, and maintains consistency across all environments from a unified codebase.

Why this answer

Using variables and workspaces allows you to define a single set of Terraform configurations while dynamically injecting environment-specific values via variable definitions (e.g., terraform.tfvars or -var-file) and isolating state per environment using workspaces (terraform workspace). This avoids duplication and ensures consistent resource definitions across dev, test, and prod, with only the variable values differing.

Exam trap

Candidates often think data sources can replace variables for environment separation, but data sources only read existing infrastructure and cannot define or override configuration values. Workspaces and variables are required to manage environment-specific settings without duplicating code.

How to eliminate wrong answers

Option A is wrong because data sources are used to fetch or compute information from providers or existing infrastructure, not to manage environment-specific configuration values or state isolation. Option B is wrong because hardcoding values directly in configuration files eliminates reusability and forces manual changes per environment, violating IaC principles of consistency and automation. Option C is wrong because duplicating configuration files for each environment leads to configuration drift, increased maintenance overhead, and violates the DRY (Don't Repeat Yourself) principle central to Terraform best practices.

47
MCQmedium

An organization uses Terraform Cloud for remote state management. A user runs `terraform apply` locally but receives an error that the state is locked. What is the most likely cause?

A.The Terraform configuration has a syntax error.
B.The user does not have access to the remote state backend.
C.Another user or process is currently running a Terraform operation that modifies the same state.
D.The remote backend is temporarily unavailable.
AnswerC

Terraform state locking is a crucial mechanism designed to prevent concurrent write operations from corrupting the remote state file. When an operation like `terraform apply` or `terraform destroy` begins, Terraform attempts to acquire an exclusive lock on the state. If another user or automated process is already performing a state-modifying operation, that lock will be held, causing subsequent operations to fail with a 'state locked' error, thereby ensuring data integrity.

Why this answer

Terraform Cloud uses a state locking mechanism to prevent concurrent modifications that could corrupt the state file. When a user runs `terraform apply` locally, the command first attempts to acquire a lock on the remote state. If another user or process (e.g., a Terraform Cloud run, a CI/CD pipeline, or another local apply) is already holding that lock, the new operation will fail with a 'state is locked' error.

This is a fundamental safety feature to ensure state consistency.

Exam trap

The trap here is that candidates often confuse a 'state locked' error with a 'backend unavailable' error (Option D) or an 'access denied' error (Option B), but The TF-003 exam specifically tests the understanding that a lock error is a concurrency control mechanism, not a connectivity or permission issue.

How to eliminate wrong answers

Option A is wrong because a syntax error in the Terraform configuration would cause a validation failure during `terraform plan` or `terraform apply`, not a state lock error; the lock error is a backend-level issue, not a configuration-level one. Option B is wrong because if the user lacked access to the remote state backend, the error would typically be an authentication or authorization failure (e.g., 'AccessDenied' or '403 Forbidden'), not a state lock message; the lock error implies the user can reach the backend but the state is already locked. Option D is wrong because if the remote backend were temporarily unavailable, the error would be a network or timeout error (e.g., 'RequestError' or 'unable to reach the backend'), not a specific 'state is locked' message; the lock error indicates the backend is reachable and actively reporting a lock.

48
MCQhard

A module block references a module with version constraint '>= 2.0, < 3.0'. An older version 1.5 is already cached from a previous init. The team wants to ensure they use a newer version. After running terraform init -upgrade, what happens?

A.Terraform upgrades to version 3.0 because it is the latest.
B.Terraform returns an error because version 1.5 is incompatible with the constraint.
C.Terraform uses the cached version 1.5 because it is already present.
D.Terraform upgrades to the latest version in the range 2.x that is not yet cached.
AnswerD

When `terraform get -upgrade` is executed, Terraform first evaluates the module's version constraint, such as `~> 2.0` (meaning `>= 2.0.0, < 3.0.0`). It then queries the module source to identify the absolute newest version available that falls within this specified range. Finally, it downloads this newly identified, latest compatible version, effectively upgrading the module if a newer one exists within the constraint and is not yet cached.

Why this answer

`terraform init -upgrade` instructs Terraform to ignore any cached versions and re-check the registry for the newest available version that satisfies the version constraint `>= 2.0, < 3.0`. Since the constraint excludes 3.0, the latest version in the 2.x series will be selected and downloaded, overwriting the cached 1.5 version.

Exam trap

HashiCorp often tests the misconception that `terraform init -upgrade` will always install the absolute latest version (like 3.0) regardless of constraints, or that a cached version will be used if it is present, when in fact the flag forces a fresh resolution within the defined range.

How to eliminate wrong answers

Option A is wrong because version 3.0 does not satisfy the constraint `< 3.0`; Terraform will never select a version outside the specified range. Option B is wrong because version 1.5 is simply ignored during the upgrade process; Terraform does not return an error for a cached incompatible version—it just fetches a compliant one. Option C is wrong because `-upgrade` explicitly tells Terraform to disregard the cached version and fetch the latest matching version from the registry.

49
MCQeasy

A team uses Terraform to manage infrastructure. They have multiple configuration directories for different environments (dev, staging, prod). They want to reuse common modules across environments. Which approach aligns with the core Terraform workflow best practices?

A.Use a single configuration with separate state files and variable files for each environment
B.Use workspaces with state stored in a local backend
C.Copy the configuration into each environment directory and modify as needed
D.Create separate Terraform configurations for each environment with hardcoded values
AnswerA

This approach leverages a single, consistent Terraform configuration module, promoting code reuse and reducing potential for configuration drift across environments. Environment-specific differences are managed through distinct `terraform.tfstate` files, typically stored in a remote backend, and separate variable definition files (`.tfvars`), which are passed during `terraform apply` using the `-var-file` flag. This ensures strong isolation between environments while maintaining a unified codebase, crucial for consistent deployments.

Why this answer

It follows the core Terraform workflow of separating configuration from state and using variable files to manage environment-specific differences. By maintaining a single configuration directory with separate state files (e.g., via different backends or state file paths) and variable files (e.g., `dev.tfvars`, `prod.tfvars`), the team avoids duplication and ensures that all environments use the same module versions and resource definitions, which is a best practice for consistency and maintainability.

Exam trap

HashiCorp often tests the misconception that workspaces are the primary mechanism for managing multiple environments, but the trap here is that workspaces with a local backend lack the isolation and locking required for team-based workflows, making variable files with separate remote state backends the recommended practice.

How to eliminate wrong answers

Option B is wrong because workspaces with a local backend store all state files in the same directory, which can lead to state file corruption or accidental overwrites when multiple team members run Terraform simultaneously, and it does not provide the isolation needed for production-grade environments. Option C is wrong because copying configurations into each environment directory violates the DRY (Don't Repeat Yourself) principle, leading to configuration drift, increased maintenance overhead, and potential inconsistencies between environments. Option D is wrong because creating separate configurations with hardcoded values eliminates reusability, makes updates error-prone, and contradicts Terraform's design of using variables and modules to parameterize infrastructure.

50
Multi-Selectmedium

During terraform init, which TWO of the following actions occur? (Choose two.)

Select 2 answers
A.Validate the configuration.
B.Create the state file.
C.Download provider plugins.
D.Generate a plan.
E.Initialize the backend.
AnswersC, E

A primary action of `terraform init` is to identify all declared providers within the configuration (e.g., `aws`, `azurerm`, `google`) and download their respective plugin executables. These binaries are stored in the `.terraform/providers` subdirectory of the working directory. This step is essential as these plugins act as the interface between Terraform and the various cloud or service APIs, enabling resource management in subsequent commands like `terraform plan` and `terraform apply`.

Why this answer

Option C is correct because terraform init downloads and installs the provider plugins declared in the configuration into the .terraform directory (or the plugin cache), resolving version constraints from the required_providers block. Option E is correct because terraform init initializes the backend, configuring where state is stored (e.g., local, S3, or Terraform Cloud) and, for remote backends, performing the backend setup such as creating or verifying the state storage. Option A is not part of init; configuration validation is performed by terraform validate.

Option B is not performed by init; the state file is created or written when Terraform applies changes (or via terraform state operations), not during initialization. Option D is not performed by init; a plan is generated by terraform plan.

Exam trap

HashiCorp often tests the misconception that `terraform init` validates the configuration or creates the state file, when in fact those actions belong to `terraform validate` and `terraform apply` respectively.

51
MCQhard

You are a DevOps engineer at a large e-commerce company. The infrastructure team uses Terraform to manage AWS resources across multiple accounts. Recently, they introduced a new module that creates an S3 bucket with a bucket policy. The module is used in several environments (dev, staging, prod). After merging a pull request that updates the bucket policy to grant cross-account access to a new partner account, the 'terraform apply' in the dev environment fails with: 'Error: Error putting S3 policy: AccessDenied: Access Denied'. The team is using a remote backend (S3) with DynamoDB locking. The CI/CD pipeline runs as an IAM role with permissions to manage infrastructure. The module uses 'aws_iam_policy_document' data source to construct the policy. The error occurs only in dev, not staging or prod. What is the most likely cause and the correct course of action?

A.Verify that DynamoDB state locking is not causing the error.
B.Run 'terraform validate' to check the policy document syntax.
C.Check the bucket policy for syntax errors by comparing with staging and prod.
D.Check the IAM permissions associated with the dev environment's role to ensure it has 's3:PutBucketPolicy' on the bucket.
AnswerD

The dev role lacks s3:PutBucketPolicy, so the apply fails only there while staging and prod roles retain it. Verifying and granting that permission on the dev bucket resolves the AccessDenied without altering the policy document itself.

Why this answer

The error 'AccessDenied' when calling 's3:PutBucketPolicy' indicates the IAM role used by the CI/CD pipeline in the dev environment lacks the necessary permission to apply the bucket policy. The module uses 'aws_iam_policy_document' to construct the policy, which is validated at plan time, so syntax errors would surface earlier. The fact that the error occurs only in dev, not staging or prod, points to an environment-specific IAM permissions issue rather than a policy syntax or state locking problem.

Exam trap

HashiCorp often tests the distinction between policy syntax errors (which would appear in all environments) and IAM permission errors (which are environment-specific), leading candidates to incorrectly focus on policy validation or state locking instead of the IAM role's permissions.

How to eliminate wrong answers

Option A is wrong because DynamoDB state locking errors produce messages like 'Error acquiring the state lock' or 'ConditionalCheckFailedException', not 'AccessDenied' from S3 API calls. Option B is wrong because 'terraform validate' checks configuration syntax and internal references, but it cannot validate S3 bucket policy syntax against the AWS IAM policy language; that validation occurs when the policy is applied via the API. Option C is wrong because comparing bucket policies between environments would not resolve an 'AccessDenied' error; the error is an authorization failure, not a syntax error, and the policy is constructed dynamically via the data source, so syntax issues would be consistent across environments.

52
MCQhard

Refer to the exhibit. A developer creates a new Terraform configuration with this backend block and runs terraform init. What will happen?

A.Terraform will initialize with a local backend because the remote backend configuration is incomplete.
B.Terraform will return an error and fail to initialize.
C.Terraform will use default values for the missing arguments and initialize successfully.
D.Terraform will prompt the developer interactively for the missing arguments.
AnswerB

Terraform's 'init' command performs validation of the backend configuration early in its execution. When a remote backend, like AWS S3, is declared but critical, non-optional arguments such as 'bucket' or 'region' are omitted, Terraform identifies this as an invalid configuration. Consequently, it will immediately terminate the initialization process and output a specific error message indicating the missing required arguments, preventing any further operations.

Why this answer

Terraform backend blocks require all mandatory arguments for the chosen backend type; if required fields are missing, terraform init fails with an error rather than silently falling back. Terraform does not supply defaults for backend configuration arguments and does not prompt interactively for them during init.

Exam trap

TF-004 often tests the misconception that Terraform will prompt interactively or fall back to local state when a remote backend block is incomplete, when in fact it hard-fails.

How to eliminate wrong answers

Option A is wrong because Terraform does not silently downgrade to a local backend when a remote backend block is incomplete; it errors out. Option C is wrong because backend configuration arguments have no implicit default values — Terraform requires explicit values for required fields. Option D is wrong because terraform init is non-interactive for backend configuration; it does not prompt for missing arguments, it fails.

53
MCQhard

A team renamed a module from 'module.network' to 'module.vpc' in their configuration. They run 'terraform plan' and see that Terraform wants to destroy the old network resources and create new ones. They want to preserve the existing resources without downtime. What should they do?

A.Add a 'moved' block to the configuration to map the old module address to the new one.
B.Use 'terraform state mv' to move the resources to the new module address.
C.Update the module source to a new version.
D.Accept the destroy and recreate since it's the only way.
AnswerA

Adding a 'moved' block to the configuration is the correct and declarative approach for handling resource address refactoring, such as renaming a module. This block explicitly informs Terraform that a resource or module previously known by one address should now be tracked under a new address. During the next 'terraform plan' and 'apply', Terraform will update the state file to reflect this change without destroying and recreating the underlying infrastructure, thus preserving existing resources and their attributes.

Why this answer

The `moved` block in Terraform allows you to refactor module addresses without destroying and recreating resources. By adding a `moved` block that maps the old module address (`module.network`) to the new one (`module.vpc`), Terraform will automatically update the state to reflect the new address during the next plan and apply, preserving the existing infrastructure and avoiding downtime.

Exam trap

HashiCorp often tests the distinction between declarative (`moved` block) and imperative (`terraform state mv`) refactoring, trapping candidates who think manual state manipulation is the correct approach for configuration-driven changes.

How to eliminate wrong answers

Option B is wrong because `terraform state mv` is a manual, imperative command that moves resources in the state file, but it does not update the configuration itself; the configuration still references the old module address, leading to drift and potential future issues. Option C is wrong because updating the module source to a new version does not address the module address rename; it would only change the module's source code, not the state mapping, and could still trigger resource recreation if the new version changes resource configurations. Option D is wrong because accepting destroy and recreate is unnecessary and would cause downtime; Terraform provides the `moved` block as a first-class refactoring mechanism to avoid this.

54
MCQmedium

Refer to the exhibit. A team is using this S3 backend configuration. During a deployment, they receive an error that the state file is locked. What is the most likely cause?

A.The S3 bucket does not exist
B.The region is incorrect
C.The DynamoDB table is not provisioned or the IAM role lacks permissions
D.The key path is incorrect
AnswerC

Terraform's S3 backend leverages an Amazon DynamoDB table for robust state locking to prevent concurrent state modifications. If the specified DynamoDB table does not exist, or if the IAM role used by Terraform lacks the necessary `dynamodb:PutItem`, `dynamodb:GetItem`, and `dynamodb:DeleteItem` permissions, Terraform will be unable to acquire or release the state lock. This directly manifests as a "Failed to get lock" or "Error acquiring the state lock" message, as the mechanism designed to prevent race conditions is non-functional.

Why this answer

The error message 'state file is locked' directly indicates that Terraform is attempting to acquire a lock on the state using DynamoDB, but the lock table either does not exist or the IAM role used by Terraform lacks the required permissions (dynamodb:PutItem, dynamodb:GetItem, dynamodb:DeleteItem, dynamodb:DescribeTable). Without a properly provisioned DynamoDB table or sufficient IAM permissions, the locking mechanism fails, producing this specific error.

Exam trap

HashiCorp often tests the distinction between S3 access errors and DynamoDB lock errors, so candidates mistakenly attribute the lock error to S3 bucket issues (like missing bucket or wrong region) rather than recognizing it as a DynamoDB-specific failure.

How to eliminate wrong answers

Option A is wrong because if the S3 bucket did not exist, Terraform would return an error such as 'bucket does not exist' or 'NoSuchBucket', not a state lock error. Option B is wrong because an incorrect region would cause an 'InvalidAccessKeyId' or 'region not found' error when trying to access S3, not a lock-related error. Option D is wrong because an incorrect key path would result in a 'NoSuchKey' error when trying to read the state file, not a lock contention issue.

55
Multi-Selectmedium

A team is evaluating Terraform for managing their multi-cloud infrastructure. Which TWO statements accurately describe Terraform's purpose and capabilities? (Choose two.)

Select 2 answers
A.Terraform requires all configuration files to be placed in a single directory named 'terraform'.
B.Terraform can provision, update, and destroy infrastructure resources across multiple providers.
C.Terraform's configuration language (HCL) is designed to be human-readable and machine-friendly.
D.Terraform uses an imperative language to specify the exact steps to create resources.
E.Terraform is primarily a configuration management tool for installing software on servers.
AnswersB, C

Terraform's declarative engine plans and applies changes through provider plugins, so a single configuration can create, modify, and delete resources spanning AWS, Azure, and GCP. This directly satisfies the stem's multi-cloud requirement, since each provider's API is abstracted behind the same lifecycle operations.

Why this answer

Option B is correct because Terraform's core purpose is infrastructure as code: the terraform plan/apply/destroy workflow lets it provision, modify, and tear down resources through provider plugins for many clouds (AWS, Azure, GCP, etc.) from one configuration. Option C is correct because Terraform's HashiCorp Configuration Language (HCL) is a declarative, human-readable syntax that is also structured enough for machines to parse and process. Option A is wrong because Terraform does not mandate a directory named 'terraform'; configuration files can live in any working directory and are conventionally named with a .tf extension.

Option D is wrong because Terraform is declarative, not imperative: you describe the desired end state and Terraform computes the steps, rather than specifying exact procedural steps. Option E is wrong because Terraform is a provisioning/IaC tool, not a configuration management tool like Ansible, Chef, or Puppet that installs and configures software on servers.

Exam trap

HashiCorp often tests the distinction between declarative (Terraform) and imperative (e.g., Ansible playbooks) approaches, and candidates may confuse Terraform's purpose with configuration management tools like Chef or Puppet.

56
MCQhard

An organization has a policy that all AWS S3 buckets must have versioning enabled. They want to ensure that even if someone removes the `versioning` block from the configuration, the bucket still has versioning enabled after `terraform apply`. Which lifecycle configuration should they add to the `aws_s3_bucket` resource?

A.`ignore_changes = [versioning]`
B.`replace_triggered_by = [aws_s3_bucket_versioning.this]`
C.`prevent_destroy`
D.`create_before_destroy`
AnswerA

The `ignore_changes` lifecycle meta-argument instructs Terraform to disregard any differences detected for the specified attributes between the configuration and the real-world state during a plan. By setting `ignore_changes = [versioning]`, Terraform will not attempt to revert or modify the `versioning` configuration of the S3 bucket, even if it has been changed outside of Terraform. This is the correct approach to prevent Terraform from undoing an out-of-band modification to a specific attribute, ensuring the external change persists.

Why this answer

`ignore_changes = [versioning]` tells Terraform to disregard any changes to the `versioning` block in the configuration during `terraform apply`. This ensures that even if someone removes the `versioning` block from the HCL, the existing versioning state on the S3 bucket (enabled) remains unchanged, enforcing the organization's policy.

Exam trap

Terraform often tests the distinction between lifecycle meta-arguments that prevent resource destruction (like `prevent_destroy`) versus those that prevent configuration drift (like `ignore_changes`), and the trap here is that candidates confuse `prevent_destroy` with protecting individual attributes from being overwritten.

How to eliminate wrong answers

Option B is wrong because `replace_triggered_by = [aws_s3_bucket_versioning.this]` is used to force resource recreation when a referenced resource changes, not to preserve existing settings; it would cause the bucket to be replaced if the versioning resource is modified, which is not the goal. Option C is wrong because `prevent_destroy` prevents the entire bucket from being destroyed but does not protect the `versioning` configuration from being overwritten or removed during updates. Option D is wrong because `create_before_destroy` controls the order of resource creation and destruction during replacement, but does not prevent changes to the `versioning` block from being applied.

57
MCQmedium

A team is using Terraform Cloud and wants to enforce that all AWS resources created by Terraform have a specific tag. Which feature should they use?

A.Cost estimation
B.Sentinel policies
C.Workspace variables
D.Run tasks
AnswerB

Sentinel policies enforce policy-as-code within Terraform Cloud, evaluating planned changes against rules such as mandatory AWS tags and blocking non-compliant runs before apply. This provides governance across all workspaces, unlike manual review or provider defaults.

Why this answer

Sentinel policies are Terraform Cloud's policy-as-code framework that allows teams to enforce mandatory rules on infrastructure configurations before they are applied. By writing a Sentinel policy that checks for the presence and value of a specific tag on all AWS resources, the team can reject any run that does not comply, ensuring consistent tagging across all resources created by Terraform.

Exam trap

Candidates often confuse Sentinel policies (native policy-as-code in Terraform Cloud) with run tasks (which integrate external tools). Sentinel is the correct choice for enforcing mandatory tags directly within Terraform Cloud's workflow.

How to eliminate wrong answers

Option A is wrong because cost estimation provides a forecast of the cost of resources defined in a plan but does not enforce tagging or any other compliance rules. Option C is wrong because workspace variables store configuration values like region or credentials but cannot enforce policies or validate resource attributes. Option D is wrong because run tasks allow integration with external systems for custom checks or notifications, but they are not a built-in feature for writing and enforcing policy rules like Sentinel; run tasks rely on external tooling and do not natively support policy-as-code for tagging enforcement.

58
Multi-Selectmedium

Which four of the following statements about Terraform state management are correct? (Choose all that apply. There are four correct answers.)

Select 4 answers
.Using remote state storage with a backend like S3 or Azure Storage provides locking to prevent concurrent modifications.
.The `terraform state rm` command can be used to remove a resource from state without destroying the real infrastructure.
.Sensitive data stored in state files can be protected by encrypting the state backend at rest.
.The `terraform import` command updates the state file to include an existing resource, enabling Terraform to manage it.
.Terraform automatically backs up the previous state file every time a new state is written.
.The `terraform state list` command can modify the state file to rename a resource.

Why this answer

Remote state backends like S3 or Azure Storage support state locking (via DynamoDB or Azure Blob lease) to prevent concurrent modifications, ensuring consistency. The `terraform state rm` command removes a resource from state without destroying the real infrastructure, which is useful for detaching management. Encrypting the state backend at rest (e.g., S3 server-side encryption or Azure Storage encryption) protects sensitive data like passwords or keys stored in the state file.

The `terraform import` command updates the state file to include an existing resource, allowing Terraform to take over its management without recreating it.

Exam trap

HashiCorp often tests the misconception that `terraform state list` can modify state or that automatic backups are built-in, when in fact Terraform requires explicit backend versioning or manual backup configuration.

59
MCQhard

After applying the configuration above, the user changes the AMI to a new value and runs 'terraform apply'. Assuming the new AMI triggers a recreate, what happens during the apply?

A.The existing instance is deleted before the new one is created.
B.Both instances run simultaneously only if the instance type allows it.
C.The new instance is created first, then the old one is deleted.
D.The plan fails because AMI change with create_before_destroy is not allowed.
AnswerA

This statement is correct. When an immutable attribute, such as the Amazon Machine Image (AMI) for an EC2 instance, is modified in the Terraform configuration, Terraform's default behavior is to destroy the existing resource before creating its replacement. This 'destroy-then-create' sequence is the standard approach for resource recreation unless explicitly overridden by `lifecycle` settings. This ensures resource consistency but typically results in a period of downtime for the affected service.

Why this answer

Terraform's default lifecycle for resource replacement is to destroy the existing resource first, then create the new one. This is the standard behavior unless `create_before_destroy` is explicitly set to `true`. The AMI change triggers a recreate, and by default, the old instance is deleted before the new one is provisioned.

Exam trap

A common trap is assuming that Terraform defaults to create-before-destroy to minimize downtime. In reality, the default is destroy-before-create; you must explicitly set `create_before_destroy = true` to change this behavior.

How to eliminate wrong answers

Option A is wrong because Terraform does not delete the existing instance before creating the new one when a recreate is triggered; it creates the new instance first to avoid downtime, unless 'create_before_destroy' is explicitly set to false or the resource type defaults to destroy-before-create. Option B is wrong because both instances running simultaneously is not dependent on the instance type; it is a result of Terraform's default 'create_before_destroy' behavior for resources that support replacement, and the instance type does not control this lifecycle ordering. Option D is wrong because an AMI change with 'create_before_destroy' is fully allowed and is a common scenario; Terraform supports this lifecycle configuration and will plan the creation of the new instance before destroying the old one.

60
MCQmedium

A team uses Terraform Cloud for remote state management. They want to ensure that state file changes are only made through the Terraform Cloud API and not through direct access to the storage backend. Which feature should they enable?

A.Sentinel policy enforcement
B.Remote state locking
C.VCS integration
D.Team tokens
AnswerB

Remote state locking is a critical mechanism within Terraform Cloud that ensures state modifications occur exclusively through its controlled API. When a Terraform operation (like a plan or apply) begins, Terraform Cloud acquires a lock on the state, preventing concurrent modifications and ensuring consistency. This lock is managed by Terraform Cloud, effectively forcing all state-altering operations to pass through its API, thereby preventing any direct, uncontrolled access or modification of the state file.

Why this answer

Remote state locking ensures that only one operation can modify the Terraform state at a time. When using Terraform Cloud as the remote backend, locking is automatically managed and prevents any direct modifications to the state file outside of a Terraform run. Because Terraform Cloud handles locking through its API, any attempt to directly access the storage backend would fail to acquire a lock, thus preventing changes.

This effectively enforces that all state modifications go through the Terraform Cloud API.

Exam trap

The trap is that many candidates assume Sentinel policy enforcement is needed to prevent direct state modifications, but Terraform Cloud's remote backend automatically uses state locking, which ensures only API-based changes are possible.

How to eliminate wrong answers

Option B is wrong because remote state locking prevents concurrent operations on the same state file but does not prevent direct access to the storage backend; it only manages locking during Terraform runs. Option C is wrong because VCS integration automates runs from version control commits but does not restrict direct state file access via the storage backend API. Option D is wrong because team tokens authenticate API calls but do not enforce that state changes must originate from the Terraform Cloud API; they can be used to directly access the storage backend if permissions allow.

61
MCQeasy

An operator runs `terraform apply` and receives an error that the state file is locked. What is the most likely cause?

A.The state file is outdated and needs refresh
B.The configuration has a syntax error
C.Another user is running a Terraform operation
D.The user lacks write permissions to the state file
AnswerC

Terraform state locking is a critical mechanism designed to prevent data corruption when multiple operators attempt to modify the state file concurrently. When one user initiates a `terraform apply` or other state-modifying operation, Terraform attempts to acquire an exclusive lock on the state. If another user is already holding that lock, the subsequent operation will fail with a state lock error, indicating that the state is currently in use and preventing simultaneous, conflicting updates.

Why this answer

Terraform uses a state locking mechanism (typically via a backend like S3 with DynamoDB, or Consul) to prevent concurrent operations from corrupting the state file. When another user or process is running a Terraform operation (e.g., `apply`, `plan`, `destroy`), the lock is held, and any subsequent `terraform apply` will fail with a 'state file is locked' error. This is a fundamental safety feature to ensure state consistency.

Exam trap

The trap here is that candidates confuse state locking with file permissions (Option D) or assume the error is due to a stale state (Option A), but The TF-003 exam specifically tests the understanding that locking is a concurrency control mechanism, not a permission or syntax issue.

How to eliminate wrong answers

Option A is wrong because an outdated state file does not cause a lock error; it would instead cause a refresh prompt or drift detection, not a lock conflict. Option B is wrong because a syntax error in the configuration would be caught during `terraform validate` or `plan`, not during `apply` as a state lock error. Option D is wrong because insufficient write permissions would result in a permissions error (e.g., 'AccessDenied' or 'permission denied'), not a lock error; locking is a separate mechanism from filesystem permissions.

62
MCQeasy

A team is using Terraform for infrastructure as code. They want to ensure that the state file is stored securely and can be accessed by multiple team members. Which backend type should they use?

A.The -state flag pointing to a network share
B.Using the -lock=false flag
C.Local backend with .terraform directory version-controlled
D.Remote backend such as Amazon S3 with DynamoDB state locking
AnswerD

A remote backend, such as Amazon S3, provides a centralized, highly available, and durable location for storing the Terraform state file, making it securely accessible to all team members. Coupling S3 with DynamoDB for state locking is crucial, as it ensures that only one user can acquire a lock and modify the state at any given time. This mechanism effectively prevents race conditions, state file corruption, and ensures infrastructure consistency across a collaborative team environment.

Why this answer

A remote backend like Amazon S3 with DynamoDB state locking provides secure, centralized storage for the Terraform state file and enables state locking to prevent concurrent modifications. This setup ensures that multiple team members can safely access and update the state without conflicts, while S3 offers encryption and access control. Local backends or network shares lack these locking and security features, making them unsuitable for team collaboration.

Exam trap

HashiCorp often tests the misconception that version-controlling the state file or using a simple network share is sufficient for team collaboration, when in fact proper state locking and remote storage are required to prevent corruption and ensure consistency.

How to eliminate wrong answers

Option A is wrong because using the -state flag to point to a network share does not provide state locking, leading to potential state corruption when multiple team members run Terraform concurrently. Option B is wrong because using the -lock=false flag disables state locking entirely, which can cause race conditions and state file corruption in a team environment. Option C is wrong because version-controlling the .terraform directory (which contains the local state file) is insecure and violates best practices, as state files often contain sensitive data and are not designed for concurrent access via version control systems.

63
MCQeasy

Which statement best describes 'immutable infrastructure' in the context of IaC?

A.Configuration is changed via patches and updates
B.Servers are never modified after deployment; new ones are created for updates
C.Resources are shared across environments
D.Infrastructure is version-controlled
AnswerB

This statement accurately defines immutable infrastructure, a paradigm where once a server or resource is deployed, it is never modified. Any required changes, such as software updates, configuration adjustments, or security patches, necessitate the creation and deployment of an entirely new server instance with the desired modifications. The old instance is then decommissioned, ensuring consistency and preventing configuration drift across the infrastructure.

Why this answer

Immutable infrastructure means servers, once deployed, are never modified in place; any change (patch, config update, new version) results in building a new image and replacing the old instance. This eliminates configuration drift and makes deployments reproducible and rollback-friendly. It is a core IaC pattern where infrastructure is treated like disposable, versioned artifacts.

Exam trap

The trap is equating 'version-controlled infrastructure' with 'immutable infrastructure'; candidates must distinguish versioning (a practice) from immutability (a deployment model where instances are never modified after creation).

How to eliminate wrong answers

Option A is wrong because patching and updating existing servers is the definition of mutable infrastructure, the opposite of immutable. Option C is wrong because sharing resources across environments is a multi-tenancy or environment-isolation concern, not a description of immutability. Option D is wrong because version-controlling infrastructure is a property of IaC generally, but it does not by itself mean the infrastructure is immutable — you can version-control mutable configurations too.

64
MCQeasy

A developer is working on a Terraform configuration that manages a single resource. They want to import an existing AWS EC2 instance into state. Which command should they use?

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

The `terraform import` command is the designated tool for bringing existing infrastructure resources, which were provisioned outside of Terraform's management, into the Terraform state file. It establishes a link between a specified remote resource and a corresponding resource block defined in the Terraform configuration. This crucial command enables developers to adopt pre-existing infrastructure and manage it subsequently with Terraform, integrating it into the desired state.

Why this answer

`terraform import` is the dedicated command for bringing an existing infrastructure resource (like an AWS EC2 instance) under Terraform management by attaching it to a resource block in the state file. It requires the resource address and the provider-specific ID (e.g., `aws_instance.my_instance i-1234567890abcdef0`) to map the real-world resource into the Terraform state without modifying the resource itself.

Exam trap

HashiCorp often tests the distinction between `terraform import` (which only updates state) and `terraform apply` (which modifies infrastructure), so the trap here is that candidates mistakenly think `terraform apply` can also import resources because it can create new ones, but it cannot attach to an existing resource that is not already in state.

How to eliminate wrong answers

Option A is wrong because `terraform apply` is used to create, update, or destroy resources based on the configuration, not to import existing resources into state. Option B is wrong because `terraform refresh` updates the state file to match real-world infrastructure but does not add new resources that are not already tracked in state; it cannot import a resource that has no corresponding state entry. Option D is wrong because `terraform state mv` moves a resource from one state address to another within the same state file or between state backends, but it does not bring an external resource into state for the first time.

65
MCQmedium

A configuration defines a variable `instance_type` with a default value `t2.micro`. After running `terraform apply`, the operator notices that the instances are being created with type `t2.small`. They check the configuration file and see the default is `t2.micro`. What is the most likely cause?

A.The variable declaration was changed after apply.
B.The state file stores the variable value and overrides the default.
C.A `terraform.tfvars` file in the working directory sets the variable to `t2.small`.
D.The `instance_type` attribute was changed by a lifecycle rule.
AnswerC

A `terraform.tfvars` file located in the working directory is one of the primary mechanisms Terraform uses to automatically load variable values. When present, values defined within this file take precedence over any `default` values specified directly within the variable's declaration in the configuration. This behavior ensures that specific deployments can easily override general defaults for resources like `instance_type`.

Why this answer

Terraform automatically loads any file named `terraform.tfvars` or `*.auto.tfvars` in the working directory, and the variable values defined in these files override the default values declared in the configuration. Even though the configuration file shows `instance_type` defaulting to `t2.micro`, the presence of a `terraform.tfvars` file setting `instance_type = "t2.small"` will cause Terraform to use `t2.small` during `apply`, explaining the observed behavior.

Exam trap

The TF-003 exam often tests the subtle distinction between where variable values are stored (state vs. variable files) and the automatic loading behavior of `terraform.tfvars`, leading candidates to incorrectly blame the state file or lifecycle rules for value overrides.

How to eliminate wrong answers

Option A is wrong because changing the variable declaration after `apply` would not retroactively affect already-created instances; the operator checked the configuration and saw the default unchanged, so this does not explain why instances were created with a different type. Option B is wrong because the state file stores resolved resource attributes (like the actual `instance_type` used), not the variable default value, and it does not override configuration defaults — it reflects what was applied. Option D is wrong because lifecycle rules (e.g., `create_before_destroy`, `prevent_destroy`) do not modify resource attribute values like `instance_type`; they control the order or protection of resource operations, not the values themselves.

66
Multi-Selectmedium

Which TWO are valid methods to import existing infrastructure into Terraform?

Select 2 answers
A.Use 'terraform state rm' to remove existing state before running apply.
B.Run 'terraform import' with the resource address and ID.
C.Use 'terraform console' to inspect and import.
D.Add resource blocks manually and run 'terraform import' for each resource.
E.Use 'terraform init -migrate-state' to import from another backend.
AnswersB, D

Running 'terraform import' with the resource address and ID is a correct and fundamental method for bringing existing infrastructure under Terraform's management. This command explicitly takes a pre-existing cloud resource, identified by its unique cloud provider ID, and associates it with a corresponding resource block defined in the Terraform configuration. This action adds the resource's details to the state file, allowing Terraform to manage its lifecycle going forward.

Why this answer

`terraform import` is the primary command for bringing existing infrastructure under Terraform management. It requires both the resource address (as defined in your configuration) and the provider-specific ID of the real-world object. This command maps the existing resource into the Terraform state, enabling subsequent `apply` operations to manage it.

Exam trap

Candidates often mistakenly believe that `terraform import` automatically generates configuration code, but it only updates the state file. You must manually write the resource block before running import.

67
Multi-Selecthard

Which THREE variable declarations are valid in Terraform?

Select 3 answers
A.variable "enabled" { type = bool default = true }
B.variable "tags" { type = map(string) default = {} }
C.variable "region" { type = string default = "us-east-1" }
D.variable "names" { type = list(string) default = "name" }
E.variable "count" { type = number default = "1" }
AnswersA, B, C

This variable declaration is valid because the `type` constraint is correctly set to `bool`, and the `default` value provided, `true`, is a literal boolean value. Terraform successfully validates that the default value's type precisely matches the explicitly declared `bool` type, ensuring strict type consistency for the variable. This configuration allows the variable to accept only `true` or `false` values.

Why this answer

Terraform variable declarations require a `type` argument and optionally a `default` value. Here, `type = bool` is a valid primitive type, and `default = true` provides a boolean default, which matches the type constraint. This syntax follows Terraform's variable block specification, where the default value must be compatible with the declared type.

Exam trap

Terraform often tests the strict type-default compatibility rule, where candidates mistakenly assume Terraform will implicitly convert a string to a number or a single value to a list, but Terraform requires exact type matching for defaults.

68
MCQeasy

A developer is writing a Terraform configuration that uses a `variable` block to define an input variable `region` with a default value of `us-west-2`. The developer wants to ensure that the variable can only be set to one of three approved regions: `us-west-2`, `us-east-1`, or `eu-west-1`. Which approach should the developer use?

A.Set the variable type to `string` and use a `default` value that is a list of the approved regions.
B.Define the variable with type `list(string)` and set the default to the approved regions, then use `contains` in the resource.
C.Add a `validation` block with a `condition` that checks if `var.region` is in the list of approved regions.
D.Use the `allowed_values` argument in the `variable` block to specify the permitted regions.
AnswerC

The `validation` block within a `variable` allows custom validation rules using a `condition` expression and an `error_message`. By checking if `var.region` is contained in the list of approved regions, the developer enforces the constraint at plan time. If the condition is false, Terraform returns the specified error message and halts execution.

Why this answer

Terraform's `variable` block supports `validation` blocks that define a `condition` and an `error_message`. The condition can use functions like `contains` to check if the provided value is within a list of approved options. This validation occurs during plan and apply, preventing invalid values from being used.

It is the standard way to enforce custom constraints on input variables.

Exam trap

The trap here is assuming that Terraform has a built-in `allowed_values` argument or that changing the variable type can restrict values, when only a `validation` block provides that capability.

69
MCQhard

A team has a monolithic Terraform configuration managing multiple AWS accounts. They want to decompose it into smaller configurations that can be managed independently. What is the recommended strategy?

A.Split the configuration into separate directories per account and resource type, and use remote state sharing.
B.Use Terraform workspaces to separate environments within the same configuration.
C.Create a single super-module that contains all resources.
D.Move everything to Terraform Cloud and use different workspaces.
AnswerA

Splitting a monolithic configuration into separate directories, perhaps by account or resource type, creates smaller, more manageable units of infrastructure. Each directory then manages its own independent state file, typically stored remotely (e.g., S3, Azure Blob Storage, Terraform Cloud). This approach allows different teams or individuals to work on distinct parts of the infrastructure concurrently without interfering with others, facilitating independent deployment, testing, and lifecycle management for specific components or environments. It directly addresses the challenges of a monolithic setup by promoting modularity and reducing blast radius.

Why this answer

Splitting a monolithic Terraform configuration into separate directories per account and resource type, combined with remote state sharing, enables independent management of each configuration while allowing them to consume outputs from one another via `terraform_remote_state` data sources. This approach aligns with the recommended practice of using separate root modules for distinct environments or accounts, avoiding tight coupling and state lock contention.

Exam trap

A common misconception in the Terraform exam is that Terraform workspaces (or Terraform Cloud workspaces) are a valid decomposition strategy, but they only separate state files for the same configuration, not the configuration itself, which fails the requirement for independent management.

How to eliminate wrong answers

Option B is wrong because Terraform workspaces are designed for managing multiple environments (e.g., dev, staging, prod) within the same configuration and state backend, but they do not decompose a monolithic configuration into independently managed pieces; all resources still reside in a single state file per workspace, which defeats the goal of independent management. Option C is wrong because creating a single super-module that contains all resources would increase complexity and coupling, making independent management impossible and violating modular design principles. Option D is wrong because moving to Terraform Cloud and using different workspaces is essentially the same as using local workspaces—it does not decompose the configuration into smaller, independently managed configurations; it only shifts the state management to a remote service without addressing the monolithic structure.

70
MCQhard

A company has a monolithic Terraform configuration that manages all infrastructure. As the infrastructure grows, plan and apply times become very long. They want to break the configuration into smaller, independent units to improve performance and reduce blast radius. Which approach should they take?

A.Refactor into multiple Terraform modules and use a single root module
B.Split the configuration into separate root modules, each with its own state file, and use data sources to share outputs
C.Use Terraform workspaces to separate environments
D.Use terraform state mv to reorganize resources into different state files
AnswerB

Splitting the configuration into separate root modules, each managing a distinct subset of infrastructure with its own state file, is the recommended approach for large-scale deployments. This strategy significantly reduces the blast radius of changes, as an issue in one module's apply operation will not affect others. It also drastically improves `terraform plan` and `apply` performance by allowing operations to target smaller, independent scopes, with outputs shared between modules using data sources like `terraform_remote_state`.

Why this answer

Splitting the monolithic configuration into separate root modules, each with its own state file, reduces the scope of `terraform plan` and `terraform apply` operations, improving performance. Using data sources to share outputs between root modules allows independent management while maintaining necessary dependencies, which also reduces the blast radius by isolating failures to a single root module.

Exam trap

The trap here is that candidates confuse Terraform modules (which are reusable components within a single root module) with root modules (which are independent stateful configurations), leading them to choose Option A instead of B.

How to eliminate wrong answers

Option A is wrong because using multiple Terraform modules within a single root module still results in a single state file and a single plan/apply operation, so it does not reduce plan/apply times or blast radius. Option C is wrong because Terraform workspaces are designed to manage multiple environments (e.g., dev, prod) with the same configuration and state backend, not to break a monolithic configuration into smaller independent units; they do not reduce the scope of a single plan/apply. Option D is wrong because `terraform state mv` is a command to move individual resources between state files within the same backend, but it does not architecturally separate the configuration into independent root modules; it is a manual, error-prone operation that does not address the need for independent lifecycle management.

71
MCQeasy

Refer to the exhibit. A developer runs 'terraform plan' and receives the following error: 'Error: InvalidAMIID.NotFound: The image id '[ami-0c55b159cbfafe1f0]' does not exist'. What is the most likely cause?

A.The 'tags' block is missing a required 'ami' tag.
B.The AMI is not available in the region specified in the provider configuration.
C.The 'ami' argument is misspelled; it should be 'image_id'.
D.The AMI ID is malformed; it should start with 'ami-' but the rest is incorrect.
AnswerB

Amazon Machine Images (AMIs) are inherently regional resources within AWS. An AMI ID, such as 'ami-0abcdef1234567890', uniquely identifies an image within a specific AWS region. If a Terraform configuration's AWS provider is set to 'us-east-1', but the specified AMI ID only exists in 'us-west-2', Terraform will fail during the plan phase, reporting that the AMI cannot be found in the 'us-east-1' region. This is a common cause of "AMI not found" errors, even if the AMI exists elsewhere.

Why this answer

The error 'InvalidAMIID.NotFound' indicates that the specified AMI ID does not exist in the AWS region configured in the Terraform provider block. AMI IDs are region-specific; an AMI available in us-east-1 may not exist in eu-west-2. Terraform validates the AMI against the region's EC2 API, and if the ID is not found, it throws this exact error.

Exam trap

HashiCorp often tests the misconception that AMI IDs are globally unique across all AWS regions, when in fact they are region-specific, leading candidates to overlook the provider region configuration.

How to eliminate wrong answers

Option A is wrong because the 'tags' block is optional and does not require an 'ami' tag; the error is about AMI existence, not missing tags. Option C is wrong because the correct Terraform argument for an AMI ID is 'ami', not 'image_id'; 'image_id' is used in other tools like Packer, not in Terraform's aws_instance resource. Option D is wrong because the AMI ID format 'ami-0c55b159cbfafe1f0' is valid (starts with 'ami-' followed by a hex string); the error states the image does not exist, not that the format is malformed.

72
MCQmedium

An organization uses Terraform workspaces to manage multiple environments (dev, staging, prod) with the same configuration. What is the primary benefit of using workspaces for state management?

A.Workspaces reduce the number of Terraform configurations needed
B.Workspaces automatically synchronize state across team members
C.Each workspace has its own independent state file, preventing environment conflicts
D.Workspaces enable role-based access control to state
AnswerC

This statement is correct because the fundamental purpose of Terraform workspaces is to provide independent state files for different environments or contexts. When a new workspace is created or selected, Terraform ensures that all subsequent operations, like `plan` and `apply`, interact with that specific, isolated state. This critical separation prevents accidental modifications or resource conflicts between distinct environments, such as development, staging, and production, even when using the exact same configuration code.

Why this answer

Terraform workspaces allow each environment (dev, staging, prod) to maintain its own independent state file within the same backend configuration. This isolation prevents state conflicts, such as one environment's resources being accidentally overwritten or destroyed by operations intended for another environment, which is critical for safe multi-environment management.

Exam trap

The trap here is that candidates confuse workspaces with environment-specific configurations or assume workspaces provide built-in state locking or access control, when in fact they only provide state isolation and require separate backend mechanisms for locking and RBAC.

How to eliminate wrong answers

Option A is wrong because workspaces do not reduce the number of Terraform configurations; they reuse the same configuration but separate state, so you still need a single configuration (or module) that works across environments. Option B is wrong because workspaces do not automatically synchronize state across team members; state synchronization requires a remote backend (e.g., S3 with DynamoDB locking) and is not a built-in feature of workspaces themselves. Option D is wrong because workspaces do not enable role-based access control (RBAC) to state; RBAC is implemented at the backend level (e.g., IAM policies on S3 buckets) and is independent of workspace functionality.

73
MCQhard

Refer to the exhibit. After applying this configuration, a team member manually changes the instance type to 't2.small' via the AWS console. The next `terraform plan` shows a change to revert to 't2.micro'. What does this demonstrate?

A.Terraform's drift detection only
B.Immutable infrastructure pattern
C.Terraform's desired state reconciliation
D.A misconfiguration in the Terraform code
AnswerC

Terraform operates on the principle of desired state configuration, where the HCL code defines the intended end-state of the infrastructure. When a manual modification introduces drift, Terraform's `plan` command identifies this deviation by comparing the actual infrastructure with the declared configuration. It then generates a plan to reconcile these differences, proposing actions to bring the actual state back into alignment with the desired state defined in the configuration.

Why this answer

Terraform operates on a desired state model: the configuration file defines the target state (t2.micro), and `terraform plan` detects that the actual state (t2.small) has diverged from it. The plan proposes to revert the instance type to t2.micro, demonstrating Terraform's reconciliation of the actual infrastructure back to the declared desired state. This is not merely drift detection (which only reports differences) but active enforcement of the desired configuration.

Exam trap

The Terraform exam often tests the distinction between drift detection (passive observation) and desired state reconciliation (active correction). The trap here is that candidates confuse the two, thinking Terraform only reports drift when it actually plans to enforce the declared state.

How to eliminate wrong answers

Option A is wrong because drift detection only identifies differences between actual and desired state without automatically planning to revert changes; Terraform's plan to revert shows reconciliation, not just detection. Option B is wrong because immutable infrastructure pattern involves replacing resources entirely (e.g., creating a new instance) rather than modifying an existing one, whereas here Terraform plans an in-place change to the instance type. Option D is wrong because the configuration is correct; the manual change via the console is an out-of-band modification that Terraform is designed to correct, not a misconfiguration in the code.

74
MCQeasy

A small startup is using Terraform to deploy AWS resources. They have two separate environments: development and production. Currently, they manage two sets of Terraform configuration files in different directories, each with its own state file stored locally. The CEO wants to reduce duplication and simplify management. The team decides to restructure into a single configuration with workspaces. After implementing workspaces, they run `terraform workspace new dev` and `terraform workspace new prod`, then `terraform apply` in the dev workspace. However, when they switch to prod and run `terraform apply`, the plan shows that Terraform wants to recreate all resources instead of managing the existing production resources. What is the most likely reason for this behavior?

A.Workspaces cannot be used for different environments; only for temporary feature branches.
B.The Terraform configuration uses the same resource names in both workspaces, causing conflicts.
C.The team did not migrate the existing production state into the 'prod' workspace.
D.The team must configure a remote backend for workspaces to function correctly.
AnswerC

This is the correct explanation. When a new workspace, such as 'prod', is created, it initializes with an empty state file, meaning it has no knowledge of existing infrastructure. Any pre-existing production resources are not automatically associated with this new workspace; their state must be explicitly migrated or imported into the 'prod' workspace's state file using commands like `terraform state mv` or `terraform import` to bring them under Terraform management within that specific context.

Why this answer

When the team restructured into a single configuration with workspaces, they created new empty workspaces (`dev` and `prod`) but did not migrate the existing production state file into the `prod` workspace. Terraform workspaces maintain separate state files, so without importing the existing production state into the `prod` workspace, Terraform has no record of the existing production resources and plans to create them from scratch. The `terraform workspace new` command creates a fresh, empty state for that workspace.

Exam trap

HashiCorp often tests the misconception that workspaces automatically inherit or share state from previous configurations, when in fact each workspace starts with a completely empty state unless explicitly migrated.

How to eliminate wrong answers

Option A is wrong because workspaces are explicitly designed to manage multiple environments (e.g., dev, staging, prod) from a single configuration, not just for temporary feature branches. Option B is wrong because resource names within a workspace are scoped to that workspace's state; using the same resource names across workspaces does not cause conflicts—each workspace maintains its own independent state. Option D is wrong because while remote backends are recommended for team collaboration, workspaces function perfectly well with local backends; the issue here is the missing state migration, not the backend type.

75
MCQeasy

What does Terraform's declarative model mean for infrastructure changes?

A.You manually approve each step
B.You describe the desired end state
C.You must specify the order of creation
D.You write scripts to create resources
AnswerB

Terraform's declarative model fundamentally means you define the desired final configuration of your infrastructure using HashiCorp Configuration Language (HCL). Instead of providing a sequence of commands to execute, you simply describe 'what' your infrastructure should look like, including resources, their properties, and relationships. Terraform then intelligently calculates the 'how' — the precise actions needed to achieve that specified end state from the current infrastructure.

Why this answer

Terraform's declarative model means you describe the desired end state of your infrastructure in configuration files, and Terraform determines the actions needed to reach that state. You do not specify the sequence of API calls or the order of resource creation; Terraform builds a dependency graph and executes operations in the correct order automatically. This contrasts with imperative scripting, where you must define each step explicitly.

Exam trap

TF-004 often tests the confusion between declarative (describe end state) and imperative (specify steps/order) — candidates may pick 'specify order of creation' thinking Terraform needs explicit sequencing, when it actually infers it.

How to eliminate wrong answers

Option A is wrong because manual approval of each step describes a gated workflow (like Terraform's plan/apply approval), not the declarative model itself — declarative means you state the end state, not that you approve each action. Option C is wrong because specifying the order of creation is the imperative approach; Terraform infers order from dependencies in the declarative configuration. Option D is wrong because writing scripts to create resources is imperative/procedural, the opposite of Terraform's declarative paradigm.

Page 1 of 6

Page 2

All pages