Courseiva

CCNA Understand Terraform basics Questions

45 questions · Understand Terraform basics · All types, answers revealed

1
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

2
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

3
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

4
MCQmedium

Refer to the exhibit. Which change to the configuration would prevent this error in the future?

A.Hardcode a different AMI ID.
B.Set the AMI to null.
C.Add a lifecycle rule to ignore changes.
D.Use a data source to fetch the AMI dynamically.
AnswerD

Using a data source to fetch the AMI dynamically is the correct and most robust solution. A data source, such as `aws_ami`, queries the AWS API at `terraform plan` time, using filters (e.g., owner, name patterns, tags) to retrieve the most current and valid AMI ID that matches the specified criteria. This ensures that the EC2 instance is always provisioned with an existing and up-to-date image, effectively preventing `InvalidAMIID.NotFound` errors caused by stale or hardcoded values.

Why this answer

Using a data source to dynamically fetch the correct AMI avoids hardcoding invalid IDs and ensures the AMI exists in the region.

5
MCQmedium

Refer to the exhibit. A user runs 'terraform plan' and sees this output. However, when they run 'terraform apply', they get an error: 'Error creating EC2 instance: UnauthorizedOperation: You are not authorized to perform this operation.' The user's IAM permissions allow ec2:RunInstances. What is the most likely missing permission?

A.ec2:CreateNetworkInterface
B.iam:PassRole
C.ec2:TerminateInstances
D.ec2:DescribeInstances
AnswerA

When creating an EC2 instance, AWS automatically provisions a primary network interface (ENI) for it, even if not explicitly configured in Terraform. This ENI handles network connectivity, including IP addresses and security groups. The `UnauthorizedOperation` error during `terraform plan` for an EC2 instance creation often indicates that the IAM principal (user or role) executing Terraform lacks the necessary `ec2:CreateNetworkInterface` permission to perform this underlying AWS API call. Without this permission, the instance provisioning fails at a fundamental networking step.

Why this answer

Creating an EC2 instance often requires permissions for related resources like network interfaces, security groups, etc. The error 'UnauthorizedOperation' despite having ec2:RunInstances suggests missing permissions for other actions. Option A is correct because the instance might require a subnet and network interface, and without ec2:CreateNetworkInterface permission, the operation fails.

6
MCQeasy

A junior engineer cloned a Terraform repository from GitHub and ran terraform init inside the project directory. The command downloaded the required provider plugins successfully. Next, they ran terraform plan and received the following error: 'Error: No configuration files found in the current directory.' The engineer checked and confirmed that the main.tf file exists in the current directory. What is the most likely cause of this error?

A.The file is named main.tf.txt instead of main.tf
B.The terraform init command was not run with -upgrade flag
C.The main.tf file contains syntax errors
D.The terraform plan command requires the -out flag
AnswerA

Terraform's configuration loader specifically scans for files ending with the `.tf` extension within the working directory and its subdirectories. Files named with other extensions, such as `.tf.txt`, are completely ignored during the parsing phase, even if they contain valid HCL syntax. Consequently, if the primary configuration is misnamed, Terraform will report that no configuration files were found, as it simply doesn't recognize the file as part of its operational scope. This prevents accidental inclusion of non-Terraform files.

Why this answer

Terraform requires configuration files to have the `.tf` extension to be recognized. If the file is named `main.tf.txt` (e.g., due to Windows hiding known file extensions or accidental renaming), Terraform will not parse it as a configuration file, resulting in the 'No configuration files found' error even though the file exists in the directory. The `terraform init` command succeeded because it only downloads providers and modules, not requiring `.tf` files to be present.

Exam trap

HashiCorp often tests the subtle distinction between file existence and file recognition by Terraform, exploiting the common assumption that any file in the directory will be read, when in fact only files with the exact `.tf` extension are parsed.

How to eliminate wrong answers

Option B is wrong because the `-upgrade` flag is used to upgrade provider plugins to the latest version within the version constraint, not to make configuration files discoverable. Option C is wrong because syntax errors in `main.tf` would cause a different error during `terraform plan` (e.g., 'Error: Unsupported argument' or 'Error: Invalid expression'), not a 'No configuration files found' error. Option D is wrong because the `-out` flag is optional and only used to save the plan to a file; `terraform plan` runs successfully without it as long as configuration files are present.

7
MCQmedium

