Courseiva

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

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

Page 2

Page 3 of 6

Page 4
151
Multi-Selectmedium

Which TWO of the following are required when configuring a Terraform backend for remote state storage?

Select 2 answers
A.Encryption at rest configuration
B.State locking support
C.A backend type (e.g., s3, azurerm, gcs)
D.Workspace configuration
E.Authentication credentials to access the backend
AnswersC, E

Specifying a backend type is absolutely fundamental because Terraform needs to know which remote storage service it should interact with to store and retrieve the state file. The `backend` block requires a named type, such as `s3`, `azurerm`, `gcs`, or `remote` (for Terraform Cloud/Enterprise), to correctly initialize the provider responsible for managing the state's persistence. Without this explicit declaration, Terraform cannot establish a connection to any remote location.

Why this answer

Every Terraform backend configuration must specify a backend type (e.g., s3, azurerm, gcs) to define where state is stored. Option E is correct because authentication credentials are required to access the remote backend; without valid credentials, Terraform cannot read or write state to the configured storage location.

Exam trap

A common misconception is that state locking is mandatory for all Terraform backends, but it is an optional feature. For example, the S3 backend requires explicit configuration of locking via DynamoDB; not all backends support locking by default.

152
MCQeasy

What is the purpose of the `terraform state list` command?

A.List all resources that would be created by the current plan
B.List all resources in the current state file
C.List all resources defined in the Terraform configuration
D.List all available workspaces
E.List all providers used in the configuration
AnswerB

This command directly queries the active Terraform state, which serves as the authoritative record of the infrastructure Terraform is managing. It meticulously enumerates every resource instance, module, and data source address stored within that state file, providing a precise inventory of the deployed components. This output is crucial for understanding the current managed infrastructure without needing to interact with the cloud provider APIs directly.

Why this answer

`terraform state list` lists all resources currently tracked in the Terraform state file, providing their resource addresses. Option B correctly describes this. Option A is incorrect because `terraform state list` does not show planned resources; that is the role of `terraform plan`.

Option C lists resources from configuration (not from state), D lists workspaces, and E lists providers.

Exam trap

The Terraform exam often tests the distinction between state-based commands and configuration-based commands, so the trap here is confusing `terraform state list` (which reads the state file) with `terraform show` or `terraform plan` (which read the configuration or generate a plan).

How to eliminate wrong answers

Option A is wrong because it is identical to the correct answer (B) and is listed as a duplicate; the question expects B as the correct choice. Option C is wrong because `terraform state list` lists resources from the state file, not from the Terraform configuration; resources defined in configuration but not yet applied will not appear. Option D is wrong because listing workspaces is done with `terraform workspace list`, not `terraform state list`.

Option E is wrong because listing providers is done with `terraform providers` or by inspecting the configuration, not with `terraform state list`.

153
MCQmedium

An organization uses Terraform with multiple workspaces to manage different environments (dev, staging, prod). They want to ensure that sensitive variables for prod are not exposed in the plan output. What should they do?

A.Mark the variable as `sensitive = true` in the variable definition
B.Use an output block to display the variable only when needed
C.Store the variable in the state file
D.Store the variable in an environment variable instead of a .tfvars file
E.Use a data source to retrieve the secret at runtime
AnswerA

Marking a variable as `sensitive = true` in its `variable` block definition instructs Terraform to redact its value from the console output during `terraform plan`, `terraform apply`, and `terraform output` commands. This prevents the secret from being accidentally exposed in logs or terminal displays. While the value is still stored in the state file, this flag significantly reduces the risk of inadvertent exposure during routine operations.

Why this answer

Marking a variable as `sensitive = true` in the variable definition prevents Terraform from displaying its value in CLI output, including plan and apply summaries. This is the direct and intended mechanism to protect sensitive data from exposure during Terraform operations, without affecting how the variable is stored or used.

Exam trap

A common misconception is that storing a variable in an environment variable or using a data source automatically hides it from plan output, when in fact only the `sensitive` attribute in the variable definition controls CLI display.

How to eliminate wrong answers

Option B is wrong because output blocks are used to display values after apply, not to suppress sensitive data from plan output; they would still expose the value if not marked sensitive. Option C is wrong because storing the variable in the state file does not prevent it from appearing in plan output; state files can also contain sensitive data in plaintext unless encrypted. Option D is wrong because environment variables are still evaluated and can be displayed in plan output unless the variable is explicitly marked as sensitive.

Option E is wrong because data sources retrieve secrets at runtime, but the resolved value can still appear in plan output if the variable referencing it is not marked sensitive.

154
Multi-Selecteasy

Which TWO options are valid ways to reference a Terraform module from a registry?

Select 2 answers
A.source = "hashicorp/consul/aws"
B.source = "consul/aws"
C.source = "hashicorp/consul/aws" version = "~> 0.1"
D.from = "hashicorp/consul/aws"
E.source = "hashicorp/consul/aws?ref=v1.0.0"
AnswersA, C

Correct; omitting the version defaults to the latest.

Why this answer

The Terraform registry module source syntax requires the format `namespace/name/provider`, and `hashicorp/consul/aws` follows this exactly. This tells Terraform to fetch the module from the public registry, using the `hashicorp` namespace, the `consul` module name, and the `aws` provider. The `version` constraint in option C is also valid, as it pins the module to a compatible version range using the `~>` operator, which is a standard Terraform version constraint syntax.

Exam trap

HashiCorp often tests the distinction between registry module syntax and Git-based module references, so the trap here is that candidates mistakenly apply Git-style `?ref=` syntax to registry modules, not realizing that registry modules require the `version` argument instead.

155
MCQeasy

A team wants to ensure that their infrastructure configuration repeatedly results in the same environment regardless of the initial state. Which IaC concept is most directly associated with this goal?

A.Version control
B.Idempotency
C.Orchestration
D.Provisioning
AnswerB

Idempotency is a fundamental principle in infrastructure as code (IaC) that ensures applying a configuration or operation multiple times produces the identical result as applying it once. This means if a resource already exists in the desired state, an idempotent operation will make no changes, preventing unintended modifications or errors during repeated deployments. It is essential for reliable automation and recovery.

Why this answer

Idempotency ensures that applying the same configuration multiple times always results in the same desired state, regardless of the starting state. In Terraform, this is achieved by the provider's ability to detect drift and reconcile the real-world infrastructure with the declared configuration in the .tf files. Without idempotency, repeated runs could create duplicate resources or fail to correct unintended changes.

Exam trap

HashiCorp often tests idempotency by contrasting it with version control, where candidates mistakenly think that simply tracking changes in Git ensures repeatable environments, ignoring that idempotency is about the execution behavior, not the history.

How to eliminate wrong answers

Option A is wrong because version control tracks changes to configuration files over time but does not guarantee that applying those files repeatedly yields the same environment; it only provides history and rollback. Option C is wrong because orchestration coordinates the order and execution of multiple automated tasks (e.g., provisioning, configuration) but does not inherently ensure that each individual operation is idempotent. Option D is wrong because provisioning is the act of creating resources (e.g., via Terraform apply) but does not by itself guarantee that subsequent runs will leave the environment unchanged if the initial state differs.

156
MCQhard

A company uses Terraform Cloud and wants to enforce policies that all EC2 instances must be of type t2.micro or t2.small. Which feature should they use?

A.Run tasks
B.Cost estimation
C.Sentinel policies
D.Terraform validate
AnswerC

Sentinel is the policy-as-code framework for enforcing rules.

Why this answer

Sentinel policies are HashiCorp's policy-as-code framework integrated with Terraform Cloud. They allow organizations to define fine-grained, logic-based rules that are enforced during the plan phase, such as restricting EC2 instance types to t2.micro or t2.small. This is the correct feature because it provides mandatory, automated policy enforcement across all workspaces, ensuring compliance before any infrastructure is provisioned.

Exam trap

A common mistake in Terraform exams is to confuse terraform validate (syntax checks) with Sentinel policy enforcement (business rules). Candidates may mistakenly choose terraform validate because they think validation includes policy checks, but Sentinel is the correct feature for enforcing rules like allowed instance types.

How to eliminate wrong answers

Option A is wrong because Run tasks are used to integrate external third-party tools (e.g., security scanners, static analysis) into the Terraform Cloud workflow, not to enforce native policy rules on resource attributes like instance type. Option B is wrong because Cost estimation provides a projected cost breakdown of the infrastructure plan but does not enforce any constraints or block non-compliant resources. Option D is wrong because terraform validate checks syntax and configuration validity locally, but it cannot enforce organizational policies like allowed instance types, and it is not a Terraform Cloud feature.

157
MCQhard

A company has a Terraform configuration that works correctly in us-east-1 but fails in us-west-2 due to resource availability. What is the best way to handle this?

A.Hardcode region in resources
B.Use count
C.Use data sources
D.Use provisioners
AnswerC

Data sources are a powerful Terraform feature that allows configurations to query and retrieve information from external systems, such as cloud provider APIs, during the plan phase. This enables dynamic fetching of region-specific attributes like available AMI IDs, instance types, or subnet configurations, which can then be used to configure resources adaptively. By leveraging data sources, the configuration can dynamically adjust to regional differences and ensure resource compatibility without hardcoding.

Why this answer

Data sources allow Terraform to query the target region for available resources at plan time, enabling dynamic configuration that adapts to regional differences. By using a data source to filter or validate resource availability, the configuration can fail gracefully or select an alternative resource without hardcoding region-specific values.

Exam trap

A common trap on the HashiCorp Terraform exam is thinking that `count` or `for_each` can directly handle regional resource differences. In reality, those meta-arguments require a data source to dynamically determine the available resources in each region, making the data source the correct approach.

How to eliminate wrong answers

Option A is wrong because hardcoding region-specific resources reduces portability and violates Terraform's infrastructure-as-code principles, requiring manual updates for each region. Option B is wrong because `count` controls the number of resource instances but cannot dynamically select a different resource type or handle unavailability across regions. Option D is wrong because provisioners are for executing scripts on local or remote machines after resource creation, not for resolving resource availability at plan time.

158
MCQeasy

A company uses Terraform with an S3 backend. A user accidentally deletes the state file. What is the best practice to recover the state?

A.Use terraform state pull from the local cache
B.Restore the state file from S3 bucket versioning
C.Use terraform import on all resources
D.Recreate the state from a terraform plan
E.Restore from the local terraform.tfstate.backup
AnswerB

S3 bucket versioning is a robust feature that automatically retains multiple versions of an object, including `terraform.tfstate`, whenever it is modified or deleted. By enabling versioning on the S3 bucket used for the Terraform backend, administrators can easily browse previous versions of the state file and restore a specific, known-good version. This provides a direct and reliable method for recovering from accidental state file corruption or deletion.

Why this answer

Using S3 versioning is the best practice because it allows you to restore the previous version of the state file. Other options, such as relying on local caches or re-importing resources, are not reliable or efficient.

159
MCQeasy

A junior engineer is asked to review a Terraform configuration that defines a module from the Terraform Registry. In which files are the descriptions of the module’s inputs and outputs typically found?

A.versions.tf
B.variables.tf
C.outputs.tf
D.main.tf
AnswerB, C

The `variables.tf` file is the standard and recommended location for defining all input variables that a Terraform module or configuration accepts. Each `variable` block within this file can include a `description` argument, which is essential for clearly documenting the purpose, expected data types, and valid values for each configurable input. These descriptions are crucial for users to understand how to interact with and customize the module.

Why this answer

In Terraform modules, input variables are declared in `variables.tf` with `description` arguments to document their purpose, and output values are declared in `outputs.tf` with `description` arguments. Therefore, descriptions of both inputs and outputs are found in these two files. Neither file alone describes both; the question's phrasing implies consideration of both files, making both B and C correct.

Exam trap

A common trap is to assume one file contains all documentation. While `variables.tf` documents inputs and `outputs.tf` documents outputs, questions asking for the file containing descriptions of both inputs and outputs imply both files are needed. Candidates may incorrectly choose only one.

How to eliminate wrong answers

Option A is wrong because `versions.tf` is used to specify required Terraform and provider version constraints, not to describe module inputs or outputs. Option C is wrong because `outputs.tf` defines output values and their descriptions, but it does not contain input variable definitions or descriptions. Option D is wrong because `main.tf` contains the core resource and module declarations, but it is not the standard location for documenting inputs and outputs; it may reference variables but does not define their descriptions.

160
MCQhard

A company uses AWS CloudFormation for AWS resources and Azure Resource Manager for Azure resources. They want to standardize on a single tool that can manage resources across both clouds with a consistent workflow and support for infrastructure as code. They also want to ensure that their infrastructure can be version-controlled and reviewed. Which approach best fulfills Terraform's purpose?

A.Use a custom Python script that calls both cloud APIs.
B.Continue using CloudFormation for AWS and Resource Manager for Azure.
C.Use Terraform with the AWS and Azure providers to manage all resources.
D.Migrate all resources to a single cloud provider to simplify management.
AnswerC

Terraform is purpose-built for multi-cloud and multi-provider infrastructure provisioning, making it the optimal solution for standardizing management across AWS and Azure. By leveraging its robust official AWS and Azure providers, engineers can define resources using a consistent HashiCorp Configuration Language (HCL) syntax within a single codebase. This approach centralizes state management, automates dependency resolution, and provides a unified, declarative workflow for all cloud resources, significantly reducing operational complexity.

Why this answer

Terraform is purpose-built for multi-cloud infrastructure as code with a unified declarative language. Using separate tools per cloud increases complexity. Terraform's provider model allows managing both AWS and Azure in the same configuration.

161
MCQmedium

