Courseiva

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

428 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 interface with different APIs, allowing Terraform to manage diverse infrastructure.

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

After running `terraform state mv` to rename a resource, the resource's state binding is lost and the resource cannot be managed. Which command should be run to restore the state binding?

A.terraform state push
B.terraform state show
C.terraform state rm
D.terraform refresh
E.terraform import
AnswerE

After terraform state mv renames a resource in the state, the provider might lose its ability to correctly identify the corresponding remote object if the underlying resource ID or its lookup mechanism changes. terraform import allows you to explicitly tell Terraform to bring an existing remote resource, identified by its actual cloud provider ID, under management for a specific resource block in your configuration. This effectively re-establishes the binding by creating a new, correct state entry that links the configuration to the live infrastructure.

Why this answer

After a failed `terraform state mv`, the resource mapping in the state may become corrupted or lost. To restore the binding, use `terraform import` to re-import the existing resource into the state. Option E, `terraform import`, is correct.

Option D, `terraform refresh`, updates the state to match real infrastructure but does not restore a missing resource binding.

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

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

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

6
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

This is the fundamental difference.

Why this answer

Declarative IaC, as used in Terraform with HCL, allows you to define the desired end state of infrastructure (e.g., 'I want an AWS EC2 instance with AMI ami-0c55b159cbfafe1f0 and instance type t2.micro'), and the tool automatically determines the necessary steps to achieve that state. In contrast, imperative IaC, such as using AWS CLI commands or Ansible playbooks with explicit 'command' modules, requires you to specify each step (e.g., 'run aws ec2 run-instances, then wait, then tag'). This fundamental difference in approach is a core concept in the TF-003 exam.

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.

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

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

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

10
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

The plan shows changes to attributes like AMI and instance type. Since the configuration hasn't changed, these differences indicate that the instance was modified manually, likely via the AWS console. This is a classic example of configuration drift, where the actual infrastructure state diverges from the desired state defined in Terraform configuration.

Option D correctly identifies this cause.

11
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 validate resource attributes.

Why this answer

Terraform Cloud's Sentinel policy framework allows you to define policy-as-code rules that can enforce mandatory tags on resources. By writing a Sentinel policy that checks for the presence of specific tags (e.g., 'Environment', 'Owner') during the plan phase, you can block or warn on any resource creation that lacks those tags, ensuring compliance with organizational tagging standards.

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.

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

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

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

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

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

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

20
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

The state file maps Terraform configurations to real-world resources, allowing Terraform to track resource metadata and detect drift.

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

22
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

Reproducible environments (C) are a key benefit because IaC allows you to consistently provision identical infrastructure from the same configuration, eliminating environment drift. Automated documentation (D) is another benefit because IaC code serves as a living, version-controlled description of your infrastructure. A is false: IaC does not guarantee cost optimization; costs depend on resource usage, not just code.

B is false: IaC does not remove the need for cloud providers; it relies on them. E is false: while IaC reduces manual errors, it does not eliminate all of them (e.g., logic errors in code).

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

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

25
MCQmedium

What is the most likely cause of this error?

A.The module requires a version constraint.
B.The module source path does not exist.
C.The required_version is incompatible with the module.
D.The module input variable 'vpc_id' is not defined in the module.
AnswerB

When a local module is referenced using a relative or absolute file system path, Terraform attempts to locate and read the module's configuration files within that specified directory. If the directory indicated by the `source` attribute, such as './modules/networking', does not exist on the file system, Terraform cannot proceed with loading the module. This directly results in an error indicating that the module source path is invalid or cannot be found, preventing any further processing of the module's contents.

Why this answer

The error message indicates that the module source path does not exist. Terraform cannot find the specified local path for the module. Option A is incorrect because version constraints are not required for local module sources; they are used for registry modules.

Option C is incorrect because the `required_version` setting in Terraform configuration controls the Terraform version, not module sourcing. Option D is incorrect because the error is about locating the module source, not about an undefined input variable.

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
Multi-Selecthard