A company wants to use Terraform to create Azure resources. They have written a configuration file but when they run `terraform init`, they get a warning about an 'incomplete lock file'. What should they do first?

A.Change the provider version in the configuration
B.Run `terraform apply` immediately
C.Run `terraform plan` to update the lock file
D.Delete the `.terraform.lock.hcl` and re-run `terraform init`
E.Run `terraform validate` to fix the warning
AnswerD

The `.terraform.lock.hcl` file serves to pin the exact versions and cryptographic checksums of providers used in a configuration, ensuring consistent and reproducible deployments. If this file becomes corrupted, outdated, or inconsistent with the actual provider requirements, deleting it forces `terraform init` to perform a fresh resolution of all provider dependencies. Subsequently re-running `terraform init` will then download the appropriate providers and generate a new, accurate `.terraform.lock.hcl` file based on the current configuration's `required_providers` block.

Why this answer

The warning about an 'incomplete lock file' indicates that the `.terraform.lock.hcl` file is corrupted, incomplete, or from an incompatible provider version. The correct first step is to delete the existing lock file and re-run `terraform init`, which will regenerate a fresh lock file based on the current configuration and provider requirements. This ensures dependency integrity before any planning or applying.

Exam trap

A common pitfall in Terraform is assuming that `terraform plan` or `terraform validate` can repair lock file issues, when in fact only `terraform init` (or manual deletion of `.terraform.lock.hcl`) will resolve dependency tracking problems.

How to eliminate wrong answers

Option A is wrong because changing the provider version in the configuration does not address a corrupted or incomplete lock file; it would only change which provider is referenced, not fix the lock file itself. Option B is wrong because running `terraform apply` without a valid lock file could lead to unexpected provider versions or dependency resolution failures, and Terraform will refuse to proceed with an incomplete lock file. Option C is wrong because `terraform plan` does not update the lock file; it reads the existing lock file and will fail or warn if the lock file is incomplete.

Option E is wrong because `terraform validate` checks configuration syntax and internal consistency, not the integrity of the dependency lock file.

8
MCQhard

Refer to the exhibit. An engineer runs 'terraform plan' and receives an error: 'Error refreshing state: state data in S3 does not have the expected content.' The state file exists and is not corrupted. What is the most likely cause?

A.The state file is locked by another process.
B.The state file was written by a different backend configuration (e.g., different key or workspace).
C.The DynamoDB table does not exist.
D.The S3 bucket is in a different region.
AnswerB

Terraform state files include a "serial" attribute that increments with each successful `apply` operation, acting as a version number for the infrastructure state. When a state file is accessed or modified through a different backend configuration, such as a distinct S3 key, a separate workspace, or even a different backend type, Terraform might encounter a `serial` number that does not align with its expected sequence for the current working directory. This discrepancy triggers a "state serial mismatch" error, indicating that the current operation is attempting to interact with a state file that has an unexpected or inconsistent version history.

Why this answer

The error 'state data in S3 does not have the expected content' indicates a mismatch between the state file's content and what Terraform expects based on the current backend configuration. This typically occurs when the state file was written using a different backend key, workspace, or bucket path, causing Terraform to read a state that does not match the expected serial or lineage. The state file itself is not corrupted, but the backend configuration (e.g., different `key` or `workspace_key_prefix`) points to a different state object in S3.

Exam trap

Terraform often tests the distinction between state lock errors and state content mismatch errors, trapping candidates who confuse a missing DynamoDB table or a locked state with a backend configuration mismatch.

How to eliminate wrong answers

Option A is wrong because a locked state file would produce a different error, such as 'Error acquiring the state lock' or 'state file is locked', not a content mismatch error. Option C is wrong because a missing DynamoDB table would cause a lock-related error (e.g., 'failed to query lock table') or a permission error, not a state content mismatch. Option D is wrong because an S3 bucket in a different region would result in a 'bucket does not exist' or 'region mismatch' error, not a content mismatch, as Terraform uses the configured region to access the bucket.

9
MCQeasy

A team is new to Terraform and wants to manage their cloud infrastructure. They have written configuration files but have not yet run any commands. What is the correct sequence of initial steps to deploy their infrastructure?

A.Run terraform init, then terraform plan, then terraform apply
B.Run terraform plan, then terraform apply, then terraform init
C.Run terraform validate, then terraform plan, then terraform apply
D.Run terraform apply, then terraform plan, then terraform init
AnswerA