Refer to the exhibit. An engineer runs terraform state list and sees these resources. The engineer wants to remove the aws_eip.web_ip resource from state without destroying the actual resource. Which command should be used?

A.terraform state rm aws_eip.web_ip
B.terraform destroy -target=aws_eip.web_ip
C.terraform refresh -target=aws_eip.web_ip
D.terraform import aws_eip.web_ip <id>
AnswerA

The `terraform state rm` command is specifically designed to remove one or more resources from the Terraform state file without interacting with the actual cloud infrastructure. This operation is crucial when a resource is no longer intended to be managed by Terraform but should persist in the cloud, or when the state file needs manual correction due to an out-of-band change. It ensures that subsequent `terraform plan` or `apply` operations will no longer consider this resource as part of the managed configuration.

Why this answer

To remove a resource from state without destroying it, use terraform state rm.

162
MCQmedium

A DevOps engineer is writing a Terraform configuration to provision an AWS EC2 instance. They want to ensure that the instance is replaced if the AMI ID changes, but not if the instance type changes. Which lifecycle meta-argument should be used?

A.Set `prevent_destroy = true`
B.Set `ignore_changes = all`
C.Set `create_before_destroy = true` and add `instance_type` to `ignore_changes`
D.Set `create_before_destroy = true` only
AnswerC

This solution effectively combines two distinct `lifecycle` rules to achieve the desired outcome. `create_before_destroy = true` ensures that when a change *does* necessitate a resource replacement (e.g., an AMI update), the new instance is fully provisioned and operational before the old one is terminated, minimizing service disruption. Concurrently, adding `instance_type` to `ignore_changes` specifically instructs Terraform to disregard modifications to this attribute, preventing it from triggering an unintended resource replacement solely due to an `instance_type` modification.

Why this answer

`create_before_destroy = true` ensures the new instance is created before the old one is destroyed, which is a best practice for zero-downtime deployments when the AMI changes. Adding `instance_type` to `ignore_changes` tells Terraform to ignore changes to the instance type attribute during plan/apply, so the instance is not replaced when only the instance type changes. This combination precisely meets the requirement: replacement on AMI change, no replacement on instance type change.

Exam trap

HashiCorp often tests the misconception that `create_before_destroy` alone controls replacement behavior, when in fact it only controls the order of operations and must be combined with `ignore_changes` to selectively prevent replacement on specific attributes.

How to eliminate wrong answers

Option A is wrong because `prevent_destroy = true` prevents any destruction of the resource, which would block the replacement when the AMI changes, contrary to the requirement. Option B is wrong because `ignore_changes = all` tells Terraform to ignore all attribute changes, meaning the instance would never be replaced even if the AMI changes, which violates the requirement. Option D is wrong because setting only `create_before_destroy = true` without `ignore_changes` would cause Terraform to replace the instance on any change, including instance type changes, which does not meet the requirement to avoid replacement on instance type changes.

163
Multi-Selectmedium

Which TWO of the following are true about Terraform workspaces?

Select 2 answers
A.Workspaces can be used to manage different provider configurations
B.All workspaces share the same state file
C.The default workspace can be deleted
D.The default workspace is named 'default'
E.Each workspace has its own state file
AnswersD, E

This statement is correct. When Terraform is initialized in a new directory using `terraform init`, it automatically creates a workspace named 'default'. This 'default' workspace is where all operations occur unless a different workspace is explicitly selected using `terraform workspace select <name>`. It serves as the initial and primary working environment for a Terraform configuration.

Why this answer

The default workspace is named 'default'. Option E is correct because each Terraform workspace maintains its own separate state file, allowing state isolation for different environments. Option A is incorrect because workspaces do not manage provider configurations; they only separate state.

Option B is false because each workspace has its own state file, not shared. Option C is false because the default workspace cannot be deleted.

Exam trap

HashiCorp often tests the misconception that workspaces can manage different provider configurations or that all workspaces share a single state file, when in fact workspaces only isolate state and have no effect on provider configuration.

164
MCQeasy

An operator wants to test an expression used in a Terraform configuration without running a plan or apply. Which command allows interactive evaluation of expressions?

A.terraform validate
B.terraform plan -out=test.tfplan
C.terraform console
D.terraform output
AnswerC

terraform console launches an interactive command-line environment where an operator can evaluate arbitrary Terraform expressions. This session has direct access to the current workspace's state, local variables, and output values, allowing for real-time testing of complex interpolations, conditional logic, and function calls. It is specifically designed for debugging and understanding how expressions resolve before applying changes to infrastructure.

Why this answer

The `terraform console` command opens an interactive Read-Eval-Print Loop (REPL) that allows operators to evaluate Terraform expressions, including interpolations and functions, using the current state and configuration without executing a plan or apply. This is the only command designed specifically for ad-hoc expression testing in a live context.

Exam trap

HashiCorp often tests the distinction between commands that validate syntax (`validate`) versus those that evaluate runtime expressions (`console`), trapping candidates who confuse static validation with dynamic expression testing.

How to eliminate wrong answers

Option A is wrong because `terraform validate` checks configuration syntax and internal consistency but does not evaluate arbitrary expressions or provide an interactive interface. Option B is wrong because `terraform plan -out=test.tfplan` generates a plan file and requires a full plan execution, not interactive expression evaluation. Option D is wrong because `terraform output` retrieves previously defined output values from state, not for testing arbitrary expressions interactively.

165
MCQmedium

Refer to the exhibit. A terraform plan shows that the instance will be replaced. What will be the order of operations?

A.The instance will be updated in-place without replacement.
B.Both instances will be created and destroyed simultaneously.
C.Create the new instance first, then destroy the old one.
D.Destroy the old instance first, then create the new one.
AnswerD

Correct. The default replacement order is destroy-before-create.

Why this answer

By default, when Terraform replaces a resource (e.g., due to a forced-new change like `ami` or `instance_type`), it destroys the old instance first and then creates the new one. This 'destroy-before-create' behavior is the default because it ensures Terraform can cleanly remove the old resource before provisioning the replacement. To achieve zero-downtime deployments, you must explicitly set `lifecycle { create_before_destroy = true }`.

Exam trap

A common misconception is that Terraform defaults to create-before-destroy for replacements. In reality, the default is destroy-before-create. Create-before-destroy must be explicitly configured via the `lifecycle` block.

How to eliminate wrong answers

Option A is wrong because the question explicitly states the instance will be replaced, not updated in-place; in-place updates occur only when the change is supported by the provider (e.g., modifying tags or security groups). Option B is wrong because Terraform does not create and destroy resources simultaneously; operations are sequential to avoid resource conflicts and ensure state consistency. Option D is wrong because destroy-before-create would cause downtime, which Terraform avoids by default for replacements; the default lifecycle behavior is create-before-destroy unless explicitly overridden with `create_before_destroy = false`.

166
MCQeasy

Which command displays the output values defined in the configuration after apply?

A.terraform state
B.terraform output
C.terraform plan
D.terraform show
AnswerB

The `terraform output` command is the dedicated utility for retrieving and displaying the values defined in `output` blocks within your Terraform configuration. After a successful `terraform apply`, these output values are computed and stored in the Terraform state file, making them accessible for inspection or use by other scripts and systems. This command can display all defined outputs or a specific named output, providing crucial information about the deployed infrastructure, such as IP addresses or connection strings.

Why this answer

The `terraform output` command is specifically designed to display the output values defined in the configuration after an apply. These outputs are declared in the `output` blocks of the root module and are stored in the state file; running `terraform output` retrieves and prints them in a human-readable format, optionally with `-json` for machine parsing.

Exam trap

A common trap is confusing `terraform output` (which shows only declared output values) with `terraform show` (which displays the entire state including all resource attributes). Candidates often choose `terraform show` when they only need to see the defined outputs.

How to eliminate wrong answers

Option A is wrong because `terraform state` is a subcommand used for advanced state management (e.g., listing resources, moving items, removing entries) and does not directly display output values. Option C is wrong because `terraform plan` shows the execution plan (what will change) before applying, not the output values from a completed apply. Option D is wrong because `terraform show` displays the current state or a saved plan file in a human-readable format, but it shows all resource attributes and metadata, not specifically the declared output values.

167
MCQmedium

A company uses Terraform with a backend configured to store state in Azure Blob Storage. They want to view the current state of resources without performing a plan or apply. Which command should be used?

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

The `terraform state list` command is the correct tool for this purpose as it is specifically designed to enumerate all resource addresses currently tracked within the Terraform state file. It queries the backend and returns a clean, line-by-line list of every managed resource, such as `aws_instance.web` or `null_resource.example`. This command provides a direct and efficient way to see all infrastructure components that Terraform is managing.

Why this answer

(terraform state list) is correct because it directly queries the Terraform state file stored in Azure Blob Storage and lists all resources tracked in that state without triggering a plan or apply. This command is part of the 'terraform state' family, designed specifically for inspecting state outside the core workflow, and it requires no infrastructure changes or API calls to cloud providers.

Exam trap

HashiCorp often tests the distinction between commands that inspect state directly (like terraform state list) versus those that trigger a refresh or plan (like terraform plan or terraform show with a state file), and candidates mistakenly choose terraform show thinking it lists resources, but it actually displays detailed attributes and requires a state file argument.

How to eliminate wrong answers

Option A (terraform output) is wrong because it only displays output values defined in the configuration, not the full list of resources in the state; it is useful for extracting specific values but does not enumerate all managed resources. Option B (terraform show) is wrong because it displays the state or plan file in a human-readable format, but it requires a state file or plan file as input and is not the primary command for simply listing resources; it is more suited for detailed inspection of a plan or state snapshot. Option D (terraform plan) is wrong because it performs a full refresh and comparison against the current infrastructure, which involves API calls to Azure and generates a plan for changes, going far beyond simply viewing the current state without side effects.

168
Multi-Selecteasy

Which TWO statements correctly describe Infrastructure as Code principles?

Select 2 answers
A.IaC enables version control of infrastructure configurations.
B.IaC requires manual approval for every infrastructure change.
C.IaC is only applicable to public cloud environments.
D.IaC eliminates the need for configuration management tools.
E.IaC promotes repeatable and consistent deployments.
AnswersA, E

IaC configurations are defined in code, which can be stored in version control systems like Git. This capability allows teams to track every change made to the infrastructure, review modifications before application, and easily revert to previous stable states if issues arise. Version control also facilitates collaborative development, ensuring a clear audit trail and improved operational transparency for infrastructure management.

Why this answer

A and E are correct. A is correct because IaC enables version control of infrastructure configurations using tools like Git, allowing tracking and rollback. E is correct because IaC automates provisioning and configuration, ensuring repeatable and consistent deployments.

B is incorrect because IaC often automates changes without requiring manual approval for every change, though approval workflows can be integrated. C is incorrect because IaC applies to on-premises, hybrid, and multi-cloud environments, not just public cloud. D is incorrect because IaC does not eliminate configuration management tools; they complement each other (e.g., Terraform for provisioning, Ansible for configuration).

169
MCQeasy

A company uses Terraform to deploy virtual machines. They want to ensure that the same exact operating system and software versions are used every time. Which practice supports this?

A.Manually installing software
B.Using a golden image and referencing it in the configuration
C.Using inline userdata scripts
D.Running configuration management after provisioning
AnswerB

A golden image, pre-configured with all necessary operating system patches, required software, and security hardening, ensures that every virtual machine provisioned from it is identical and compliant from the moment it launches. By referencing this image ID within the Terraform configuration, the deployment becomes highly repeatable, consistent, and significantly faster, as no post-provisioning installation steps are required. This method aligns perfectly with immutable infrastructure principles, drastically reducing configuration drift and simplifying management and troubleshooting.

Why this answer

Using a golden image—a pre-configured virtual machine template containing the exact operating system and software versions—ensures consistency across deployments. Terraform can reference this image via the `source_image` or `image_id` argument in a resource like `azurerm_virtual_machine` or `aws_instance`, guaranteeing that every provisioned VM starts from the same immutable baseline.

Exam trap

HashiCorp often tests the misconception that userdata scripts or configuration management tools can guarantee identical software versions, but the trap is that these methods depend on external sources (repositories, scripts) that can change over time, whereas a golden image captures a fixed, immutable state at build time.

How to eliminate wrong answers

Option A is wrong because manually installing software introduces human error and configuration drift, defeating the goal of repeatable, identical deployments. Option C is wrong because inline userdata scripts (e.g., cloud-init) run at first boot and can install software, but they are prone to failures from network issues, repository changes, or script updates, and do not guarantee the same exact versions every time. Option D is wrong because running configuration management (e.g., Ansible, Chef) after provisioning applies changes to a running system, which can still result in version inconsistencies if the base image or package repositories differ.

170
Multi-Selecthard

Which three characteristics are associated with immutable infrastructure as practiced by Terraform?

Select 3 answers
A.New versions are deployed by creating new instances
B.Configuration drift is accepted
C.Rollbacks are performed by redeploying a previous version
D.Resources are replaced rather than modified in place
E.In-place updates are preferred
AnswersA, C, D

In immutable infrastructure, deploying a new version involves provisioning entirely new instances from a fresh, updated image or configuration. These new instances replace the old ones, which are then decommissioned, ensuring that every deployment starts from a known, consistent state rather than modifying existing running systems.

Why this answer

Immutable infrastructure in Terraform involves deploying new versions by creating entirely new instances rather than modifying existing ones. This aligns with Terraform's resource lifecycle, where changes to certain attributes trigger destruction and recreation, ensuring a consistent and reproducible state.

Exam trap