Which THREE of the following are valid ways to reference a module output value within the same Terraform configuration?

Select 4 answers
A.In the count or for_each of another module or resource.
B.In a resource argument, e.g., subnet_id = module.vpc.public_subnet_ids
C.In a data source definition as a filter.
D.In a provider block to set endpoints.
E.In a locals block to perform transformations.
AnswersA, B, C, E

Module outputs can control the number of instances or the iteration set of other resources.

Why this answer

Options A, B, C, and E are correct ways to reference a module output value within the same Terraform configuration. Module outputs can be used in `count` or `for_each` meta-arguments (A), directly in resource arguments (B), in data source filter blocks (C), and in `locals` blocks for transformation (E). Option D is incorrect because provider blocks require static configuration and cannot reference module outputs; provider configurations are resolved before any resources or modules.

Exam trap

Module outputs are valid in resource arguments, count/for_each, data source filter blocks, and locals blocks. They cannot be used in provider blocks because provider configurations are static and resolved before any other resources are evaluated.

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

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

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

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

32
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

This command handles the migration.

Why this answer

`terraform init` is the command that initializes the backend configuration and, when a backend block is added to the configuration, automatically prompts to migrate the existing local state file to the new remote backend. This command handles the state migration seamlessly without requiring manual intervention, ensuring the state file is copied and the backend is configured correctly.

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.

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

The 'terraform state rm' command removes the resource from the state file but does not destroy the actual infrastructure. The resource still exists in AWS. The next 'terraform plan' sees that the resource is not in state but the configuration still exists, so it plans to create a new resource with the same configuration.

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 modules; running terraform init with -upgrade or clearing the .terraform directory forces a fresh download.

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 steps to the numbered slots on the right, or tap a step then tap a slot.

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

Why this order

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

Correct. The DynamoDB table must exist before 'terraform init' because the backend will attempt to use it for locking during subsequent operations, and Terraform does not create the table automatically.

Why this answer

The DynamoDB table must exist before running `terraform init`, because the table is required for state locking and Terraform does not create it automatically. Option B is correct: enabling S3 bucket versioning provides consistency checks and allows recovery from accidental state deletion or corruption. Option C is incorrect: the `key` argument in the backend configuration is mandatory to specify the path for the state file in the S3 bucket.

Option D is incorrect: by default, the S3 backend does not encrypt state at rest; encryption must be explicitly enabled using the `encrypt` argument or an environment variable. Option E is incorrect: state locking prevents concurrent writes but does not block read operations; reading the state file is still allowed while it is locked.

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

Referencing a specific Git tag (e.g., v1.0.0) ensures that each environment uses a fixed version of the module until the tag is explicitly updated. This prevents unintended changes from the master branch affecting environments. Option B is incorrect because separate branches can still receive updates that may cause unintended changes; it does not solve the version pinning problem.

Option C is incorrect because Terragrunt is an additional tool that manages dependencies but does not inherently enforce module version pinning without additional configuration, and it adds complexity. Option D is incorrect in this context because the team already uses a Git repository; migrating to the Terraform Registry is not an immediate solution and may not be feasible, whereas using Git tags is a straightforward native approach.

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

46
MCQhard

An organization uses Terraform with AWS S3 backend and DynamoDB for state locking. During a plan, you receive an error: 'Error acquiring the state lock'. The lock information in DynamoDB shows a lock from a previous session that crashed. What is the most appropriate next step?

A.Run terraform unlock
B.Run terraform force-unlock with the lock ID
C.Wait for the lock to expire automatically
D.Delete the lock item from DynamoDB table directly
AnswerB

This command releases the lock from the previous session.

Why this answer

When a Terraform process crashes while holding a state lock, the lock remains in DynamoDB and must be manually released. The `terraform force-unlock` command with the specific lock ID is the designed mechanism to override a stale lock, as it directly interacts with the DynamoDB locking table to remove the lock item. This is the safest and most appropriate method, as it ensures the lock is released in a controlled manner without risking state corruption.