This sequence represents the standard and required workflow for managing infrastructure with Terraform. The `terraform init` command is essential for initializing the working directory, downloading necessary provider plugins and modules, and setting up the backend. Following this, `terraform plan` generates an execution plan, detailing all proposed infrastructure changes without making any modifications. Finally, `terraform apply` executes this plan, provisioning or modifying the infrastructure to match the desired state defined in the configuration.

Why this answer

The correct sequence is `terraform init`, `terraform plan`, then `terraform apply`. `terraform init` must be run first to initialize the working directory, download required provider plugins (e.g., AWS, Azure), and set up the backend state storage. Without initialization, subsequent commands like `plan` and `apply` will fail because Terraform cannot locate providers or configure the state backend. After initialization, `terraform plan` creates an execution plan showing what resources will be created, modified, or destroyed, and `terraform apply` executes that plan to deploy the infrastructure.

Exam trap

A common mistake is thinking that `terraform validate` or `terraform plan` can be run before `terraform init`, but in reality, `init` is mandatory first because it downloads providers and sets up the backend, without which no other command can execute.

How to eliminate wrong answers

Option B is wrong because `terraform plan` and `terraform apply` require an initialized working directory; running `plan` before `init` will fail with an error about missing providers or backend configuration. Option C is wrong because `terraform validate` is optional and checks syntax/correctness but is not a required initial step; the mandatory first step is always `terraform init` to download providers and set up state. Option D is wrong because `terraform apply` cannot run before `terraform init` (no providers or state) and `terraform plan` must precede `apply` to review changes; running `apply` without `plan` is possible but dangerous and not the correct initial sequence.

10
MCQhard

Refer to the exhibit. A user applies this configuration. They then run 'terraform destroy' but the destroy fails with an error: 'Error deleting load balancer: DependencyViolation: The load balancer 'arn:aws:elasticloadbalancing:...' cannot be deleted because it is currently associated with another resource.' The user has not made any changes to the resources. What is the most likely cause?

A.The aws_lb_listener does not have explicit depends_on for the aws_lb_target_group.
B.The aws_lb_target_group is missing an explicit depends_on for the aws_lb_listener.
C.The aws_lb_target_group is missing an explicit depends_on for the aws_lb.
D.The aws_lb_listener is missing an explicit depends_on for the aws_lb.
AnswerD

The aws_lb_listener is indeed missing an explicit depends_on for the aws_lb. AWS API rules mandate that listeners must be deleted before their associated load balancer can be destroyed. Without an explicit depends_on on the listener for the load balancer, Terraform might attempt to destroy the load balancer first, leading to a DependencyViolation error from AWS. This explicit dependency ensures the correct destruction order, preventing the error.

Why this answer

The destroy fails because Terraform attempts to delete the load balancer before the listener that is associated with it. The listener has an implicit dependency on the load balancer via the `load_balancer_arn` attribute, but Terraform may not always recognize this implicit dependency, especially if the reference is indirect. Therefore, an explicit `depends_on` from the listener to the load balancer is required to ensure the listener is destroyed first, releasing the association and allowing the load balancer to be deleted.

Option D correctly identifies this missing dependency on the listener.

Exam trap

The error 'DependencyViolation' indicates that the load balancer cannot be deleted because it is still associated with a listener. Although the listener references the load balancer via `load_balancer_arn`, Terraform may not always infer this implicit dependency, especially if the reference comes from a module output or variable. Adding an explicit `depends_on` from the listener to the load balancer ensures the listener is destroyed first, releasing the association.

11
MCQeasy

A developer is new to Terraform and wants to understand the purpose of the terraform init command. Which statement correctly describes its primary function?

A.It initializes the local environment by downloading the required provider plugins and modules.
B.It checks the syntax of all configuration files.
C.It compares the state file with real infrastructure.
D.It creates the initial configuration for a new Terraform project.
AnswerA

The `terraform init` command is foundational, executed first in a new or cloned Terraform project to prepare the local environment. It scans the configuration files (e.g., `.tf` files) to identify all declared `required_providers` and any `module` blocks. Subsequently, it downloads the specified provider plugins from the Terraform Registry or configured mirrors, and fetches remote modules, storing them in the `.terraform` directory. This process ensures all necessary components are available for subsequent commands like `terraform plan` or `terraform apply`.

Why this answer