The trap here is that candidates confuse immutable infrastructure with mutable patterns, mistakenly thinking that in-place updates or accepting drift are acceptable, when Terraform's immutable model strictly replaces resources to enforce consistency.

171
Drag & Dropmedium

Drag and drop the steps to initialize a Terraform working directory 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

Initialization begins after writing configs; terraform init downloads providers/modules, creates .terraform directory, and validate checks syntax.

172
Matchingmedium

Match each Terraform variable type to its example value.

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

Concepts
Matches

"hello"

42

true

["a", "b"]

{"key" = "value"}

Why these pairings

Terraform variable types: string uses quotes, number is numeric, bool is true/false, list is an array. Common mistakes include confusing numbers with strings and lists with bools.

173
MCQeasy

A team wants to manage infrastructure across multiple cloud providers using a single tool that supports infrastructure as code. Which tool is best suited for this purpose?

A.Ansible
B.Terraform
C.AWS CloudFormation
D.Chef
AnswerB

Terraform is an open-source infrastructure as code tool specifically engineered for provisioning and managing infrastructure across multiple cloud providers and on-premise solutions. It uses a declarative configuration language (HCL) to define desired infrastructure states, allowing teams to consistently create, update, and destroy resources like virtual machines, networks, and databases across AWS, Azure, GCP, and others. Its provider-based architecture enables seamless interaction with diverse APIs, making it ideal for multi-cloud strategies.

Why this answer

Terraform is the best choice because it is a cloud-agnostic Infrastructure as Code (IaC) tool that uses a declarative configuration language (HCL) to manage resources across multiple providers (e.g., AWS, Azure, GCP) through a single workflow. Unlike provider-specific tools, Terraform's provider plugin architecture allows it to abstract away API differences, enabling consistent state management and provisioning across heterogeneous environments.

Exam trap

The trap here is that candidates confuse configuration management tools (Ansible, Chef) with infrastructure provisioning tools, or assume that a cloud-specific tool like CloudFormation is sufficient for multi-cloud management, ignoring the requirement for a single, provider-agnostic tool.

How to eliminate wrong answers

Option A is wrong because Ansible is primarily a configuration management and automation tool that uses imperative playbooks (YAML) and relies on SSH/WinRM for execution; while it can provision infrastructure via modules, it lacks native multi-cloud state management and is not designed as a dedicated IaC provisioning tool. Option C is wrong because AWS CloudFormation is a proprietary IaC service that only manages resources within the AWS ecosystem, using JSON/YAML templates tied to the AWS API, and cannot manage resources from other cloud providers. Option D is wrong because Chef is a configuration management tool that uses a Ruby-based DSL (recipes/cookbooks) to enforce desired state on existing servers, not to provision infrastructure across multiple clouds, and it requires a Chef server for node management.

174
MCQhard

A module defines an input variable with 'sensitive = true'. The root module tries to use that variable in an output block. What happens when running 'terraform apply'?

A.The output value is hidden in the CLI output but still available in the state.
B.The apply fails with an error because sensitive variables cannot be used in outputs.
C.The output is displayed normally because outputs are always visible.
D.The output is removed from the plan entirely to protect the sensitive value.
AnswerA

When an output value is marked as sensitive = true, Terraform intentionally obfuscates its display in CLI operations like terraform plan, terraform apply, and terraform output. This prevents accidental exposure of secrets in terminal logs or shared screens. However, for Terraform to manage and track the infrastructure correctly, the actual sensitive value is still persisted unencrypted within the terraform.tfstate file, making it accessible to Terraform itself for subsequent operations.

Why this answer

When a variable is marked `sensitive = true`, Terraform prevents its value from being displayed in CLI output for any output that references it. However, the value is still stored in the state file and can be used within the module. Therefore, `terraform apply` succeeds, but the output value is hidden in the CLI output while remaining available in the state.

Exam trap

The Terraform exam often tests the misconception that sensitive variables cause errors or are completely removed from the plan, when in fact they are only hidden from CLI output but persist in the state.

How to eliminate wrong answers

Option B is wrong because Terraform does not prevent sensitive variables from being used in outputs; it only hides the value from CLI display. Option C is wrong because outputs that reference sensitive variables are not displayed normally; they are redacted in the CLI output. Option D is wrong because the output is not removed from the plan; it remains in the plan and state, but its value is masked in the CLI output.

175
MCQmedium

Refer to the exhibit. A developer runs `terraform apply` but receives an error that the state file is locked. Which of the following is a likely cause?

A.The DynamoDB table for locking is not configured
B.The S3 bucket does not exist
C.The IAM user lacks s3:ListBucket permission
D.The encryption key is incorrect
E.Another user has an active plan or apply running
AnswerE

Terraform's state locking mechanism, often implemented via a DynamoDB table when using an S3 backend, is designed to prevent concurrent operations from corrupting the shared state file. When one user or automated process initiates a `terraform plan` or `terraform apply` that modifies the state, a lock is acquired. If another user or process attempts to run a state-modifying command simultaneously, Terraform will detect the active lock and report a state lock error, preventing the second operation from proceeding until the lock is released.

Why this answer

A state lock error indicates that the state file is currently locked by another process. This commonly occurs when another user or an automated process is running a terraform plan or apply that holds the lock. Options such as a missing DynamoDB table, nonexistent S3 bucket, lack of s3:ListBucket permission, or incorrect encryption key would result in different error messages related to backend configuration or permissions, not a lock error.

176
MCQmedium

A team is using Terraform to manage a multi-tier application on AWS. The configuration includes resources for VPC, subnets, security groups, and EC2 instances. Recently, a developer manually created an additional security group in the AWS console for testing, and now the team wants to manage it via Terraform. They have updated the configuration to include this security group with the same name and rules. When they run `terraform plan`, it shows that the security group will be created, but the existing one is not detected. They want to bring the existing security group under Terraform management without recreating it. The team is using a remote backend with state locking. What should they do?

A.Run `terraform apply` and then modify the state to remove the duplicate.
B.Manually edit the Terraform state file to add the security group.
C.Run `terraform refresh` to update the state with the existing resource.
D.Use `terraform import` to import the existing security group into state.
AnswerD

proper method to adopt existing resources

Why this answer

Use `terraform import` to import the existing security group into state. `terraform import` is the proper way to bring existing resources under Terraform management. Option A is incorrect because running `terraform apply` would attempt to create a duplicate security group, resulting in an error or duplicate resource. Option B is incorrect because manually editing the Terraform state file is error-prone and not recommended.

Option C is incorrect because `terraform refresh` updates the state with the current state of resources already in the state file, but does not import new resources; it would not detect the manually created security group.

177
MCQhard

An operator runs terraform apply and receives the exhibit error. The instance was created but Terraform reports a failure. What is the most likely cause?

A.The state file is locked and cannot be updated
B.The AMI ID is incorrect and the instance failed to boot
C.The AWS API returned an error during instance creation
D.A provisioner block is configured to wait for SSH, but the instance is not reachable
AnswerD

Terraform provisioners, particularly the `remote-exec` provisioner, often require network connectivity (like SSH or WinRM) to the newly created instance to execute commands. If the instance is created successfully but is not reachable via the configured connection (e.g., due to security group rules, network ACLs, an incorrect key pair, or the instance not being fully booted), the provisioner will repeatedly attempt to connect until a timeout is reached. This scenario perfectly aligns with an instance being created but then failing during a post-creation step.

Why this answer

The error indicates that the instance was created successfully but Terraform reports a failure during the apply phase. This typically occurs when a provisioner block (e.g., file or remote-exec) is configured to wait for SSH connectivity, but the instance is not reachable within the timeout period. Terraform marks the resource as 'tainted' and reports a failure, even though the cloud resource itself was provisioned.

Exam trap

HashiCorp often tests the distinction between resource creation failures (which prevent the resource from existing) and provisioner failures (which occur after creation and leave the resource running but tainted), leading candidates to incorrectly select an API error or AMI issue when the instance clearly exists.

How to eliminate wrong answers

Option A is wrong because a locked state file would prevent Terraform from acquiring the lock and would return a 'state lock' error before any resource creation, not after the instance is created. Option B is wrong because an incorrect AMI ID would cause the instance creation to fail at the AWS API level, resulting in a 'launch failure' or 'invalid AMI' error, not a post-creation SSH timeout. Option C is wrong because if the AWS API returned an error during instance creation, the instance would not be created at all; the error would be returned during the create call, not after the instance exists.

178
MCQmedium

A company uses Terraform with multiple workspaces (dev, staging, prod) and a remote backend in an S3 bucket with a DynamoDB lock table. The backend configuration is defined in the main.tf with partial configuration. Developers are required to provide the backend configuration via command-line flags during 'terraform init'. One developer accidentally ran 'terraform init' without the required flags on a Monday morning. The init succeeded and created a local state file in the project directory. Over the next few days, other team members made changes to the workspace and pushed updates to the remote state. The developer who ran local init then runs 'terraform plan' and sees a plan that would recreate all resources. They realize their mistake. How can this situation be prevented in the future?

A.Enable state locking on the local backend to prevent conflicts.
B.Implement a CI/CD pipeline that runs 'terraform init' with the correct backend config and enforces that only pipeline-initiated runs are allowed.
C.Add a 'terraform plan -check' step that warns if state is not remote.
D.Use 'terraform workspace' commands to switch to the correct workspace before running init.
AnswerB

Implementing a CI/CD pipeline is the most robust solution for managing Terraform state across multiple workspaces and teams. The pipeline can be configured to explicitly run 'terraform init' with the correct remote backend configuration, ensuring all operations consistently use the designated shared state. Enforcing pipeline-initiated runs prevents individual developers from accidentally using local state or incorrect backend configurations, thereby centralizing state management, preventing divergence, and ensuring operational consistency.

Why this answer

Implementing a CI/CD pipeline that runs 'terraform init' with the correct backend configuration ensures that all developers use the same remote backend and prevents accidental local inits. This enforces consistency and avoids the scenario where a developer creates a local state file that diverges from the remote state. Option A is incorrect because state locking prevents concurrent modifications but does not prevent the use of a local backend.

Option C is incorrect because there is no 'terraform plan -check' flag; even if there were, it would not detect a local state at plan time if the state was already initialized locally. Option D is incorrect because 'terraform workspace' commands manage workspaces but do not enforce that the backend is remote; a local backend still works with workspaces.

179
Multi-Selecteasy

Which TWO statements accurately describe key purposes of Terraform?

Select 2 answers
A.Terraform enables declarative infrastructure provisioning.
B.Terraform provides built-in security scanning.
C.Terraform automates continuous delivery pipelines.
D.Terraform supports multi-cloud and multi-provider environments.
E.Terraform manages both mutable and immutable infrastructure.
AnswersA, D

Terraform's core design principle is declarative infrastructure provisioning. Users define the desired end state of their infrastructure using HashiCorp Configuration Language (HCL) or JSON, rather than specifying a sequence of steps to reach that state. Terraform then computes the necessary actions (create, update, delete) to transition the current infrastructure to the desired configuration, ensuring idempotence and consistency. This approach simplifies management and reduces human error.

Why this answer

Terraform allows users to define infrastructure using declarative configuration (HCL), specifying the desired end state rather than step-by-step procedures. Option D is correct because Terraform supports multiple cloud providers (AWS, Azure, GCP) and many other services through providers, enabling multi-cloud and multi-provider management. Option B is incorrect: Terraform does not have built-in security scanning; security scanning is typically handled by external tools or integrated via providers.

Option C is incorrect: While Terraform can be used within CI/CD pipelines, it does not automate the pipelines themselves; CI/CD tools like Jenkins or GitHub Actions handle pipeline automation. Option E is incorrect: Terraform primarily manages immutable infrastructure, but this is a characteristic of how it manages resources (by replacing rather than modifying), not a core purpose statement.

180
MCQeasy

A new developer joins a project that uses Terraform with a remote backend in GCS (Google Cloud Storage). They clone the repository and run `terraform init` successfully. However, when they run `terraform plan`, they get an error: "Error loading state: AccessDenied: 403 my-project-terraform-state@my-project.iam.gserviceaccount.com does not have storage.objects.get access to the Google Cloud Storage bucket." What is the most likely resolution?

A.Disable access control on the bucket temporarily
B.Run `terraform init -reconfigure` to regenerate the backend configuration
C.Grant the `Storage Object Viewer` role to the service account on the GCS bucket
D.Change the backend to local state and commit the state to the repository
AnswerC

Granting the `Storage Object Viewer` role to the service account directly addresses the issue of insufficient permissions for reading the Terraform state file stored in Google Cloud Storage. This specific IAM role provides the necessary `storage.objects.get` permission, allowing the service account to retrieve the state file's contents. Terraform requires read access to the state file to understand the current infrastructure's deployed configuration before planning any changes, ensuring consistency and preventing unintended modifications. This is a secure and precise way to resolve the access problem.

Why this answer

The error 'AccessDenied: 403 ... does not have storage.objects.get access' indicates that the service account used by Terraform lacks read permissions on the GCS bucket. Granting the 'Storage Object Viewer' role to that service account on the bucket provides the necessary `storage.objects.get` permission, allowing Terraform to read the state file. Option C is correct; options A, B, and D are not appropriate solutions.

181
MCQhard

You are a DevOps engineer at a company that manages infrastructure for multiple environments (dev, staging, prod) using Terraform. Each environment has its own state file stored in an S3 backend with DynamoDB locking. The team recently adopted a policy of running 'terraform plan' in CI/CD pipelines to review changes before applying. However, developers have reported that sometimes the plan output shows that Terraform wants to destroy and recreate resources that were not modified in their code changes. For example, a developer added a new tag to an S3 bucket in the staging environment, but the plan also showed that an unrelated EC2 instance would be replaced. Upon investigation, you notice that the state file for staging was last modified two days ago, but the developer's branch is based on a commit from one week ago. Which action is most likely to resolve the issue and ensure that plans only reflect changes from the current configuration changes?