Exam trap

HashiCorp often tests the distinction between `terraform unlock` (a non-existent command) and `terraform force-unlock` (the actual command), trapping candidates who assume a generic 'unlock' verb exists without knowing the exact syntax.

How to eliminate wrong answers

Option A is wrong because `terraform unlock` is not a valid Terraform command; the correct command is `terraform force-unlock`. Option C is wrong because DynamoDB state locks do not have a built-in automatic expiration or TTL; they persist indefinitely until explicitly removed, so waiting is ineffective. Option D is wrong because manually deleting the lock item from the DynamoDB table bypasses Terraform's safety checks and could lead to state corruption or concurrent access issues if another process is actively using the lock.

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 team is migrating from local state to an S3 remote backend. They have existing state files in the working directory. After configuring the backend block and running `terraform init`, what is the correct next step to migrate the existing state?

A.Execute `terraform init` and confirm yes when prompted to copy existing state
B.Run `terraform state push` to upload the local state
C.Delete the local state file and run `terraform apply` to recreate
D.Manually copy the state file to S3 using AWS CLI
AnswerA

When migrating from a local state to a remote backend like S3, `terraform init` is the authoritative command. It detects the change in the `backend` configuration block within your `.tf` files. Upon execution, Terraform prompts the user to confirm the migration, offering to copy the existing local `terraform.tfstate` file to the newly configured remote backend, ensuring a seamless and consistent transition of the state management.

Why this answer

When migrating from local to remote state, Terraform automatically prompts to copy existing state during `terraform init` if the backend block changes. Selecting 'yes' will migrate the state. Option A correctly describes this process.

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

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

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 AccessDenied indicates the IAM role lacks permission to set the policy on that bucket.

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
Multi-Selectmedium

Which TWO of the following are valid ways to import existing infrastructure into Terraform management? (Choose TWO.)

Select 2 answers
A.Use 'terraform validate' to automatically import resources.
B.Use 'terraform state rm' to remove resources from state, then re-add them.
C.Use the 'terraform import' command with the resource address and ID.
D.Write the configuration manually and run 'terraform plan' to refresh state, then adjust.
E.Run 'terraform apply' with an empty configuration to detect resources.
AnswersC, D

This is the primary method for importing existing resources.

Why this answer

'terraform import' is the dedicated command to bring existing infrastructure under Terraform management by associating a real-world resource ID with a resource address in state. Option D is correct because you can manually write configuration that matches the existing resource, then run 'terraform plan' to refresh state and detect any drift, allowing you to adjust the configuration until the plan shows no changes.

Exam trap

HashiCorp often tests the misconception that 'terraform validate' or 'terraform apply' can import resources, when in fact only 'terraform import' (or manual configuration with plan refresh) accomplishes this, and candidates confuse validation or apply with the import workflow.

53
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

The backend block is missing required arguments (like bucket and region). Terraform will return an error during initialization and will not proceed.

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

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

56
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 manages the full lifecycle of infrastructure resources.

Why this answer

Terraform is designed as an infrastructure-as-code tool that can provision, update, and destroy resources across multiple cloud providers (e.g., AWS, Azure, GCP) and other services using a declarative configuration. This multi-provider capability is a core differentiator from single-cloud tools, enabling consistent workflows for hybrid and multi-cloud environments.

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.

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

58
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 enforces policies on configurations before apply.

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.

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

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

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

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

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

64
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 that servers are never modified after deployment; instead, new servers are created for any updates or changes. Option B correctly states this. Option A describes mutable infrastructure where configuration is changed via patches.

Option C is about resource sharing, not immutable infrastructure. Option D is about version control, which is a separate IaC practice.

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

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

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

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

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

In a declarative model, you describe the desired end state, and Terraform determines the steps to achieve that state, handling dependencies and changes automatically.

Page 1 of 6

Page 2

All pages