`terraform init` is the first command to run in any Terraform project. Its primary function is to initialize the working directory by downloading and installing the required provider plugins (e.g., from the Terraform Registry) and modules specified in the configuration. It also sets up the backend for state storage and locks, ensuring the local environment is ready for subsequent commands like `plan` and `apply`.

Exam trap

A common trap in Terraform certification is confusing `terraform init` with `terraform validate` or `terraform plan`. Candidates may think `init` checks syntax or creates the project, but it strictly downloads providers/modules and initializes the backend.

How to eliminate wrong answers

Option B is wrong because syntax checking of configuration files is performed by `terraform validate`, not `init`. Option C is wrong because comparing the state file with real infrastructure is the job of `terraform plan`, which detects drift. Option D is wrong because `terraform init` does not create initial configuration; it initializes an existing configuration directory.

Creating a new project typically involves writing `.tf` files manually or using `terraform scaffold` or a template.

12
MCQhard

Refer to the exhibit. An engineer receives this error when running terraform apply. What is the most likely cause?

A.The policy JSON is missing a required field like "Sid".
B.The Action element should be an array, not a string.
C.The Resource ARN is incorrect because it lacks a region.
D.The policy exceeds the maximum size limit.
AnswerB

AWS IAM policy syntax strictly mandates that the `Action` element must be an array of strings, even when only a single action is specified. If the `Action` element is provided as a plain string (e.g., `"s3:GetObject"`) instead of being encapsulated within an array (e.g., `["s3:GetObject"]`), the IAM policy parser will encounter a type mismatch error. This fundamental syntax requirement is a common source of errors and prevents the policy from being correctly interpreted and applied.

Why this answer

The error indicates a malformed policy JSON. In IAM policy syntax, the `Action` element must be an array of strings, even if only one action is specified. The provided policy has `"Action": "ec2:DescribeInstances"` (a string), which is invalid; it should be `"Action": ["ec2:DescribeInstances"]`.

This is the most likely cause of the error.

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

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

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

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

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

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

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

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

21
Matchingmedium

Match each Terraform feature to its description.

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

Concepts
Matches

Maps real-world resources to configuration

Plugin to interact with a specific cloud or service API

Container for multiple resources used together

Defines where state snapshots are stored

Executes scripts on local or remote machine during creation/destruction

Why these pairings

Terraform State tracks resource states, Providers enable API interactions, Modules bundle resources for reuse, and Workspaces manage environments. Common confusions include swapping State with Provider or Provider with Module.

22
Drag & Dropmedium

Drag and drop the steps to set up remote state with Terraform Cloud 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 order is to first create the workspace in Terraform Cloud, then add the cloud block to your Terraform configuration referencing that workspace, and finally run terraform init which detects the cloud block and migrates the state from local to the remote workspace. Other orders fail because the workspace must exist before the cloud block is configured or init is run without proper backend configuration.

23
Matchingmedium

Match each Terraform provisioner to its typical use case.

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

Concepts
Matches

Copy files to the remote resource

Run a script on the machine running Terraform

Run a script on the remote resource

Configure resource using Chef

Configure resource using Puppet

Why these pairings

The correct matches are: file provisioner for copying files to the remote machine, remote-exec for running commands on the remote machine, and local-exec for running commands locally. Common confusions include swapping the roles of file and remote-exec.

24
Multi-Selectmedium

Which three of the following are core characteristics of Terraform's execution plan? (Choose three.)

Select 3 answers
.It is generated by the `terraform plan` command.
.It shows what actions Terraform will take to reach the desired state.
.It can be saved to a file and later applied using `terraform apply` with that file.
.It automatically applies changes to infrastructure without user confirmation.
.It only shows changes for resources that were manually modified outside Terraform.
.It is a read-only view of the current state file with no indication of future actions.

Why this answer

The `terraform plan` command generates an execution plan that shows exactly what actions Terraform will take to reach the desired state defined in the configuration. This plan can be saved to a file and later applied using `terraform apply` with that file, ensuring the exact same changes are executed. These three characteristics are fundamental to Terraform's workflow, providing a safe and predictable way to manage infrastructure changes.

Exam trap

HashiCorp often tests the misconception that the execution plan is an automatic apply mechanism or that it only detects drift from manual changes, when in fact it is a deliberate, user-initiated preview that compares the entire configuration against the current state.

25
MCQhard