A.Run 'terraform init -reconfigure' to ensure the local state is synchronized with the remote backend before planning.
B.Set the 'skip_metadata_api_check' option in the provider to avoid changes.
C.Use 'terraform plan -target=aws_s3_bucket.bucket' to limit the plan to only the S3 bucket.
D.Run 'terraform plan -refresh=true' to refresh the state before planning.
AnswerA

Running 'terraform init -reconfigure' forces Terraform to re-initialize its backend configuration, which includes re-downloading the latest authoritative state file from the configured remote backend. This action is essential when the local state cache is stale or missing, ensuring that subsequent 'terraform plan' operations accurately compare the desired configuration against the actual infrastructure reflected in the most current remote state. It effectively resolves discrepancies arising from out-of-band changes or state updates by other team members, providing a synchronized baseline.

Why this answer

`terraform init -reconfigure` forces Terraform to reinitialize the backend and re-download the latest state file from the remote S3 backend, discarding any stale local copy. The developer's local state was based on a week-old commit, while the actual remote state had been updated two days ago, causing Terraform to detect spurious differences (e.g., an unrelated EC2 instance) due to state drift. This command ensures the local state matches the remote state before planning, so the plan only reflects changes from the current configuration.

Exam trap

HashiCorp often tests the misconception that `terraform plan -refresh=true` (or the default refresh) is sufficient to synchronize state, when in fact it only updates the state against live infrastructure without re-downloading the remote state file, leaving stale local state intact.

How to eliminate wrong answers

Option B is wrong because `skip_metadata_api_check` is an AWS provider option that controls whether Terraform checks the EC2 metadata service for credentials; it has no effect on state synchronization or plan accuracy. Option C is wrong because `terraform plan -target=aws_s3_bucket.bucket` would limit the plan to only that resource, but it would not resolve the underlying state mismatch; the plan would still be based on stale state and could miss or misrepresent dependencies. Option D is wrong because `terraform plan -refresh=true` (the default behavior) refreshes the state against real infrastructure but does not re-download the remote state file; if the local state is outdated, refreshing will still use the stale local copy and may produce incorrect diffs.

182
Multi-Selectmedium

Which TWO actions will cause Terraform to update the state file?

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

terraform destroy is an imperative action that terminates and removes all resources currently managed by the Terraform configuration. Upon successful deletion of these resources from the cloud provider, Terraform meticulously updates the state file. This update marks those resources as removed, ensuring the state accurately reflects the infrastructure's current absence and preventing orphaned entries or inconsistencies with the real world.

Why this answer

`terraform apply` and `terraform destroy` both modify the state file. `plan`, `validate`, and `fmt` do not make changes to the state.

183
MCQhard

During a CI/CD pipeline run, terraform apply fails halfway through due to a network error. The state file is locked. The team wants to resume from the last successful apply. What should they do?

A.Re-run terraform apply after solving the network issue; Terraform will handle partial state.
B.Run terraform destroy and then reapply.
C.Force unlock the state and then reapply.
D.Manually delete the partially created resources in the cloud console and reapply.
AnswerA

When a `terraform apply` operation fails midway due to a transient issue like a network problem, Terraform's state file accurately records all resources that were successfully provisioned before the interruption. Because `terraform apply` is idempotent, re-running it after resolving the network issue will prompt Terraform to compare the desired configuration with the current state. It will then intelligently provision only the missing resources and update any that are out of sync, effectively resuming the deployment from where it left off without needing manual intervention or cleanup.

Why this answer

Terraform's state file tracks all managed resources and their current status. When `terraform apply` fails mid-run, the state is locked to prevent corruption, but Terraform records any resources that were successfully created before the failure. After resolving the network issue, re-running `terraform apply` will use the existing state to detect already-created resources and continue from where it left off, creating only the remaining resources.

This is the correct and intended workflow for handling partial state in Terraform.

Exam trap

The trap here is the misconception that a failed apply requires manual cleanup or state manipulation, when in fact Terraform's state-aware design allows safe resumption by simply re-running the apply command after fixing the transient issue.

How to eliminate wrong answers

Option B is wrong because `terraform destroy` would delete all resources managed by the configuration, including those successfully created before the failure, which is unnecessary and destructive when the goal is to resume from the last successful apply. Option C is wrong because force-unlocking the state without addressing the underlying network issue could lead to state corruption or duplicate resource creation, and the lock is a safety mechanism that should only be removed after verifying no other process is using the state. Option D is wrong because manually deleting partially created resources in the cloud console bypasses Terraform's state tracking, causing a mismatch between the state file and actual infrastructure, which will lead to errors on subsequent applies and potential resource drift.

184
MCQhard

After running 'terraform apply', the user sees that the 'aws_s3_bucket_object' is created successfully, but the bucket name is not as expected. What is the most likely reason?

A.The module variable 'bucket_name' is not consumed by the resource; the resource uses a hardcoded name.
B.The module output is incorrectly defined; it should use 'bucket' attribute instead of 'id'.
C.The module does not have an output for the bucket name, so the reference fails silently.
D.The output 'bucket_name' in the module is set to 'aws_s3_bucket.this.id', which is the bucket name, so the bucket name should be as expected.
AnswerD

The configuration appears correct; if the bucket name is not as expected, the issue might be elsewhere, but the output is correct.

Why this answer

The module output 'bucket_name' is defined as 'aws_s3_bucket.this.id', and in Terraform, the 'id' attribute of an 'aws_s3_bucket' resource is exactly the bucket name (not a generated ID). Since the user sees the object created successfully, the module is being called and the output is correctly referencing the bucket name, so the bucket name should be as expected. The question implies the user's expectation is wrong or the bucket name is actually correct, making D the only statement that aligns with Terraform's behavior.

Exam trap

HashiCorp often tests the misconception that 'id' is a random or internal identifier rather than the actual resource name, leading candidates to incorrectly think the output is wrong when it is actually correct.

How to eliminate wrong answers

Option A is wrong because if the resource used a hardcoded name, the bucket would still be created with that name, but the user would see a mismatch only if they expected a different name; the module variable not being consumed would cause a different bucket name, but the question states the bucket name is 'not as expected', not that it failed. Option B is wrong because the 'bucket' attribute of 'aws_s3_bucket' is the bucket name as well, but using 'id' is also correct and does not cause a mismatch; the output definition is not the issue here. Option C is wrong because if the module had no output for the bucket name, the reference would fail with an error during 'terraform apply', not silently succeed; Terraform requires explicit outputs to be defined for module references.

185
MCQmedium

A root module uses a module that creates an AWS EC2 instance. The module outputs the instance ID. The root module then uses this output in a null_resource provisioner. After modifying the module, terraform plan shows that the EC2 instance will be destroyed and recreated. What is the impact on the null_resource?

A.The null_resource prompts the user to confirm before any changes.
B.The null_resource will remain unchanged because it is not directly attached to the module.
C.The null_resource will fail to run because the output is temporarily unavailable during destroy.
D.The null_resource will be destroyed and recreated alongside the EC2 instance.
AnswerD

The `null_resource` is specifically designed to execute its `provisioners` whenever a value within its `triggers` map changes. Since the `null_resource` depends on an output from the module that creates the EC2 instance, any recreation or significant modification to that EC2 instance will alter the associated module output. This detected change in the output value will then cause the `null_resource` to be marked for destruction and subsequent recreation, ensuring its provisioners run again with the updated context of the new instance.

Why this answer

The null_resource's triggers typically depend on the module's output (the instance ID). When the EC2 instance is destroyed and recreated, its ID changes, which updates the trigger value. Terraform interprets this change as a need to destroy and recreate the null_resource along with its provisioner, ensuring the provisioner runs again with the new instance ID.

Exam trap

The trap here is that candidates assume null_resource is immutable or independent because it is a HashiCorp-specific resource with no real infrastructure, but Terraform treats any change in its triggers as a recreation signal, making it tightly coupled to upstream dependencies.

How to eliminate wrong answers

Option A is wrong because null_resource does not prompt for user confirmation; it follows standard Terraform planning and applies without interactive prompts. Option B is wrong because the null_resource is indirectly attached via the output dependency; Terraform tracks all resource dependencies through the graph, so a change in the module's output triggers recreation of dependent resources. Option C is wrong because the output is not temporarily unavailable during destroy; Terraform resolves the new output value after the instance is recreated, and the null_resource is recreated after that, so the provisioner runs with the new value.

186
MCQeasy

A Terraform user wants to visualize the execution order of resources before applying changes. Which command provides a dependency graph view?

A.terraform graph
B.terraform show
C.terraform plan
D.terraform output
AnswerA

The `terraform graph` command is specifically designed to generate a visual representation of the dependency graph for a Terraform configuration. It processes the configuration files and outputs a graph in the DOT format, which can then be rendered into an image using external tools like Graphviz. This visual output clearly illustrates the relationships and execution order between resources, modules, and providers, making it the ideal tool for visualizing the infrastructure's provisioning flow.

Why this answer

The `terraform graph` command generates a visual representation of the dependency graph for Terraform resources, showing the execution order based on implicit and explicit dependencies. This allows users to see which resources will be created, updated, or destroyed in sequence before applying changes. It outputs DOT format, which can be rendered with tools like Graphviz.

Exam trap

HashiCorp often tests the distinction between commands that show execution plans (`terraform plan`) versus those that visualize the underlying dependency graph (`terraform graph`), leading candidates to mistakenly choose `terraform plan` for graph visualization.

How to eliminate wrong answers

Option B is wrong because `terraform show` displays the current state or a saved plan file, not a dependency graph of execution order. Option C is wrong because `terraform plan` shows the execution plan as a textual diff of changes, not a visual dependency graph. Option D is wrong because `terraform output` retrieves output values from the state, not any graph or execution order visualization.

187
MCQhard

You are a DevOps engineer at a company that uses Terraform to manage infrastructure in AWS. The team recently adopted Terraform Cloud for remote state management and collaboration. They have a single workspace named 'production' that manages all production resources. Currently, the state file is stored in Terraform Cloud's default backend. The team wants to implement a disaster recovery strategy where they can restore the state file if Terraform Cloud experiences an outage. They also want to ensure that state file backups are taken automatically before every apply. Which approach should they recommend?

A.Manually download the state file from Terraform Cloud UI after each apply
B.Enable S3 replication on Terraform Cloud's internal state storage
C.Switch to an S3 backend with DynamoDB locking and configure Terraform Cloud to run remotely but store state locally
D.Use Terraform Cloud's API to download the state file before each apply and store it in a secure S3 bucket with versioning enabled
AnswerD

Utilizing Terraform Cloud's API to programmatically download the state file before each apply provides a robust, automated backup solution. Storing these downloaded state files in a separate, secure S3 bucket with versioning enabled creates an immutable audit trail and a reliable recovery point. This strategy ensures that a consistent backup exists prior to any potential infrastructure changes, offering a critical layer of disaster recovery and compliance.

Why this answer

It leverages the Terraform Cloud API to programmatically download the state file before each apply, storing it in a customer-managed S3 bucket with versioning enabled. This creates automatic, auditable backups independent of Terraform Cloud's availability, satisfying the disaster recovery requirement without changing the remote execution model. Options A and C are either manual or incompatible with Terraform Cloud's remote state management, and option B is not possible as Terraform Cloud does not expose its internal storage for replication.

Exam trap

The trap here is that candidates may assume Terraform Cloud's internal state storage is configurable or that switching to an S3 backend is compatible with Terraform Cloud's remote execution model, but Terraform Cloud requires its own backend for state management and does not expose underlying storage for replication.

How to eliminate wrong answers

Option A is wrong because manually downloading the state file from the Terraform Cloud UI after each apply is not automated, violates the requirement for backups before every apply, and introduces human error risk. Option B is wrong because Terraform Cloud's internal state storage is a managed service; customers cannot enable S3 replication on it, as they have no access to the underlying storage infrastructure. Option C is wrong because switching to an S3 backend with DynamoDB locking and configuring Terraform Cloud to run remotely but store state locally is contradictory—Terraform Cloud's remote execution requires state to be stored in its backend, and local state storage would break collaboration and remote operations.

188
MCQhard

You are a platform engineer at a large enterprise that uses Terraform Cloud with a VCS-backed workflow for all infrastructure. Your team manages a configuration that provisions AWS EC2 instances for a critical application. Recently, a junior team member accidentally committed a change that removed a required tag from the EC2 instance resource. The change passed the plan stage but was blocked by a Sentinel policy during the apply, preventing the infrastructure from being updated. The team needs to fix the configuration and apply the change. However, the repository is configured to automatically trigger runs on every push to the main branch. The team wants to avoid triggering an unwanted run while they work on the fix. What should the team do?

A.Temporarily disable the VCS connection in Terraform Cloud to prevent runs
B.Run terraform apply locally with the fixed configuration to bypass Terraform Cloud
C.Create a feature branch, fix the configuration, and merge via pull request
D.Amend the commit on main and force push to overwrite history
AnswerC

Standard practice; avoids triggering runs on main until merge.

Why this answer

Using a feature branch and pull request allows the team to fix the configuration without triggering a run on the main branch, since Terraform Cloud’s VCS integration only auto-triggers runs on pushes to the configured branch (typically main). Once the fix is merged via pull request, the change will be applied through the normal VCS-backed workflow, maintaining audit trails and policy enforcement. This approach avoids disrupting the VCS connection or bypassing Terraform Cloud’s governance.