A Terraform configuration uses `count` to create multiple EC2 instances. After adding a new variable for instance type, the user runs `terraform plan` and sees that all instances are marked for recreation. What is the most likely cause?

A.The `count` index changed, causing all resources to be re-indexed
B.The user forgot to run `terraform refresh` after changing the variable
C.The state file is corrupt and needs to be refreshed
D.The variable change triggers a new value for each resource, causing Terraform to see differences
E.The provider version is incompatible with the new variable type
AnswerD

When an input variable's value changes, and that variable is referenced within the configuration of resources created using `count`, Terraform re-evaluates the entire configuration. For each resource instance managed by `count`, the new variable value is used to compute its attributes. If these newly computed attributes for an existing resource instance differ from what is currently recorded in the state file, Terraform identifies these as 'differences' and proposes actions (e.g., update, replace, or destroy/create) in the execution plan to reconcile the desired state with the actual state.

Why this answer

When you change a variable that is referenced within a resource's configuration (such as `instance_type`), Terraform sees a diff between the current state and the new configuration for every resource created by `count`. Since `count` resources are identified by their index in the state, and the new variable value changes the desired configuration for each instance, Terraform plans to recreate all of them to apply the new instance type.

Exam trap

The trap here is that candidates often confuse `count` re-indexing (which happens when the count value itself changes) with the effect of changing a variable that is used inside the resource block, leading them to incorrectly select Option A.

How to eliminate wrong answers

Option A is wrong because changing the `count` index (i.e., the number of resources) would cause re-indexing, but the question states that the variable for instance type was added, not that the count value changed. Option B is wrong because `terraform refresh` updates the state to match real-world infrastructure but does not prevent Terraform from detecting configuration changes; the plan would still show recreation if the variable changed. Option C is wrong because a corrupt state file would typically cause errors or inconsistencies, not a clean plan showing all resources marked for recreation.

Option E is wrong because provider version incompatibility would manifest as errors during initialization or plan, not as a planned recreation of all instances due to a variable change.

26
MCQhard

You are a platform engineer at a fintech company. Your team manages a multi-region application on AWS using Terraform. The infrastructure includes VPCs, subnets, EC2 instances, and an Application Load Balancer (ALB). The configuration uses modules from the Terraform Registry and remote state in S3 with DynamoDB locking. Recently, after a colleague ran `terraform apply` in the us-east-1 region, the application experienced downtime because the ALB's target group was accidentally updated to point to instances in us-west-2 instead of us-east-1. The root cause was that the Terraform configuration for the ALB used a variable `target_region` which was hardcoded to us-west-2 in a `terraform.tfvars` file that was not intended for that workspace. Your team wants to prevent such misconfigurations in the future. Which course of action would most effectively reduce the risk of using incorrect variable values across workspaces?

A.Implement a CI/CD pipeline that runs `terraform plan` for every workspace and requires manual approval before apply
B.Use the same S3 backend for all regions but with different state file keys, and enforce naming conventions
C.Store all variables in a single `terraform.tfvars` file and use conditionals with `terraform.workspace` to select values
D.Create separate Terraform configurations for each region, each with its own backend configuration and variable files, and use directory structure to enforce separation
AnswerD

Creating separate Terraform configurations for each region, each within its own dedicated directory, provides the strongest form of isolation. This approach ensures that each region has its own backend configuration, state file, and explicitly defined variable files (e.g., `region.tfvars`). This physical separation makes it virtually impossible to accidentally apply variables or configurations meant for one region to another, as the `terraform` command must be executed from the correct, isolated directory.

Why this answer

Creating separate Terraform configurations for each region enforces strict isolation at the directory and backend level, preventing accidental cross-region variable injection. This approach ensures that each region's configuration has its own dedicated variable files and state, eliminating the risk of a `terraform.tfvars` file from one workspace affecting another. It aligns with infrastructure-as-code best practices for multi-region deployments where environment boundaries must be explicit.

Exam trap

The trap here is that candidates often assume workspaces provide sufficient isolation for multi-region deployments, but workspaces share the same variable files and backend configuration, making them unsuitable for preventing cross-region variable misconfigurations.

How to eliminate wrong answers

Option A is wrong because a CI/CD pipeline with manual approval only adds a process gate but does not prevent the root cause—the hardcoded variable value in the tfvars file—and can still allow the same misconfiguration to pass through if the plan output is not carefully reviewed. Option B is wrong because using the same S3 backend with different state file keys and naming conventions does not prevent a developer from accidentally applying a configuration that references the wrong region variable; it only organizes state files, not variable values. Option C is wrong because storing all variables in a single tfvars file with conditionals based on `terraform.workspace` still allows a single file to contain the wrong default or a typo, and it does not enforce separation of concerns; a misconfigured workspace name could still select the wrong value.

27
Multi-Selecthard

A company is using Terraform to manage secrets in AWS Secrets Manager. They want to ensure that sensitive values are not exposed in logs, the console, or plan output. Which two practices should they implement? (Choose two.)

Select 2 answers
A.Use the sensitive flag in variable definitions
B.Use a remote backend with encryption
C.Use a data source to fetch secrets at runtime instead of hardcoding
D.Store variable values in terraform.tfvars file
E.Mark outputs as sensitive = true
AnswersA, E

Using sensitive = true within a variable definition explicitly instructs Terraform to redact the variable's value from all CLI outputs, including terraform plan and terraform apply. This ensures that sensitive data, such as API keys or database credentials, is replaced with (sensitive value) in the console, preventing accidental exposure in build logs or terminal history. This mechanism is crucial for maintaining the confidentiality of secrets during the infrastructure provisioning lifecycle.

Why this answer

Marking a variable with `sensitive = true` in its definition block tells Terraform to redact its value in CLI output, logs, and plan output. This prevents the secret from being displayed in plaintext during `terraform plan` or `terraform apply`, even if the variable is used in a resource argument. Option E is correct because setting `sensitive = true` on an output value instructs Terraform to suppress that output in the CLI and in any logs or console displays, ensuring the secret value is not exposed after apply.

Exam trap

A common trap is thinking that using a remote backend with encryption or a data source alone is sufficient to protect secrets from exposure in logs and plan output, when in fact only explicit `sensitive` annotations on variables and outputs control CLI display.

28
MCQmedium

A developer accidentally deletes the local terraform.tfstate file. The backend is configured to store state remotely in an S3 bucket. What is the effect on Terraform operations?

A.Terraform will create a new empty state file, losing all existing managed resources.
B.Terraform will fail with an error because the local state is missing.
C.Terraform will automatically recover the state from the remote backend on the next plan or apply.
D.Terraform will prompt the user to confirm whether to use the remote state.
AnswerC

Correct. With a remote backend, Terraform downloads the state from the remote source; the local file is not the authoritative copy.

Why this answer

When a remote backend (e.g., S3) is configured, Terraform stores the state file in the remote location and maintains a local copy as a cache. Deleting the local terraform.tfstate file does not affect the remote state. On the next plan or apply, Terraform automatically pulls the latest state from the remote backend, effectively recovering it without data loss or manual intervention.

Exam trap

The HashiCorp exam often tests the misconception that Terraform requires a local state file to operate, but with a remote backend, the local file is merely a cache and its deletion does not disrupt operations.

How to eliminate wrong answers

Option A is wrong because Terraform does not create a new empty state file when a remote backend is configured; it retrieves the existing state from the remote backend, preserving all managed resources. Option B is wrong because the local state is only a cache; its absence does not cause a failure since Terraform reads from and writes to the remote backend directly. Option D is wrong because Terraform does not prompt the user for confirmation; it automatically uses the remote state as defined in the backend configuration without interactive prompts.

29
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

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

30
MCQeasy

What file extension is commonly used for Terraform configuration files?

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

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

31
Multi-Selecthard

Which three of the following are true regarding Terraform state?

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

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

Why this answer

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

Exam trap

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

32
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

33
MCQmedium

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

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

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

Why this answer

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

34
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

35
MCQmedium

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

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

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

Why this answer

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

36
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

37
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

38
MCQeasy

A developer runs terraform apply to create an AWS EC2 instance using an AMI sourced from the aws_ami data source with most_recent = true. Immediately after apply completes, the developer runs terraform plan again. The plan shows that Terraform intends to replace the EC2 instance. What is the most likely cause?

A.A new AMI was released after the apply, causing the data source to return a different AMI ID.
B.The developer did not run terraform init before the second plan.
C.The instance type was changed in the configuration between apply and plan.
D.The Terraform state file was corrupted during the apply.
AnswerA