Exam trap

The trap here is that candidates may think disabling the VCS connection or force pushing is acceptable, but HashiCorp tests the understanding that the VCS-backed workflow is the single source of truth and must not be bypassed or disrupted, even temporarily.

How to eliminate wrong answers

Option A is wrong because temporarily disabling the VCS connection in Terraform Cloud would prevent all runs, including legitimate ones, and requires manual reconnection, which is disruptive and error-prone. Option B is wrong because running terraform apply locally bypasses Terraform Cloud entirely, violating the enterprise requirement for VCS-backed workflow and Sentinel policy enforcement, and the local state would not match the remote state in Terraform Cloud. Option D is wrong because amending the commit on main and force pushing rewrites history, which is dangerous in a shared repository, may break other collaborators’ work, and still triggers a run on the main branch due to the push event.

189
Matchingmedium

Match each Terraform error code to its meaning.

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

Concepts
Matches

Success – no errors

Error – command failed

Error – CLI argument parsing error

Error – configuration errors

Error – state lock error

Why these pairings

Terraform exit codes indicate the result of command execution. Exit code 0 means success, 1 means general error, and 2 means usage error. The other codes are not defined by Terraform.

190
MCQhard

A company uses Terraform with multiple cloud providers and wants to integrate with their existing CI/CD pipeline. They need to enforce that all infrastructure changes go through code review and automated testing before being applied to production. Which approach best meets these requirements?

A.Store state in a remote backend and use terraform apply in the pipeline
B.Configure Terraform Cloud with run triggers and policy checks
C.Use the Terraform CLI in the CI/CD pipeline with remote state
D.Run terraform apply locally after manual approval
AnswerB

Terraform Cloud provides a robust platform for managing Terraform workflows, offering features like run triggers that automate infrastructure changes upon code commits. Its integrated policy checks, powered by Sentinel, enforce compliance and security standards by evaluating plans before application. This setup ensures mandatory code review and automated policy enforcement, creating a secure and auditable change management process.

Why this answer

Terraform Cloud's run triggers and policy checks (e.g., Sentinel) enforce that all infrastructure changes must pass code review and automated testing before being applied. This integrates directly with the CI/CD pipeline by requiring a pull request to trigger a plan, which is then reviewed and approved via Terraform Cloud's governance controls, ensuring no change reaches production without validation.

Exam trap

HashiCorp often tests the misconception that simply using a remote backend or running terraform apply in a pipeline is sufficient for governance, but the key requirement here is enforced code review and automated testing, which only Terraform Cloud's policy checks and run triggers provide natively.

How to eliminate wrong answers

Option A is wrong because storing state in a remote backend and using terraform apply in the pipeline does not inherently enforce code review or automated testing; it only centralizes state management, leaving the pipeline to apply changes without mandatory review gates. Option C is wrong because using the Terraform CLI in the CI/CD pipeline with remote state still lacks built-in policy enforcement or review workflows; it requires custom scripting to add approval steps, which is not a native feature. Option D is wrong because running terraform apply locally after manual approval bypasses the CI/CD pipeline entirely, violating the requirement to integrate with the existing pipeline and failing to enforce automated testing.

191
Multi-Selectmedium

Which TWO are benefits of Terraform's immutable infrastructure approach?

Select 2 answers
A.Easier rollbacks
B.Better performance
C.Faster provisioning
D.Lower cost
E.Reduced configuration drift
AnswersA, E

Immutable infrastructure significantly simplifies rollbacks because each deployment is based on a distinct, versioned artifact, such as a golden AMI or container image. If a new deployment introduces issues, reverting to a previous stable state involves merely deploying an older, validated version of the infrastructure artifact. This process replaces the entire problematic environment with a known-good one, eliminating complex in-place patching or state restoration.

Why this answer

Terraform's immutable infrastructure approach replaces entire resources rather than modifying them in-place. This means the previous version of the infrastructure is preserved as a state snapshot, allowing you to roll back by simply reapplying the prior configuration from your version control system. This eliminates the complexity of tracking incremental changes and ensures a clean, predictable rollback process.

Exam trap

Candidates often mistakenly assume that immutable infrastructure inherently improves performance or reduces costs, but in Terraform, the trade-offs include potentially slower provisioning due to full resource replacement and possible cost increases from maintaining multiple resource versions.

192
MCQeasy

Which command can be used to see the current state of a specific resource in the Terraform state?

A.`terraform state show <resource>`
B.`terraform output`
C.`terraform state list`
D.`terraform show`
AnswerA

This command is precisely designed to display the current attributes and values of a single, specific resource as recorded in the Terraform state file. By providing the resource's address (e.g., aws_instance.web), it retrieves and outputs all its managed properties, offering a detailed snapshot of that particular infrastructure component's state. This is invaluable for debugging, auditing, or verifying the configuration of an individual resource.

Why this answer

The `terraform state show <resource>` command is specifically designed to display the attributes and current state of a single resource as recorded in the Terraform state file. This allows you to inspect the exact values Terraform is tracking for that resource, which is essential for debugging drift or understanding the current infrastructure representation.

Exam trap

The Terraform exam often tests the distinction between listing resources (`terraform state list`) and viewing a specific resource's details (`terraform state show`), leading candidates to confuse the two commands when asked for a targeted state inspection.

How to eliminate wrong answers

Option B is wrong because `terraform output` only displays output values defined in the configuration, not the state of arbitrary resources. Option C is wrong because `terraform state list` merely lists all resource addresses in the state without showing their attributes or current state details. Option D is wrong because `terraform show` displays the entire state or plan file in a human-readable format, but it does not target a specific resource for detailed attribute inspection.

193
MCQeasy

A team is evaluating Terraform and Ansible for infrastructure provisioning. They note that Terraform describes the desired end state, while Ansible defines steps to reach that state. This difference is best described as:

A.Declarative vs imperative
B.Client-server vs agentless
C.Immutable vs mutable
D.Push vs pull
AnswerA

Terraform's configuration files are fundamentally declarative, meaning they specify the desired end state of infrastructure resources without detailing the exact procedural steps to achieve it. In contrast, Ansible typically employs an imperative approach, where playbooks define a precise sequence of commands and tasks that must be executed in a specific order to transition the infrastructure to a particular configuration. This distinction in how desired outcomes are expressed is a primary differentiator when evaluating these infrastructure as code tools.

Why this answer

The difference between declarative and imperative paradigms is key: Terraform is declarative (you specify the desired end state, and Terraform figures out how to achieve it), while Ansible is imperative (you specify each step to reach the state). Option B (client-server vs agentless) refers to architecture, option C (immutable vs mutable) refers to update strategies, and option D (push vs pull) refers to deployment methods. Therefore, option A is correct.

194
MCQmedium

A company uses Terraform to manage infrastructure in multiple AWS accounts. An engineer runs terraform plan and sees that a security group rule will be updated, but the change is not intended. The engineer wants to understand why Terraform is proposing the change without affecting other resources. Which approach should the engineer take to troubleshoot?

A.Run terraform state list to review the current state.
B.Run terraform show to display the current state.
C.Run terraform validate to check for configuration errors.
D.Run terraform plan -out=plan.tfplan and then terraform show plan.tfplan.
AnswerD

This two-step approach is the correct method for reviewing proposed infrastructure changes before applying them. `terraform plan -out=plan.tfplan` first generates a detailed execution plan by comparing the current configuration with the existing state and remote infrastructure, saving it to a specified file. Subsequently, `terraform show plan.tfplan` allows for a comprehensive, human-readable inspection of all proposed actions (creations, updates, deletions) contained within that saved plan file, without applying them.

Why this answer

`terraform plan -out=plan.tfplan` saves the plan to a binary file, and `terraform show plan.tfplan` then displays the full plan details, including the exact attribute-level diff and the reason for the change (e.g., a drift between the configuration and the state). This allows the engineer to inspect the proposed change without applying it, isolating the root cause without affecting other resources.

Exam trap

HashiCorp often tests the misconception that `terraform show` alone (without a plan file) reveals the reason for a proposed change, when in fact it only displays the current state or a previously saved plan, not the diff logic for a new plan.

How to eliminate wrong answers

Option A is wrong because `terraform state list` only outputs the resource addresses in the state file; it does not show the proposed changes or the diff that explains why a security group rule is being updated. Option B is wrong because `terraform show` without a plan file displays the current state or the saved plan from a previous `-out` file; by itself it does not reveal the reason for an unintended change in a new plan. Option C is wrong because `terraform validate` checks only syntax and configuration consistency (e.g., required arguments, valid references) and does not compare the configuration against the state or detect drift that would cause a plan to propose a change.

195
Multi-Selectmedium

Which three of the following best describe the core purpose and capabilities of Terraform? (Choose three.)

Select 3 answers
.It is an infrastructure as code tool that allows you to define and provision data center infrastructure using a declarative configuration language.
.It can manage both low-level components like compute instances and high-level components like DNS records across multiple cloud providers.
.It maintains a state file to map real-world resources to your configuration and to track metadata such as resource dependencies.
.It is primarily a configuration management tool for installing and configuring software on existing servers.
.It only supports public cloud providers (AWS, Azure, GCP) and cannot manage on-premises infrastructure.
.It requires a running daemon or agent on each target machine to execute resource changes.

Why this answer

Terraform is an infrastructure as code (IaC) tool that uses a declarative configuration language (HCL) to define and provision data center infrastructure. It manages both low-level components (e.g., compute instances, storage) and high-level components (e.g., DNS records, SaaS resources) across multiple cloud providers and on-premises systems via providers. Terraform maintains a state file to map real-world resources to your configuration, track metadata like dependencies, and enable incremental updates.

Exam trap

HashiCorp often tests the misconception that Terraform is a configuration management tool or requires agents, aiming to confuse candidates who conflate IaC provisioning with software configuration management tools like Chef or Puppet.

196
Drag & Dropmedium

Drag and drop the steps to create and apply a Terraform plan in the correct order.

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

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

Why this order

The correct sequence is: Terraform init (initialize the working directory and download providers/modules), Terraform plan (review the changes Terraform will make), and Terraform apply (execute the planned changes). This order ensures the environment is ready, changes are reviewed, and then safely applied.

197
MCQhard

A Terraform configuration uses a module from the Terraform Registry. After updating the module version in the configuration, the operator runs 'terraform plan' but does not see the changes expected from the new version. What is the most likely cause?

A.The operator did not run 'terraform get' to update modules.
B.The operator did not run 'terraform init' after changing the version.
C.The operator did not run 'terraform refresh' to update state.
D.The module version constraint is stored in the state file and must be updated.
AnswerB

When a module's version constraint is modified within the Terraform configuration, `terraform init` is the essential command to execute. This command re-evaluates all module requirements, downloads the newly specified module version into the `.terraform` directory, and updates the dependency lock file (`.terraform.lock.hcl`). Without running `init`, Terraform will continue to use the previously downloaded module version, leading to unexpected behavior or errors.

Why this answer

When you change a module version in the configuration, Terraform must re-initialize the working directory to download the new version and update the dependency lock file (.terraform.lock.hcl). Running 'terraform plan' without first running 'terraform init' will use the previously cached module version, so the expected changes from the new version will not appear. 'terraform init' is the required command to fetch and lock the updated module source.

Exam trap

HashiCorp often tests the misconception that 'terraform plan' automatically fetches new module versions, when in fact 'terraform init' is required to update the module cache and lock file before planning.

How to eliminate wrong answers

Option A is wrong because 'terraform get' is a legacy command that only downloads modules without updating the dependency lock file or re-initializing the backend; it is not the correct command for version changes. Option C is wrong because 'terraform refresh' updates the state file to match real-world infrastructure but does not affect module source code or version resolution. Option D is wrong because module version constraints are defined in the configuration, not stored in the state file; the state file records resource attributes, not module source metadata.

198
MCQhard

A team uses Terraform to manage infrastructure in AWS. They have a single workspace and store state in an S3 bucket with DynamoDB locking. After a recent apply, the state file became corrupted due to a network interruption during the state write. The team needs to recover the state and prevent future corruption. They have not enabled any backup or versioning. What should they do?

A.Enable S3 bucket versioning and DynamoDB point-in-time recovery, then use terraform state pull to retrieve a previous state version.
B.Use terraform force-unlock to release the lock and reapply the configuration.
C.Manually edit the state file in S3 to fix the corruption.
D.Delete the state file and run terraform import for all resources.
AnswerD

When a Terraform state file is irrecoverably corrupted, deleting it and then systematically importing all existing resources is often the only reliable, albeit labor-intensive, method to regain control. This process rebuilds a new, accurate state file by querying the actual infrastructure and associating it with the configuration. While it is time-consuming, requires meticulous attention to detail for every resource, and loses historical state references, it ensures Terraform's state correctly reflects the real-world resources.

Why this answer

Since versioning was not enabled before the corruption, no previous state versions exist in S3. Enabling it now (Option A) does not recover the corrupted state. `terraform state pull` retrieves the *current* state, not a previous version, making Option A ineffective. Manually editing the S3 state (C) is risky and discouraged. `force-unlock` (B) only releases the lock without fixing corruption.

Deleting the corrupted state and running `terraform import` for all resources (D) is the only reliable way to recover when no backup is available, though it requires knowing all resource IDs. After recovery, enable S3 versioning and DynamoDB point-in-time recovery to prevent future incidents.

199
MCQhard