When an `aws_ami` data source is configured with `most_recent = true`, Terraform dynamically queries AWS for the latest matching AMI during each `terraform plan` execution. If a new AMI is released by AWS between an `apply` and a subsequent `plan`, the data source will resolve to a different AMI ID. This change in the computed AMI ID, which is typically used by an `aws_instance` resource, will be detected by Terraform as a drift, necessitating the replacement of the existing EC2 instance to use the newly identified AMI.

Why this answer

The `aws_ami` data source with `most_recent = true` dynamically queries AWS for the latest AMI matching the specified filters at plan time. If a new AMI is published between the first `apply` and the subsequent `plan`, the data source returns a different AMI ID, causing Terraform to detect a change in the AMI attribute of the EC2 instance. Since the AMI ID is a force-new attribute for `aws_instance`, Terraform plans to replace the instance.

Exam trap

The TF-003 exam often tests the misconception that data source results are cached in state and remain static between runs, whereas in reality they are fetched fresh each plan, leading to potential drift when external resources change.

How to eliminate wrong answers

Option B is wrong because `terraform init` initializes the working directory and downloads providers/modules; it does not affect the freshness of data source results between plan runs. Option C is wrong because the question states the configuration was not changed between apply and plan, so a changed instance type is not the cause. Option D is wrong because a corrupted state file would typically cause errors or inconsistencies, not a clean plan to replace a resource with a different AMI ID.

39
MCQmedium

A team is using Terraform to manage infrastructure across multiple environments (dev, test, prod). They want to reuse the same configuration but vary resource configurations like instance size and number of instances. Which Terraform feature should they use?

A.Separate directories with symlinks
B.Remote backends with different state files
C.Terraform modules with variables
D.Terraform workspaces
AnswerC

Terraform modules with variables are the correct and recommended pattern for managing infrastructure across multiple environments or teams. Modules encapsulate a set of related resources into a reusable component, which can then be instantiated multiple times. By passing different variable values to the module for each environment (e.g., `dev`, `staging`, `prod`), teams can deploy identical infrastructure patterns with environment-specific configurations, promoting consistency, reducing code duplication, and simplifying maintenance.

Why this answer

Terraform modules with variables allow you to define reusable infrastructure and pass environment-specific variable values. This is the recommended approach for code reuse across environments.

40
Multi-Selecthard

Which TWO of the following are valid ways to reference a resource attribute in Terraform?

Select 2 answers
A.`module.vpc.output`
B.`data.aws_ami.ubuntu.id`
C.`var.instance_type`
D.`module.vpc.vpc_id`
E.`aws_instance.web.id`
AnswersD, E

This is a valid way to reference an attribute. It correctly accesses the `vpc_id` output from a child module named `vpc`. Module outputs are commonly used to expose specific attributes or computed values from resources managed within that module, making them accessible to the parent module or other parts of the configuration. This effectively references a value derived from a resource within the module, making it a valid answer.

Why this answer

`module.vpc.vpc_id` directly references an output attribute from a module. In Terraform, module outputs are accessed using the syntax `module.<module_name>.<output_name>`, and `vpc_id` is a common output from VPC modules that exposes the ID of the created VPC resource.

Exam trap

HashiCorp often tests the distinction between resource attributes, data source attributes, module outputs, and input variables, and the trap here is that candidates confuse data source references (like `data.aws_ami.ubuntu.id`) with resource attribute references, or they think `module.vpc.output` is a valid catch-all syntax for module outputs.

41
MCQmedium

Refer to the exhibit. An engineer runs terraform plan and sees this output. Which statement about the planned change is true?

A.The change will replace the existing ingress rule with a new one.
B.The security group will be destroyed and recreated.
C.Terraform will add a new ingress rule without removing the old one.
D.The security group will be updated but the ingress rule will remain unchanged.
AnswerA

The plan output shows '-/+' next to the ingress rule, meaning Terraform will destroy the existing rule and create a new one with the updated CIDR block. This is a replacement, not an in-place update.

Why this answer

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

42
MCQhard

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

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

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

Why this answer

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

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

43
MCQhard

A team uses Terraform with a remote backend that stores state in Azure Storage. A developer runs terraform apply and receives an error: 'Error refreshing state: state data in Azure Blob does not have expected content.' What is the most likely cause?

A.The Azure Storage account access key has expired.
B.The blob name contains uppercase letters.
C.The Terraform version is incompatible with the backend.
D.The state file was manually edited.
AnswerD

Manually editing a Terraform state file directly introduces a high risk of corrupting its intricate JSON structure. Even minor syntax errors, like a missing comma, an unclosed bracket, or invalid data types, will cause Terraform's strict JSON parser to fail. When Terraform encounters such malformed content, it cannot interpret the file as valid state data, leading directly to an 'unexpected content' or parsing error.

Why this answer

The error 'state data in Azure Blob does not have expected content' indicates that Terraform's internal consistency check failed when reading the state file. This typically occurs when the state file has been manually edited outside of Terraform, corrupting its JSON structure or checksum. Terraform expects the state to be in a specific format and will reject any blob content that does not match its expected schema or hash.

Exam trap

A common mistake is to confuse authentication/authorization errors (like expired access keys) with state integrity errors. The error message specifically indicates a content validation failure, not a permission issue.

How to eliminate wrong answers

Option A is wrong because an expired storage account access key would result in an authentication error (e.g., '403 Forbidden' or 'Storage authentication failed'), not a content validation error. Option B is wrong because Azure Blob Storage is case-insensitive for blob names, and Terraform normalizes blob names to lowercase; uppercase letters would not cause a content mismatch error. Option C is wrong because version incompatibility between Terraform and the backend typically produces a 'backend initialization' or 'unsupported protocol version' error, not a state content validation error.

44
MCQhard

A developer runs terraform plan and sees a large number of resources will be destroyed. They suspect the state file is corrupted. They have a recent backup of the state file. Which command can help recover the previous state from the backup?

A.terraform state push
B.No command can recover; they must re-import all resources.
C.terraform state rm
D.terraform state pull
AnswerA

When a Terraform state file becomes corrupted or is accidentally deleted, and a valid backup of the state file exists locally, `terraform state push` is the command used to upload this backup to the configured remote backend. This action overwrites the current (potentially invalid or missing) state in the backend with the provided backup, effectively restoring the infrastructure's known state. This allows subsequent `terraform plan` and `apply` operations to correctly reflect the deployed resources.

Why this answer

The `terraform state push` command is used to manually upload a local state file to the remote backend, overwriting the current remote state. In this scenario, the developer can use a recent backup of the state file and run `terraform state push` to restore the previous state, effectively recovering from the corruption. This command directly replaces the remote state with the specified local file, allowing Terraform to revert to the known good state.

Exam trap

The trap here is that candidates often confuse `terraform state push` with `terraform state pull`, assuming that pulling a backup file is the recovery action, but only `push` can overwrite the remote state with a local backup.

How to eliminate wrong answers

Option B is wrong because Terraform provides state management commands to recover from backups without requiring re-importing all resources, which would be time-consuming and error-prone. Option C is wrong because `terraform state rm` is used to remove specific resources from the state file, not to restore a previous state from a backup. Option D is wrong because `terraform state pull` downloads the current remote state to a local file; it does not push a backup back into the remote backend.

45
MCQhard

A company uses Terraform to manage infrastructure across dev, staging, and production environments. They use Terraform workspaces to separate state files. The backend is configured with an S3 bucket for state storage and a DynamoDB table for state locking. Recently, the team has grown from 2 to 10 developers, and they frequently encounter the error: 'Error acquiring the state lock' when running terraform apply in quick succession. The error message includes: 'Lock Info: ID: ... Operation: Apply. Who: user@company.com. Version: 1.0.0. Created: ...' The error occurs intermittently, especially during peak deployment times. The DynamoDB table is configured with 5 read and 5 write capacity units. The team's current workflow involves multiple developers running apply on different workspaces simultaneously. Which course of action should the team take to minimize state locking errors?

A.Disable state locking to eliminate the error.
B.Increase the DynamoDB table's write capacity units to a higher value.
C.Use a different backend that does not support locking, such as local state.
D.Implement a pre-apply hook that checks if the state is already locked and waits.
AnswerB

Terraform's S3 backend utilizes a DynamoDB table for state locking, where a lock is acquired by writing a unique item to this table. Insufficient write capacity units (WCUs) on the DynamoDB table can cause these lock acquisition attempts to be throttled or fail, especially under high concurrency from multiple developers. Increasing the WCUs ensures that DynamoDB can handle the required throughput for lock writes and updates, thereby reducing throttling errors and allowing successful lock acquisition.

Why this answer

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

Ready to test yourself?

Try a timed practice session using only Understand Terraform basics questions.