Your team is developing a custom module for creating EC2 instances with attached EBS volumes. The module variables are: instance_type (default "t2.micro"), ami (required), volume_size (default 8), volume_type (default "gp2"). Another team uses this module to create a web server. In their root module, they call the module without any explicit instance_type override, but they do set other variables. After applying, the web server is created with instance_type "t2.nano" instead of the expected "t2.micro". They confirm that the module still has the default "t2.micro". What is the most likely explanation?

A.The module's instance_type variable uses a default that is "t2.nano" but the root module overrode it with a variable from its own context.
B.The instance_type variable is not defined in the module's variables.tf, so it uses a default from the AWS provider.
C.The root module has a variable called instance_type set to "t2.nano" that is being passed to the module.
D.The module's variable default was changed to "t2.nano" in a new version.
AnswerC

If the root module defines or inherits an instance_type variable with value "t2.nano", and the module block passes it (e.g., instance_type = var.instance_type), that overrides the module's default.

Why this answer

In Terraform, when a module is called, any variable with the same name in the root module that is explicitly passed to the module block (e.g., instance_type = var.instance_type) will override the module's default value, even if the module itself has a default. The root module likely declared a variable instance_type with a default of 't2.nano' and is passing it to the module call. Option A is incorrect because the module's default is 't2.micro', not 't2.nano'.

Option B is incorrect because if the variable is not defined in the module's variables.tf, passing it would cause an error; it cannot fall back to an AWS provider default. Option D is incorrect because the scenario explicitly states the module default remains 't2.micro'.

200
MCQmedium

An operator modifies a Terraform configuration to change the `ami` attribute of an `aws_instance` resource. When they run `terraform plan`, they see that the resource will be destroyed and recreated. They want to avoid the recreation and instead update the instance in-place. What is the best approach?

A.Add `create_before_destroy` lifecycle rule
B.Accept the recreation; it is required for this attribute
C.Use `ignore_changes` in lifecycle to ignore AMI changes
D.Add `prevent_destroy` lifecycle rule
AnswerB

Changing the Amazon Machine Image (AMI) ID for an existing AWS EC2 instance resource typically necessitates its recreation. The AMI is a fundamental, immutable property of an EC2 instance that cannot be modified in-place after the instance has been launched. Therefore, to apply an updated AMI, Terraform must destroy the old instance and provision a completely new one with the specified new AMI.

Why this answer

Changing the `ami` attribute of an `aws_instance` resource is a force-new attribute in the AWS provider. Terraform cannot update the AMI of a running EC2 instance in-place; it must destroy the existing instance and create a new one with the new AMI. This is a fundamental constraint of the AWS API, not a Terraform limitation.

Exam trap

The exam tests the misconception that lifecycle rules like `create_before_destroy` or `ignore_changes` can circumvent provider-level force-new attributes, when in fact they only affect Terraform's behavior, not the underlying API constraints.

How to eliminate wrong answers

Option A is wrong because `create_before_destroy` only changes the order of operations (creating the new resource before destroying the old one) but does not prevent the destruction itself; the resource will still be recreated. Option C is wrong because `ignore_changes` would cause Terraform to ignore any changes to the AMI attribute, meaning the instance would not be updated at all, which defeats the purpose of modifying the configuration. Option D is wrong because `prevent_destroy` would block any operation that destroys the resource, causing the plan to fail with an error; it does not enable in-place updates.

201
MCQeasy

Which command initializes a Terraform working directory by downloading providers and modules?

A.terraform plan
B.terraform apply
C.terraform get
D.terraform init
AnswerD

The "terraform init" command is the fundamental operation for preparing a Terraform working directory for use. It performs several essential setup steps, including discovering and downloading all necessary provider plugins, retrieving remote modules, and configuring the backend for state management. This comprehensive initialization ensures that Terraform has all the required components to parse configurations, create execution plans, and apply infrastructure changes effectively.

Why this answer

`terraform init` is the command that initializes a Terraform working directory by downloading and installing the required providers and modules specified in the configuration files. It also sets up the backend for state storage and locks, ensuring the environment is ready for subsequent operations like planning and applying.

Exam trap

Candidates often confuse `terraform init` with `terraform get`, mistakenly thinking `terraform get` handles both providers and modules. In reality, `terraform get` only manages modules while `terraform init` handles providers, modules, and backend initialization.

How to eliminate wrong answers

Option A is wrong because `terraform plan` creates an execution plan by comparing the current state with the desired configuration, but it does not download providers or modules. Option B is wrong because `terraform apply` executes the changes proposed by the plan, applying infrastructure modifications, but it does not perform initialization tasks. Option C is wrong because `terraform get` only downloads and updates modules referenced in the configuration, but it does not download providers or initialize the backend.

202
Multi-Selecteasy

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

Select 2 answers
A.terraform fmt
B.terraform init
C.terraform console
D.terraform apply
E.terraform get
AnswersB, D

The `terraform init` command is a foundational and essential first step in the core Terraform workflow, preparing the working directory for subsequent operations. It downloads and installs necessary provider plugins, initializes the backend for state storage, and retrieves any required modules. This command establishes the environment crucial for Terraform to understand and interact with the desired infrastructure, making it indispensable before planning or applying changes.

Why this answer

`terraform init`, is correct because it initializes a working directory containing Terraform configuration files, downloading and installing the required providers and modules. This is the first command in the core Terraform workflow, which follows the sequence: init, plan, apply. Without `init`, subsequent commands like `plan` or `apply` will fail due to missing provider plugins and backend configuration.

Exam trap

HashiCorp often tests the distinction between commands that are part of the core provisioning workflow (init, plan, apply) versus auxiliary commands like `fmt`, `console`, or `get`, which are used for formatting, debugging, or module management but not for the fundamental plan-apply cycle.

203
MCQmedium

During a deployment, a user runs `terraform apply` but the command fails because the state lock cannot be acquired. They suspect the lock was released after the previous `apply` but is still held. What command can they use to force unlock the state?

A.`terraform init -force-copy`
B.`terraform force-unlock <lock_id>`
C.`terraform state unlock`
D.`terraform break-lock`
AnswerB

This command is the correct and designated mechanism for manually releasing a stuck or orphaned Terraform state lock. When a Terraform operation is interrupted, the state lock might persist, preventing subsequent operations. By providing the unique `<lock_id>`, this command allows an administrator to force the release of the specific lock, enabling further infrastructure changes to proceed safely. This is an essential recovery tool for maintaining operational continuity.

Why this answer

When Terraform cannot acquire a state lock because it was not properly released (e.g., after a crash or interrupted apply), the `force-unlock` command is the only built-in way to manually break the lock. You must provide the lock ID (obtained from the error message or backend) to override the lock, which is stored in the backend (e.g., DynamoDB, Consul) and prevents concurrent modifications. This command is designed for recovery scenarios where the lock holder is known to be dead.

Exam trap

The Terraform exam often tests the exact command syntax, so candidates may confuse `terraform force-unlock` with non-existent commands like `terraform state unlock` or `terraform break-lock`, or misuse `terraform init -force-copy` which serves a completely different purpose.

How to eliminate wrong answers

Option A is wrong because `terraform init -force-copy` is used to force copying the state from a remote backend to a local backend, not to release a state lock. Option C is wrong because `terraform state unlock` is not a valid Terraform command; the correct command is `terraform force-unlock`. Option D is wrong because `terraform break-lock` is not a real Terraform command; it is a fabricated option that does not exist in the Terraform CLI.

204
MCQeasy

A user wants to remove a specific resource from Terraform state without destroying the actual infrastructure. Which command should they use?

A.terraform state rm resource
B.terraform taint resource
C.terraform state mv resource
D.terraform destroy -target=resource
AnswerA

The `terraform state rm <address>` command is precisely designed to remove one or more resource instances from the Terraform state file. This operation updates the state to reflect that Terraform no longer manages the specified resource, but critically, it does not interact with the cloud provider or affect the actual infrastructure resource itself. The resource will continue to exist in the cloud, unmanaged by Terraform, making this the correct choice for decoupling a resource from state without destruction.

Why this answer

The `terraform state rm` command is the correct choice because it removes a specified resource from the Terraform state file without making any API calls to the actual infrastructure provider. This allows the resource to be detached from Terraform management while leaving the real-world resource running, which is exactly what the user wants.

Exam trap

HashiCorp often tests the distinction between state manipulation commands that affect only the state file versus commands that trigger actual infrastructure changes, so candidates may confuse `terraform state rm` with `terraform destroy` or `terraform taint`.

How to eliminate wrong answers

Option B is wrong because `terraform taint` marks a resource for recreation on the next apply, but it does not remove the resource from state or leave the infrastructure intact. Option C is wrong because `terraform state mv` moves a resource to a different address within the state file, but it does not remove it from state or detach it from management. Option D is wrong because `terraform destroy -target=resource` will actually delete the specified infrastructure resource, which is the opposite of what the user wants.

205
MCQeasy

A module 'web_app' defines an input variable 'instance_count' with type = number and a validation block ensuring it is between 1 and 10. What happens if a user sets instance_count = 0?

A.Terraform returns an error during validation and stops execution.
B.Terraform applies the module with zero instances, as a value of 0 is allowed.
C.Terraform ignores the validation if the variable is explicitly set.
D.Terraform uses the default value for instance_count from the module.
AnswerA

When a variable's custom validation condition fails, Terraform immediately halts execution and returns an error. This occurs during the planning phase (e.g., `terraform plan` or `terraform apply`), before any infrastructure changes are proposed or applied. The explicit error message defined in the validation block provides clear feedback, preventing the deployment of invalid configurations.

Why this answer

HashiCorp Terraform validates input variables against their declared type and any validation blocks before applying configuration. When `instance_count = 0` is set, the validation block's condition `var.instance_count >= 1 && var.instance_count <= 10` evaluates to `false`, causing HashiCorp Terraform to halt with an error during the `terraform plan` or `terraform validate` phase, preventing any further execution.

Exam trap

The trap here is that candidates may assume HashiCorp Terraform silently falls back to a default value or ignores validation when a variable is explicitly set, but in reality, explicit assignment overrides defaults and validation is always enforced, causing an immediate error for out-of-range values.

How to eliminate wrong answers

Option B is wrong because a value of 0 fails the validation condition, so Terraform does not allow the apply to proceed; it returns an error instead. Option C is wrong because validation blocks are always enforced regardless of how the variable is set—explicitly, via default, or through a `.tfvars` file—there is no mechanism to bypass them. Option D is wrong because a default value is only used when the variable is not assigned at all; when the user explicitly sets `instance_count = 0`, that value is used and must pass validation, which it does not.

206
Multi-Selectmedium

Which TWO of the following are valid methods to share data between Terraform configurations?

Select 2 answers
A.Use output variables across configurations
B.Use modules to share state
C.Use depends_on to pass values
D.Store shared data in a common backend and read it via data sources
E.Use terraform_remote_state data source
AnswersD, E

Storing shared data in a common backend, such as an S3 bucket or Consul Key-Value store, allows different Terraform configurations to access specific values. Data sources like `aws_s3_bucket_object` or `consul_kv` can then be used to retrieve these arbitrary pieces of information, providing a flexible method for cross-configuration data exchange beyond just Terraform state outputs.

Why this answer

Storing shared data in a common backend (e.g., an S3 bucket with DynamoDB locking) and reading it via data sources (like the `terraform_remote_state` data source) allows different Terraform configurations to consume outputs from one another without duplicating state or breaking isolation. This pattern is the recommended way to share data across configurations because it leverages the backend's locking and consistency guarantees.

Exam trap

HashiCorp often tests the misconception that output variables alone can be used across configurations, but they require an explicit data source like `terraform_remote_state` to be consumed externally.

207
MCQhard

You are a DevOps engineer managing a multi-environment Terraform setup using workspaces. Your team has three workspaces: dev, staging, and prod. All infrastructure is defined in a single root module with environment-specific variable values stored in separate .tfvars files. Recently, a colleague accidentally ran terraform destroy in the prod workspace, which deleted critical production resources. You need to implement a safety mechanism to prevent accidental destruction of production resources in the future. The solution should not require changes to the Terraform provider or backend configuration. Which approach should you take?

A.Create a wrapper script that checks the workspace before running terraform destroy and requires a manual confirmation for prod.
B.Use Terraform Sentinel policies with a mandatory policy that denies destroy on the prod workspace.
C.Configure a remote backend with state locking and force unlock only for non-prod workspaces.
D.Add a lifecycle precondition block in a null_resource that checks if the current workspace is 'prod' and fails if terraform destroy is attempted.
AnswerD

A `lifecycle` precondition block allows for custom validation checks that are evaluated during the plan and apply phases, including `terraform destroy`. By placing a precondition within a `null_resource` that checks `terraform.workspace == "prod"` and setting an `error_message` if true, Terraform will explicitly fail the `destroy` operation before any resources are touched. This provides a declarative, Terraform-native safety mechanism directly within the configuration.

Why this answer

A `lifecycle` precondition block in a `null_resource` can evaluate the current workspace at plan time using `terraform.workspace`. When `terraform destroy` is run, the precondition fails if the workspace is `prod`, preventing the destroy operation without altering the provider or backend configuration. This approach is native to Terraform, requires no external tools, and directly enforces the safety check within the configuration itself.

Exam trap

HashiCorp often tests the distinction between native Terraform features (like `lifecycle` preconditions) and external tools (like wrapper scripts or Sentinel) that require additional infrastructure or configuration changes, leading candidates to choose a non-native solution that is not self-contained within the root module.

How to eliminate wrong answers

Option A is wrong because a wrapper script is an external, non-enforceable mechanism that can be bypassed by running `terraform destroy` directly, and it does not integrate with Terraform's execution lifecycle. Option B is wrong because Sentinel policies require a Terraform Cloud/Enterprise backend with policy enforcement, which is not part of the standard open-source Terraform setup and would change the backend configuration. Option C is wrong because state locking prevents concurrent operations, not destructive actions; `force unlock` is unrelated to workspace-specific safety, and locking does not block `terraform destroy` on any workspace.

208
MCQmedium

The user runs `terraform init` successfully, but then `terraform plan` still fails with a different error: "Error: No configuration files found in this directory." The directory contains backend.tf and main.tf. What is the most likely cause?

A.The backend block is misconfigured.
B.The user is not in the same directory as the .tf files.
C.The workspace name in the backend configuration is incorrect.
D.The main.tf file contains invalid syntax.
AnswerB

Terraform commands, including plan and apply, by default search for .tf configuration files exclusively within the current working directory. If the user executes these commands from a different directory where the .tf files are not present, Terraform will report that no configuration files were found, even if terraform init previously succeeded in the correct location.

Why this answer

The error 'No configuration files found in this directory' indicates that Terraform cannot locate any .tf files in the current working directory. Even though the directory contains backend.tf and main.tf, the user must be in that directory when running `terraform plan`. This is a common path issue, not a configuration or syntax problem.

Exam trap

HashiCorp often tests the distinction between configuration errors (like syntax or backend issues) and operational errors (like working directory), leading candidates to overthink complex backend or syntax problems when the real issue is a simple path mismatch.

How to eliminate wrong answers

Option A is wrong because a misconfigured backend block would cause an error during `terraform init` or `terraform plan` related to state initialization, not a 'no configuration files' error. Option C is wrong because an incorrect workspace name would cause an error about workspace state or backend configuration, not a missing configuration files error. Option D is wrong because invalid syntax in main.tf would produce a syntax error during parsing, not a 'no configuration files' error.

209
Multi-Selectmedium

Which of the following are core concepts or behaviors of Terraform's execution model and state management? (Choose four.)

Select 4 answers
.Terraform uses a desired state model, where configuration defines the target state and Terraform determines the actions needed to reach it.
.The Terraform state file maps real-world resources to your configuration, and keeps track of metadata such as resource dependencies and attributes.
.Terraform plan produces an execution plan showing what actions will be taken to achieve the desired state, without making any changes.
.Terraform apply executes the changes proposed by the plan, and can be run with or without a prior plan being saved.
.Terraform refresh automatically updates the state file to match real-world infrastructure by modifying resources if differences are found.
.Terraform destroy removes all resources defined in the configuration from the state file only, without affecting the actual infrastructure.

Why this answer

Terraform's execution model is fundamentally a desired state model: the configuration declares the target state, and Terraform computes the actions needed to reach it. The state file is the critical mapping between configuration and real-world resources, tracking metadata like dependencies and attributes. The plan phase produces a dry-run execution plan without making changes, while apply executes those changes and can be run directly without a saved plan file.

These four behaviors—desired state, state file mapping, plan as dry-run, and apply as execution—are core to how Terraform operates.

Exam trap

HashiCorp often tests the misconception that refresh modifies infrastructure or that destroy only affects state, when in reality refresh is a read-only operation and destroy removes actual resources.

210
MCQeasy

A team wants to ensure that all Terraform runs are recorded for audit purposes. Which practice should they implement?

A.Run 'terraform show' after every apply to capture state.
B.Add the state file to version control after each run.
C.Enable state locking in the backend configuration.
D.Configure a remote backend that supports state versioning.
AnswerD

Configuring a remote backend that supports state versioning is the recommended and most effective solution. Services like Amazon S3 with versioning or Azure Storage blobs automatically store a new, immutable version of the state file every time 'terraform apply' is executed. This creates a comprehensive, auditable history of all infrastructure changes, enabling easy rollback to previous states and ensuring all Terraform runs are reliably recorded for compliance and operational visibility.

Why this answer

Configuring a remote backend that supports state versioning (e.g., Terraform Cloud, S3 with versioning enabled) automatically records every state change, providing a complete audit trail of all Terraform runs. This ensures that previous state snapshots are preserved and can be reviewed or restored if needed, meeting audit requirements without manual intervention.

Exam trap

HashiCorp often tests the distinction between state locking (a concurrency safety feature) and state versioning (an audit/history feature), causing candidates to mistakenly choose state locking as the solution for audit trails.

How to eliminate wrong answers

Option A is wrong because 'terraform show' only displays the current state file contents; it does not record or preserve historical state changes for audit purposes. Option B is wrong because adding the state file to version control after each run is error-prone, can expose sensitive data, and violates Terraform's best practice of never committing state files to VCS. Option C is wrong because state locking prevents concurrent modifications and corruption but does not create a historical record of state changes; it is a concurrency control mechanism, not an audit trail.

211
MCQhard

Refer to the exhibit. An engineer runs 'terraform apply' and receives the lock error. After forcing an unlock, what is the most important next step?

A.Check if the previous apply process is still running, and if not, proceed with the new apply.
B.Delete the state file and re-import resources.
C.Run 'terraform apply' again immediately.
D.Modify the backend configuration to disable locking.
AnswerA

When Terraform encounters a state lock, it indicates that another operation is either still active or terminated unexpectedly, leaving the lock in place. The correct procedure is to first confirm that no legitimate Terraform process is currently modifying the state. If the previous operation has indeed completed or failed, and the lock persists, the `terraform force-unlock` command can then be used to safely release the stale lock, allowing a new `terraform apply` to proceed without risking state corruption. This ensures state integrity.

Why this answer

Force-unlocking should be used with caution. The engineer must verify that the previous operation (the one holding the lock) is no longer running or has completed, otherwise unlocking could cause state corruption. The most important next step is to ensure the previous process is not active.

212
Multi-Selecteasy

Which two of the following are correct statements about Terraform providers?

Select 2 answers
A.A provider must be defined in every Terraform configuration.
B.Providers are plugins that Terraform uses to manage resources.
C.Providers can be sourced from the Terraform Registry.
D.Only one provider can be used per configuration.
E.Providers are automatically installed by terraform plan.
AnswersB, C

This statement is correct. Providers function as specialized plugins that extend Terraform's core capabilities, enabling it to interact with various cloud platforms, SaaS offerings, and on-premise infrastructure. Each provider implements a set of resource types and data sources, defining the API calls and logic necessary to create, read, update, and delete those specific infrastructure components.

Why this answer

Terraform providers are plugins that enable Terraform to manage resources for a specific cloud or service (e.g., AWS, Azure). They can be sourced from the Terraform Registry or other locations. The correct statements are B and C.

A is incorrect because a provider is not required in every configuration; some configurations may use only data sources or child modules that already have providers defined. D is incorrect because multiple providers can be used in a single configuration to manage resources across different platforms. E is incorrect because providers are installed by `terraform init`, not `terraform plan`.

213
MCQeasy

Refer to the exhibit. What does this output show?

A.Resources to be created
B.Resources in the configuration
C.Resources that are out of sync
D.Resources managed by Terraform
AnswerD

The `terraform state list` command directly queries and displays the contents of the Terraform state file, which is the authoritative record of all infrastructure resources that Terraform is currently managing. This output precisely enumerates every resource instance that has been successfully provisioned, imported, and whose metadata is stored within the state, unequivocally confirming their status as being under Terraform's active management. It serves as a definitive inventory of the infrastructure Terraform controls.

Why this answer

The output shows a list of resources that Terraform is currently tracking in its state file. This indicates which resources are under Terraform's management, not just those defined in the configuration or those that are out of sync. Option D is correct because the `terraform state list` command (or similar output) displays all resources that Terraform is actively managing, regardless of their current state relative to the configuration.

Exam trap

A common pitfall in Terraform exams is confusing resources defined in the configuration with resources actually managed in the state, leading candidates to select 'Resources in the configuration' (Option B) instead of 'Resources managed by Terraform'.

How to eliminate wrong answers

Option A is wrong because the output does not show resources to be created; it shows resources already tracked in the state, which may already exist. Option B is wrong because the output is not limited to resources defined in the configuration; it includes all resources in the state, which can differ from the configuration if resources were imported or removed. Option C is wrong because the output does not indicate synchronization status; it simply lists managed resources without comparing them to the configuration or real-world infrastructure.

214
MCQeasy

A team is using Terraform to manage infrastructure across multiple environments (dev, staging, prod). They want to reuse the same root module configuration but with different variable values. Which approach is the most efficient?

A.Use environment variables to switch between configurations
B.Use a single state file that includes all environments
C.Copy the entire configuration into separate directories for each environment
D.Use Terraform workspaces
AnswerD

Terraform workspaces provide an elegant solution for managing multiple distinct environments using a single, shared configuration. Each workspace maintains its own isolated state file within the configured backend, ensuring that operations in one environment do not affect others. This approach promotes code reusability, reduces duplication, and simplifies the management of infrastructure across development, staging, and production environments effectively.

Why this answer

Terraform workspaces allow you to manage multiple distinct sets of infrastructure resources (e.g., dev, staging, prod) from the same root module configuration by maintaining separate state files for each workspace. This avoids duplicating code or manually managing state file switching, making it the most efficient approach for reusing configuration with different variable values across environments.

Exam trap

HashiCorp often tests the misconception that environment variables alone can replace state isolation, but the trap here is that environment variables only affect input values, not state management, so they cannot prevent cross-environment state conflicts.

How to eliminate wrong answers

Option A is wrong because environment variables can influence variable values but do not manage separate state files or isolate infrastructure state per environment, leading to potential state corruption or unintended modifications. Option B is wrong because a single state file for all environments would cause conflicts, as Terraform would attempt to manage resources from different environments as a single set, violating isolation and making operations like targeted updates error-prone. Option C is wrong because copying the entire configuration into separate directories duplicates code, increases maintenance overhead, and violates DRY principles, whereas workspaces achieve the same goal without duplication.

215
MCQhard

Refer to the exhibit. You need to add a security group to each instance. You have a local value defined as 'security_group_map = { "subnet-1" = "sg-1", "subnet-2" = "sg-2" }'. Which expression should be used to reference the security group ID in the resource block?

A.vpc_security_group_ids = [local.security_group_map[var.subnet_ids[count.index]]]
B.vpc_security_group_ids = [lookup(security_group_map, var.subnet_ids[count.index])]
C.vpc_security_group_ids = [security_group_map[var.subnet_ids[count.index]]]
D.vpc_security_group_ids = [lookup(local.security_group_map, var.subnet_ids[count.index])]
AnswerA

This option correctly references a local value named `security_group_map` using the `local.` prefix, which is mandatory for accessing local variables. It then uses map indexing `[...]` to retrieve a security group ID. The key for this lookup is dynamically determined by `var.subnet_ids[count.index]`, which fetches a specific subnet ID from a list variable based on the current `count` iteration, ensuring the correct security group is associated with each resource instance.

Why this answer

It properly references the local value `security_group_map` using the `local.` prefix, which is required in Terraform to access local values. It then uses the subnet ID from `var.subnet_ids[count.index]` as the key to look up the corresponding security group ID. This ensures each instance gets the correct security group based on its subnet index.

Exam trap

The Terraform exam often tests the distinction between accessing local values (requiring `local.` prefix) vs. variables or resources, and the misuse of `lookup` when direct indexing is appropriate, leading candidates to omit the `local.` prefix or use unnecessary functions.

How to eliminate wrong answers

Option B is wrong because it uses `lookup(security_group_map, ...)` without the `local.` prefix, which would cause Terraform to look for a variable or resource named `security_group_map` instead of the local value, resulting in a reference error. Option C is wrong because it directly references `security_group_map[var.subnet_ids[count.index]]` without the `local.` prefix, which is invalid syntax for accessing a local value in Terraform. Option D is wrong because it uses `lookup(local.security_group_map, ...)` but the `lookup` function is unnecessary here; direct indexing with brackets is the correct approach for a map lookup, and using `lookup` adds no benefit and can obscure the intent.

216
MCQhard

Refer to the exhibit. A team is troubleshooting a Terraform deployment. What information can be inferred from this state file?

A.The Terraform version is outdated and must be upgraded.
B.There is one EC2 instance of type t2.micro with a dependency on a security group.
C.The instance ID is invalid and needs to be recreated.
D.The security group dependency was not applied.
AnswerB

The Terraform state file, as presented in the exhibit, explicitly shows a single `aws_instance` resource. Within its attributes, `instance_type` is clearly set to `t2.micro`. Furthermore, the `vpc_security_group_ids` attribute contains an array with one entry, indicating an explicit dependency on a security group resource. This direct evidence from the state confirms the presence and configuration of the EC2 instance and its security group association.

Why this answer

The state file explicitly shows a resource of type `aws_instance` with `instance_type = "t2.micro"` and a `depends_on` meta-argument referencing `aws_security_group.example`. This indicates that Terraform recorded the EC2 instance as created with a t2.micro type and that it has a formal dependency on a security group resource, ensuring the security group is created before the instance during apply.

Exam trap

A common trick in Terraform exams is to assume that a `depends_on` entry in the state file means the dependency was 'not applied' or that the state file is invalid without a `terraform_version`, but in reality the presence of the dependency list confirms it was recorded and enforced.

How to eliminate wrong answers

Option A is wrong because the state file does not contain any version metadata or `terraform_version` field that would indicate an outdated version; Terraform state files include a `terraform_version` key only if the state was written by a newer version, and its absence or presence does not imply a required upgrade. Option C is wrong because the state file shows a valid `id` for the EC2 instance (e.g., `i-0abcd1234efgh5678`), and there is no indication of invalidity or need for recreation; instance IDs in state are simply recorded identifiers, not validated against the live cloud. Option D is wrong because the `depends_on` attribute in the state file explicitly records that the dependency on the security group was applied; if it were not applied, the `depends_on` block would be absent or empty.

217
MCQeasy

A configuration uses variables defined in a 'variables.tf' file. The operator wants to override these variables for a specific run without modifying the file. Which method should they use?

A.Edit the state file directly.
B.Set environment variables with the same name as the variables.
C.Create a 'terraform.tfvars' file.
D.Use the '-var' flag with 'terraform plan' or 'terraform apply'.
AnswerD

The `-var` flag, used with commands like `terraform plan` or `terraform apply`, is the most direct and idiomatic way to provide or override variable values for a single Terraform execution. Values supplied via `-var` on the command line take the highest precedence, ensuring they are used for that specific run, and are not persisted for subsequent operations. This method is ideal for temporary adjustments, sensitive data, or testing different configurations without modifying files.

Why this answer

The `-var` flag on `terraform plan` or `terraform apply` allows operators to override variable values for a single run without modifying any files. This is the correct method because it provides a temporary override that does not persist across runs, unlike file-based or environment variable approaches.

Exam trap

HashiCorp often tests the variable precedence order, and the trap here is that candidates confuse environment variables (`TF_VAR_*`) with the `-var` flag, thinking both are equally temporary, but environment variables persist for the entire shell session, whereas `-var` applies only to the single command invocation.

How to eliminate wrong answers

Option A is wrong because editing the state file directly is dangerous and unsupported; Terraform state is a JSON representation of infrastructure, not a configuration input, and manual edits can cause corruption or drift. Option B is wrong because environment variables with the same name as Terraform variables (e.g., `TF_VAR_<name>`) do override variables, but they affect all runs in that shell session, not just a specific run, and the question explicitly asks for a method that overrides for a specific run without modifying files. Option C is wrong because creating a `terraform.tfvars` file permanently overrides the default values in `variables.tf` for all runs in that directory, which violates the requirement to override for a specific run only.

218
Multi-Selecthard

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

Select 3 answers
A.Edit state files directly to fix drift
B.Use remote backends to store state files
C.Enable versioning on the state storage backend
D.Store state files locally to avoid network latency
E.Use state locking to prevent concurrent modifications
AnswersB, C, E

Remote backends enable sharing and locking.

Why this answer

Remote backends (e.g., S3, Azure Storage, Terraform Cloud) store state outside the local filesystem, enabling team collaboration, durability, and integration with state locking and encryption. This prevents loss of state due to local machine failure and ensures all team members work from the same state file, which is critical for consistent infrastructure management.

Exam trap

HashiCorp often tests the misconception that local state is simpler and thus better for small teams, but the exam expects you to recognize that remote backends with locking and versioning are mandatory best practices for any collaborative or production Terraform workflow.

219
MCQeasy

Refer to the exhibit. The configuration fails with an error indicating that the module does not support the 'enable_vpn_gateway' argument. What is the most likely cause?

A.The argument name is misspelled; it should be 'enable_vpn' instead.
B.The module version '3.18.0' does not include the 'enable_vpn_gateway' variable; it was added in a later version.
C.The module does not support VPN gateways at all.
D.The module source is incorrectly specified; it should use a git URL instead of the registry path.
AnswerB

This option correctly identifies the root cause. When a module is explicitly pinned to a specific version, such as '3.18.0', Terraform strictly adheres to the variables and outputs defined within that exact module release. The `enable_vpn_gateway` variable was introduced in a subsequent version of the `terraform-aws-vpc` module, meaning it is not recognized or available in version '3.18.0', leading to an 'Unsupported Argument' or 'Undefined Variable' error during plan or apply.

Why this answer

The error message indicates that the module does not support the 'enable_vpn_gateway' argument. In Terraform, module arguments are defined by the module's published variables. The module version '3.18.0' predates the introduction of the 'enable_vpn_gateway' variable, which was added in a later version.

Upgrading the module version to one that includes this variable resolves the error.

Exam trap

HashiCorp often tests the concept that module arguments are version-dependent, and the trap here is that candidates may assume the argument name is misspelled or that the module lacks the feature entirely, rather than recognizing that the module version simply does not include that variable yet.

How to eliminate wrong answers

Option A is wrong because the argument name 'enable_vpn_gateway' is not a misspelling of 'enable_vpn'; the error specifically states the module does not support the argument, not that the name is incorrect. Option C is wrong because the module does support VPN gateways, but the specific variable 'enable_vpn_gateway' was not available in version 3.18.0. Option D is wrong because the module source (registry path) is correctly specified; using a git URL would not change the available variables for a given module version.

220
MCQeasy

Which version of the module was downloaded and why?

A.3.0.0, because ~> 3.0 only allows the exact version 3.0.0.
B.3.19.0, because it is the latest version and version constraints are ignored.
C.3.19.0, because it is the latest version matching the constraint ~> 3.0, which allows any 3.x version.
D.3.0.0, because ~> 3.0 is limited to patch updates within 3.0.x.
AnswerC

This statement is correct because the pessimistic version constraint `~> 3.0` instructs Terraform to select the highest available module version that is greater than or equal to 3.0.0 but strictly less than 4.0.0. Given that 3.19.0 is the latest version within this `3.x` major release series, it is the one Terraform will download. This constraint allows for minor and patch updates while preventing unintended major version upgrades that could introduce breaking changes.

Why this answer

The constraint `~> 3.0` in Terraform's version constraint syntax allows only the rightmost element to increment. Since `3.0` is a two-part version, the constraint permits any version in the `3.x` range (i.e., `3.0.0` up to but not including `4.0.0`). Therefore, the latest version matching that constraint is `3.19.0`, which is the highest available 3.x version.

Exam trap

The trap here is that candidates often confuse the behavior of `~> 3.0` (which allows any 3.x version) with `~> 3.0.0` (which restricts to patch updates only within 3.0.x), leading them to incorrectly select option D.

How to eliminate wrong answers

Option A is wrong because `~> 3.0` does not pin to the exact version `3.0.0`; it allows any version in the `3.x` range, not just `3.0.0`. Option B is wrong because version constraints are never ignored in Terraform; the resolver always respects the declared constraints and will not download a version outside the allowed range. Option D is wrong because `~> 3.0` is not limited to patch updates within `3.0.x`; that behavior would apply to a three-part constraint like `~> 3.0.0`, which restricts to `3.0.x` only.

221
MCQmedium

Refer to the exhibit. What will happen when you run terraform plan?

A.The plan will prompt for the name interactively.
B.The plan will succeed and create the IAM user with a generated name.
C.The plan will fail with an error about missing required argument.
D.The plan will create the user with the path only.
AnswerC

Terraform performs rigorous configuration validation during the `plan` phase, checking the provided arguments against the resource's schema defined by its respective provider. For the `aws_iam_user` resource, the `name` attribute is unequivocally marked as required. Therefore, omitting this critical argument will trigger a validation error, causing the `terraform plan` command to fail before any changes can be proposed or applied.

Why this answer

The configuration is missing the required 'name' argument for an IAM user resource. Terraform will fail during the planning phase with an error indicating that the required argument is missing. Option C correctly identifies this error.

Option A is incorrect because Terraform does not prompt for missing required arguments interactively; it fails with an error. Option B is incorrect because the plan cannot succeed without the required 'name' argument. Option D is incorrect because the resource cannot be created without the name; the path alone is insufficient.

222
MCQmedium

An organization uses a shared remote backend. They want to prevent concurrent apply operations that could corrupt the state. What built-in mechanism does Terraform provide?

A.State locking
B.File permissions on the remote state file
C.Workspace isolation
D.State file versioning
E.Backend versioning
AnswerA

State locking is a critical feature for shared remote backends, designed to prevent race conditions and state corruption when multiple users or automated processes attempt to modify the infrastructure simultaneously. When an operation like `terraform plan` or `terraform apply` begins, Terraform acquires a lock on the state file, preventing any other operation from writing to it until the current operation completes or the lock is explicitly released. This ensures atomic updates, guaranteeing that only one modification occurs at a time, thus maintaining state consistency and integrity.

Why this answer

Terraform's state locking mechanism prevents concurrent operations that could corrupt the state file by acquiring a lock on the backend before running `plan` or `apply`. When using a shared remote backend, the lock is held for the duration of the operation and released upon completion, ensuring only one process modifies the state at a time. Option D refers to state file versioning, which provides the ability to recover previous versions but does not prevent concurrent writes.

Exam trap

HashiCorp often tests the distinction between state locking and state file versioning, where candidates confuse versioning (which provides recovery) with locking (which prevents concurrent writes).

How to eliminate wrong answers

Option B is wrong because file permissions on the remote state file (e.g., S3 bucket policies) control access but do not prevent concurrent writes from multiple Terraform processes; they are a security measure, not a concurrency control. Option C is wrong because workspace isolation separates state files by workspace but does not prevent concurrent applies within the same workspace; it addresses environment separation, not locking. Option D is wrong because it is a duplicate of the correct answer (A) and is listed as a separate option, but the question expects a single correct mechanism; selecting D would be redundant and incorrect if A is chosen.

Option E is wrong because backend versioning (e.g., S3 versioning) keeps historical state file versions but does not prevent concurrent writes; it provides recovery from corruption, not prevention.

223
MCQeasy

A team uses Terraform to manage infrastructure. After running 'terraform apply', a developer notices that a new security group rule was added, but then immediately removed. What is the most likely cause?

A.The security group rule was added manually and Terraform removed it to match the configuration.
B.The state file was corrupted and Terraform performed a refresh.
C.The configuration was changed to remove the rule after the apply.
D.The developer accidentally ran 'terraform destroy' instead.
AnswerA

Terraform's core principle is to manage infrastructure to match the desired state defined in its configuration files. When a security group rule is added manually outside of Terraform, it creates a "drift" between the actual infrastructure and Terraform's known desired state. During a subsequent `terraform apply` operation, Terraform detects this unmanaged rule and, in its effort to enforce the configured state, removes the rule to bring the infrastructure back into alignment with what is declared in the `.tf` files.

Why this answer

Terraform operates on a desired-state model: it compares the configuration in `.tf` files against the real-world infrastructure and the state file. If a security group rule was added manually outside of Terraform, Terraform detects it as a drift during the next `apply` and removes it to reconcile the actual state with the declared configuration. This is the core behavior of Terraform's lifecycle management.

Exam trap

HashiCorp often tests the misconception that Terraform only adds resources and never removes them, or that manual changes are automatically adopted; the trap here is that candidates confuse Terraform's 'import' capability (which requires explicit import) with automatic drift correction, leading them to think Terraform would preserve the manual rule.

How to eliminate wrong answers

Option B is wrong because a corrupted state file would cause errors or a refresh failure, not a targeted removal of a single resource; Terraform would not silently add and then remove a rule due to corruption. Option C is wrong because if the configuration was changed to remove the rule before the apply, Terraform would simply not create it in the first place, not add it and then immediately remove it. Option D is wrong because `terraform destroy` would tear down the entire security group (or all resources), not just add and remove a single rule.

224
Multi-Selecteasy

Which TWO statements about using Terraform with remote backends are correct?

Select 2 answers
A.Remote backends require manual state migration.
B.Remote backends store state in a shared location.
C.Remote backends store state in the local filesystem.
D.Remote backends cannot be used with Terraform Cloud.
E.Remote backends enable state locking.
AnswersB, E

Remote backends are fundamentally designed to store Terraform's state file in a centralized, shared location, such as an S3 bucket, Azure Storage Account, or a dedicated Terraform Cloud workspace. This shared storage ensures that all team members working on the same infrastructure configuration have access to the most current state of the managed resources. This collaborative approach prevents conflicts and ensures consistency across deployments, making it a critical feature for team environments.

Why this answer

Remote backends enable state locking and store state in a shared location, preventing conflicts and enabling team collaboration. The other options are incorrect: remote backends do not store state locally, can be used with Terraform Cloud, and migration can be automated.

225
MCQhard

A developer has a module that outputs a list of subnet IDs. They want to use this list to create an EC2 instance in each subnet using for_each. Which for_each expression is correct?

A.module.my_module.ids
B.toset(module.my_module.ids)
C.{ for id in module.my_module.ids : id => id }
D.module.my_module.ids[*]
AnswerB

The `toset()` function is the correct choice because Terraform's `for_each` argument specifically requires a set of strings or a map. When applied to a list, `toset()` converts it into a set, automatically deduplicating any identical elements. This ensures that each subnet ID from the module's output becomes a unique, stable key for `for_each`, allowing Terraform to reliably manage distinct resource instances.

Why this answer

`for_each` in Terraform requires a map or a set of strings to iterate over, and `toset()` converts the list of subnet IDs into a set, which is a valid input for `for_each`. A plain list (as in option A) is not directly supported by `for_each`, which expects a map or set to ensure unique keys and deterministic behavior.

Exam trap

The trap here is that candidates often assume `for_each` accepts lists directly, confusing it with `count`, or they overcomplicate the solution with a map expression when `toset()` is the simplest and most correct approach.

How to eliminate wrong answers

Option A is wrong because `module.my_module.ids` is a list, and `for_each` does not accept a list directly; it requires a map or set of strings. Option C is wrong because while it creates a map from the list, it is unnecessarily verbose and redundant; `toset()` is the idiomatic and simpler approach. Option D is wrong because `module.my_module.ids[*]` is a splat expression that still produces a list, not a set or map, and thus is invalid for `for_each`.

Page 2

Page 3 of 6

Page 4

All pages