CCNA Use the core Terraform workflow Questions

53 questions · Use the core Terraform workflow · All types, answers revealed

1
MCQhard

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

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

Force-unlock should only be used if the lock is orphaned, after verifying no other process is using it.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

2
MCQeasy

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

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

Correct! Backend region is separate from provider region.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

3
Multi-Selectmedium

Which TWO of the following are valid steps in the core Terraform workflow?

Select 2 answers
A.Run terraform import to bring existing resources under management
B.Run terraform init to initialize the working directory and download providers
C.Run terraform output to retrieve output values
D.Run terraform apply to create or update infrastructure
E.Run terraform destroy to remove resources
AnswersB, D

Init is the first step to set up the environment.

Why this answer

Option B is correct because `terraform init` is the first step in the core Terraform workflow, which initializes the working directory, downloads the required provider plugins, and sets up the backend configuration. Without this step, subsequent commands like `terraform plan` or `terraform apply` cannot function, as the providers and state backend are not yet configured.

Exam trap

HashiCorp often tests the distinction between the core workflow (init, plan, apply) and auxiliary commands (import, output, destroy, state), so candidates mistakenly select commands that are commonly used but not part of the three-step core workflow.

4
MCQmedium

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

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

Import brings the existing resource into Terraform state so it can be managed.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

5
MCQhard

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

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

Correct! This allows incremental migration without resource recreation.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

6
Multi-Selecteasy

Which TWO statements accurately describe the `terraform plan` command? (Select TWO.)

Select 2 answers
A.It can be used to destroy infrastructure if the `-destroy` flag is set
B.It applies changes to infrastructure
C.It requires no configuration files in the directory
D.It automatically refreshes the state before creating the plan
E.It can output a plan to a file using the `-out` option
AnswersD, E

By default, `terraform plan` refreshes state (unless `-refresh=false`).

Why this answer

`terraform plan` creates an execution plan and can optionally save it to a file. It does not apply changes; it only shows what will happen. It supports refresh option.

7
MCQeasy

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

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

This is the recommended approach for environment isolation.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

8
Multi-Selectmedium

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

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

terraform init downloads required providers into .terraform directory.

Why this answer

Option C is correct because `terraform init` downloads the provider plugins specified in the configuration from the Terraform Registry or other configured sources. This is a core function of the init command, ensuring the required plugins are available locally before any operations like plan or apply are executed.

Exam trap

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

9
MCQhard

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

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

The AccessDenied indicates the IAM role lacks permission to set the policy on that bucket.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

10
MCQeasy

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

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

This provides secure, shared state storage with locking to prevent conflicts.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

11
MCQhard

A team uses Terraform with remote state in Azure Storage. They have a CI/CD pipeline that runs terraform plan and apply. Recently, a team member ran terraform apply manually from their local machine and the process crashed due to a network interruption. Now, the pipeline's next run fails with an error: "Error: Error acquiring the state lock". The team is unsure who holds the lock. They need to proceed with the pipeline as soon as possible. What should they do?

A.Use terraform force-unlock with the lock ID to break the lock.
B.Wait for the lock to expire automatically.
C.Re-run terraform apply with -lock=false to skip locking.
D.Delete the .terraform folder and reinitialize.
AnswerA

Force-unlock allows you to remove a stuck lock, but should be used cautiously.

Why this answer

The correct action is to use `terraform force-unlock` with the lock ID to break the stale lock. When a Terraform process crashes while holding a state lock (stored in Azure Blob Storage via the `azurerm` backend), the lock remains in place, blocking all subsequent operations. The `force-unlock` command is the designed mechanism to manually release such locks, and the lock ID can be obtained from the error message or by querying the Azure Storage blob's lease state.

Exam trap

HashiCorp often tests the misconception that `-lock=false` is a safe workaround for lock issues, but in reality it bypasses safety guarantees and can lead to state corruption, while `force-unlock` is the correct, intended recovery command.

How to eliminate wrong answers

Option B is wrong because Terraform state locks do not have a built-in expiration mechanism; they persist until explicitly released, so waiting will not resolve the issue. Option C is wrong because using `-lock=false` skips lock acquisition entirely, which risks concurrent state modifications and data corruption, and is not a safe or recommended practice for resolving a stuck lock. Option D is wrong because deleting the `.terraform` folder and reinitializing only clears local cached data and provider plugins; it does not affect the remote state lock held in Azure Storage, so the pipeline would still fail with the same lock error.

12
MCQmedium

A developer is reviewing a terraform plan output and sees that a resource of type "aws_instance" with name "web" will be updated. The developer expected no changes because the configuration hasn't been modified. The instance was manually resized in the AWS console by another team. The developer wants to reconcile the state without destroying the instance. What should they do?

A.Run terraform apply -refresh-only to update the state to match reality.
B.Run terraform state rm aws_instance.web and then terraform import.
C.Manually edit the state file to match the instance attributes.
D.Run terraform apply with -target=aws_instance.web to update only that resource.
AnswerA

Refresh-only syncs state with real-world infrastructure without making changes.

Why this answer

Option A is correct because `terraform apply -refresh-only` updates the Terraform state to match the actual infrastructure without making any configuration changes. This command reads the current state of the `aws_instance.web` resource from AWS and writes it to the state file, reconciling the drift caused by the manual resize. It does not destroy or recreate the instance, preserving the existing resource.

Exam trap

HashiCorp often tests the distinction between `terraform apply -refresh-only` and `terraform apply` with `-target`, where candidates mistakenly think targeting a resource will only refresh it, but in reality `-target` still applies configuration changes and can cause updates or destruction.

How to eliminate wrong answers

Option B is wrong because `terraform state rm` followed by `terraform import` is unnecessarily destructive and complex; it removes the resource from state entirely, which could cause Terraform to plan a destroy on the next apply if the configuration still references it, and re-importing requires knowing the exact resource ID. Option C is wrong because manually editing the state file is error-prone, unsupported, and violates Terraform's principle of using the CLI to manage state; it can lead to corruption or inconsistencies. Option D is wrong because `terraform apply -target=aws_instance.web` would attempt to apply the configuration to that resource, which would likely trigger an update or destroy/recreate action based on the configuration, not just refresh the state; it does not reconcile drift without changes.

13
Multi-Selectmedium

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

Select 2 answers
A.Create infrastructure manually via cloud console
B.Write Terraform configuration files
C.Review the execution plan
D.Commit changes to version control
E.Run unit tests on the configuration
AnswersB, C

Correct! Writing config is the first step.

Why this answer

The core workflow consists of: Write (author config), Plan (review changes), Apply (execute). Options that match are 'Write configuration' and 'Review execution plan'.

14
Multi-Selecthard

A team is adopting Terraform for infrastructure deployment. They want to ensure that the core workflow (write, plan, apply) is followed effectively. Which two practices should they adopt? (Choose two.)

Select 2 answers
A.Store Terraform configurations in a version control system like Git.
B.Require manual confirmation for every terraform plan execution.
C.Store state files locally on the engineer's machine.
D.Always run terraform apply directly without terraform plan to save time.
E.Use a remote backend with state locking enabled.
AnswersA, E

Version control allows tracking changes, collaboration, and rollback.

Why this answer

Option A is correct because storing Terraform configurations in a version control system like Git ensures that the 'write' phase is collaborative, auditable, and repeatable. It enables teams to track changes, roll back to previous versions, and enforce code review before applying infrastructure changes, which is a core DevOps practice for the Terraform workflow.

Exam trap

HashiCorp often tests the misconception that local state storage is acceptable for teams, but the exam expects candidates to recognize that remote backends with locking are mandatory for collaborative workflows to prevent state conflicts and enable team-based infrastructure management.

15
Multi-Selecthard

Which THREE of the following are valid flags for the terraform apply command? (Choose three.)

Select 3 answers
A.-lock-timeout
B.-target
C.-var-file
D.-auto-approve
E.-refresh=false
AnswersB, C, D

Limits apply to specific resource addresses.

Why this answer

The `-target` flag is valid for `terraform apply` because it allows you to target specific resources or modules for application, which is useful for incremental deployments or debugging. This flag accepts a resource address pattern and limits the apply operation to only those resources and their dependencies, as defined in the Terraform execution plan.

Exam trap

HashiCorp often tests the distinction between flags that are valid for `terraform plan` versus `terraform apply`, and candidates may incorrectly assume that flags like `-refresh=false` or `-lock-timeout` are exclusive to one command when they actually work for both.

16
Multi-Selecthard

Which THREE of the following are valid reasons to use 'terraform refresh'? (Choose three.)

Select 3 answers
A.To update the state file when resources were deleted outside of Terraform.
B.To detect drift between the state file and actual infrastructure.
C.To import existing infrastructure into Terraform management.
D.To update the state file after making manual changes to resources.
E.To update the Terraform configuration with current resource settings.
AnswersA, B, D

Refresh will mark deleted resources as removed from state.

Why this answer

Option A is correct because `terraform refresh` updates the state file to reflect the current real-world infrastructure, including resources that were deleted outside of Terraform. This ensures the state file accurately represents the actual infrastructure, preventing drift and allowing Terraform to plan correctly.

Exam trap

HashiCorp often tests the distinction between `terraform refresh` (state update only) and `terraform import` (adding new resources to state), as well as the misconception that `terraform refresh` modifies configuration files.

17
MCQeasy

A user runs 'terraform plan' and the output includes a change that adds a new resource. However, the user expected the change to modify an existing resource. What is the most likely cause?

A.The provider version was updated.
B.A required attribute was added to the resource block.
C.The state file was manually deleted.
D.The resource name or type was changed in the configuration.
AnswerD

Changing the resource name or type makes Terraform treat it as a new resource.

Why this answer

When a resource's name or type is changed in the configuration, Terraform interprets it as a request to destroy the old resource and create a new one, because Terraform maps each resource block to a state entry using its resource type and name (e.g., `aws_instance.web`). The plan output will show a `+` (create) for the new resource and a `-` (destroy) for the old one, rather than a `~` (update in-place). This matches the user's observation of a new resource being added instead of the expected modification.

Exam trap

HashiCorp often tests the misconception that Terraform identifies resources by their configuration block content (e.g., tags or names) rather than by the resource type and name in the block header, leading candidates to incorrectly attribute the behavior to provider updates or attribute changes.

How to eliminate wrong answers

Option A is wrong because updating a provider version may change default values or introduce new attributes, but it does not cause Terraform to treat an existing resource as a new resource; it would typically trigger in-place updates or require re-creation only if schema changes are incompatible. Option B is wrong because adding a required attribute to a resource block that already exists in state would cause a plan error (missing required argument) or force re-creation if the attribute cannot be updated in-place, but it would not silently add a new resource while leaving the old one unchanged. Option C is wrong because manually deleting the state file would cause Terraform to see no existing resources at all, so it would plan to create all resources from scratch, not just one new resource; the user would see many `+` entries, not a single addition.

18
MCQhard

A DevOps engineer is troubleshooting a failed 'terraform apply'. The error message says: 'Error: Error applying IAM policy: The policy failed validation'. The IAM policy is defined using HCL in a JSON-encoded string. What is the most efficient way to debug this issue?

A.Run 'terraform plan' to see the detailed error.
B.Use 'terraform console' to test the policy string.
C.Use a JSON validator tool to check the policy string in the configuration.
D.Upgrade to the latest Terraform version.
AnswerC

Validating the JSON string locally identifies syntax issues before running apply.

Why this answer

Option C is correct because the error 'The policy failed validation' indicates that the JSON-encoded IAM policy string in the Terraform configuration is malformed or violates AWS IAM policy syntax. Using a JSON validator tool (e.g., `jq`, online validator, or `aws iam simulate-custom-policy`) directly checks the string's structure and compliance with AWS IAM policy schema, which is the most efficient first step before re-running Terraform. This isolates the issue from Terraform's execution logic and avoids unnecessary plan/apply cycles.

Exam trap

HashiCorp often tests the misconception that `terraform plan` catches all errors, but plan only validates Terraform configuration syntax and state drift, not the semantic correctness of embedded JSON strings that are passed to external APIs.

How to eliminate wrong answers

Option A is wrong because `terraform plan` does not validate the syntax of a JSON-encoded IAM policy string; it only compares the desired state with the current state and would not catch validation errors that occur during apply. Option B is wrong because `terraform console` is used to evaluate expressions and test interpolation, not to validate JSON policy strings or AWS IAM policy syntax. Option D is wrong because upgrading Terraform version does not fix a malformed JSON policy string; the error is a content validation issue, not a software bug.

19
MCQhard

An organization uses Terraform workspaces to manage multiple environments (dev, staging, prod). They notice that terraform plan in the prod workspace unexpectedly shows changes to a resource that should be identical across workspaces. The resource uses a backend that stores state in an S3 bucket. What is the most likely cause?

A.The prod workspace was created by copying the dev workspace state.
B.The S3 bucket does not support versioning.
C.The terraform.workspace variable is used in the resource configuration.
D.The provider version differs between workspaces.
AnswerC

Using terraform.workspace in resource arguments will cause different plans per workspace.

Why this answer

Option D is correct because if the resource configuration references the terraform.workspace variable (e.g., for naming), the plan will differ per workspace. Option A is wrong because S3 versioning affects state file recovery, not plan differences. Option B is plausible but less likely because copying state would cause identical state initially.

Option C is wrong if the provider version is consistent across workspaces.

20
Matchingmedium

Match each Terraform workflow stage to its description.

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

Concepts
Matches

Author infrastructure as code configuration

Preview changes before applying

Execute the planned changes

Tear down managed infrastructure

Restructure configuration without changing external resources

Why these pairings

These stages represent the core Terraform workflow.

21
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 can cause timeouts if the instance is not accessible after creation.

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.

22
Drag & Dropmedium

Drag and drop the steps to import existing infrastructure into Terraform state in the correct order.

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

Steps
Order

Why this order

Import adds existing resources to state; plan shows drift between config and real world.

23
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 saves the plan and allows detailed inspection of proposed changes.

Why this answer

Option D is correct because `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.

24
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

Init initializes the directory and downloads providers.

Why this answer

Option B, `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.

25
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

Remote backends like S3 with versioning keep a history of state changes.

Why this answer

Option D is correct because 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.

26
MCQmedium

A team is running terraform in a CI/CD pipeline that executes multiple jobs in parallel for different modules. They notice that terraform init takes a long time in each job because it downloads provider plugins repeatedly. They want to speed up the init process by caching providers. What should they do?

A.Use the plugin_cache_dir setting in the CLI configuration file.
B.Set the environment variable TF_PLUGIN_CACHE_DIR to a shared path.
C.Copy the .terraform folder from a previous job.
D.Use terraform providers lock to freeze versions.
AnswerA

This caches downloaded plugins across runs, speeding up init.

Why this answer

Option A is correct because the `plugin_cache_dir` setting in the Terraform CLI configuration file instructs Terraform to store downloaded provider plugins in a shared cache directory. Once a plugin is cached, subsequent `terraform init` commands in parallel jobs can reuse the cached plugin instead of downloading it again, significantly reducing init time. This setting is defined in the `.terraformrc` or `terraform.rc` file and is the recommended approach for CI/CD pipelines.

Exam trap

HashiCorp often tests the distinction between CLI configuration file settings and environment variables, so the trap here is that candidates confuse the deprecated `TF_PLUGIN_CACHE_DIR` environment variable with the correct `plugin_cache_dir` CLI configuration setting, or they assume environment variables override the config file when they do not.

How to eliminate wrong answers

Option B is wrong because the environment variable `TF_PLUGIN_CACHE_DIR` is not a valid Terraform environment variable; Terraform uses `TF_PLUGIN_CACHE_DIR` only in older versions (0.12 and earlier) and it is deprecated. The correct environment variable is `TF_PLUGIN_CACHE_DIR` is not recognized; instead, the CLI configuration file setting `plugin_cache_dir` is the proper method. Option C is wrong because copying the `.terraform` folder from a previous job is unreliable and can cause state conflicts, as the `.terraform` folder contains lock files and provider metadata that may not be compatible across different module jobs or Terraform versions.

Option D is wrong because `terraform providers lock` is used to generate a lock file (`.terraform.lock.hcl`) to freeze provider versions for consistency, not to cache provider plugins; it does not speed up downloads.

27
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 detects drift and reverts changes not in the configuration.

Why this answer

Option A is correct because 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.

28
Multi-Selectmedium

Which three of the following are required steps in the core Terraform workflow for managing infrastructure? (Choose three.)

Select 3 answers
.Write Terraform configuration files that define the desired state of resources.
.Run terraform init to initialize the working directory and download provider plugins.
.Run terraform plan to review the execution plan before applying changes.
.Run terraform destroy to remove all managed resources after every apply.
.Run terraform fmt to automatically fix formatting issues in configuration files.
.Run terraform validate to check configuration syntax before initializing the backend.

Why this answer

The core Terraform workflow consists of three essential steps: writing configuration files to define the desired state, running `terraform init` to initialize the working directory and download provider plugins, and running `terraform plan` to review the execution plan before applying changes. These steps form the fundamental 'write, plan, apply' cycle that Terraform uses to manage infrastructure declaratively. Without these, you cannot safely or correctly provision resources.

Exam trap

HashiCorp often tests the distinction between mandatory workflow steps and optional auxiliary commands, so the trap here is that candidates confuse helpful but non-essential commands like `terraform fmt` or `terraform validate` with the core required steps of write, init, and plan.

29
MCQhard

A developer is troubleshooting a Terraform configuration that fails during `terraform plan` with the error: "Error: Invalid reference". The error points to a line that references `var.environment` in a module block. What is the most likely cause?

A.The Terraform version does not support module variables
B.The variable `var.environment` is not defined in the root module's variables.tf
C.The variable `environment` is not defined in the child module's variables.tf
D.The module source path is invalid
AnswerC

Correct! When referencing `var.environment` inside a module block, that variable must be declared in the child module.

Why this answer

Option C is correct because when a Terraform module block references a variable like `var.environment`, that variable must be defined in the child module's `variables.tf` file. The error 'Invalid reference' indicates Terraform cannot resolve the variable within the module's scope, meaning the child module does not declare an input variable named `environment`. Without this declaration, the module cannot accept the value passed from the root module.

Exam trap

HashiCorp often tests the distinction between root module variables and child module input variables, trapping candidates who assume `var.environment` must be defined in the root module's `variables.tf` rather than in the child module's `variables.tf`.

How to eliminate wrong answers

Option A is wrong because Terraform has supported module variables since version 0.10, and the error is not related to version compatibility. Option B is wrong because `var.environment` in a module block refers to a variable passed to the child module, not a root module variable; the root module's `variables.tf` is irrelevant here. Option D is wrong because an invalid module source path would produce a different error, such as 'Error: Failed to download module' or 'Error: Unreadable module directory', not an 'Invalid reference' error.

30
MCQmedium

During a terraform apply, the process crashes mid-way. The state file may be in an inconsistent state. What is the first recommended step to recover?

A.Run terraform force-unlock.
B.Run terraform apply with -auto-approve.
C.Run terraform plan.
D.Run terraform destroy.
AnswerC

terraform plan shows the current state and what changes would be made, helping to assess the situation.

Why this answer

Option C is correct because running terraform plan will show the current state and the pending changes, allowing you to diagnose the situation. Option A is wrong because re-running apply may fail again or cause further issues. Option B is wrong because terraform destroy would remove all resources, not just the half-created ones.

Option D is wrong because force-unlock is only for lock issues, not state inconsistency.

31
MCQmedium

During 'terraform apply', a user receives an error: 'Error: Error creating resource: Resource already exists'. The resource does not appear in the Terraform state. What is the most likely cause?

A.The state file was migrated from a different backend and the resource is duplicated.
B.The resource was removed from the configuration but not from state.
C.The user forgot to run terraform refresh before apply.
D.The resource was manually created outside of Terraform before the apply.
AnswerD

If the resource already exists in the cloud provider but not in state, Terraform will try to create it and fail.

Why this answer

Option D is correct because the error 'Resource already exists' indicates that the resource was created outside of Terraform's management (e.g., manually via the cloud console or CLI). Since the resource does not appear in the Terraform state, Terraform attempts to create it during 'terraform apply', but the underlying API rejects the request because the resource already exists in the cloud provider. This is a common state drift scenario where the real-world infrastructure is out of sync with the Terraform state.

Exam trap

HashiCorp often tests the misconception that 'terraform refresh' can fix state drift issues like this, but refresh only updates existing state attributes—it does not import unmanaged resources into the state, so the apply will still fail.

How to eliminate wrong answers

Option A is wrong because migrating a state file from a different backend would not cause a 'Resource already exists' error during apply; it would either succeed or fail with state-related conflicts, not an API-level duplicate resource error. Option B is wrong because if a resource was removed from configuration but not from state, 'terraform apply' would not attempt to create it—it would simply leave the resource in state and unmanaged, not trigger a creation error. Option C is wrong because 'terraform refresh' updates the state file to match real-world resources, but it does not prevent the 'Resource already exists' error; the error occurs because Terraform tries to create a resource that already exists, and refresh alone does not import that resource into state.

32
MCQhard

A company uses Terraform Cloud and wants to enforce policies that prevent creating resources with public IP addresses unless explicitly approved. What Terraform Cloud feature should they use?

A.Sentinel policies
B.VCS integration
C.Workspaces
D.Run tasks
AnswerA

Sentinel is a policy-as-code framework that can enforce rules before apply.

Why this answer

Option C is correct because Sentinel is the policy-as-code framework in Terraform Cloud. Option A is wrong because workspaces are for state isolation, not policy. Option B is wrong because VCS integration is for triggering runs.

Option D is wrong because run tasks allow custom validation but Sentinel is the built-in policy engine.

33
MCQhard

An organization uses Terraform with a remote backend in Azure. After a network outage, a developer attempts to run `terraform apply` and receives the error: "Error: Failed to get existing workspaces: blob (key) not found". What is the most likely cause?

A.The Terraform backend configuration has incorrect access key
B.The Azure storage account was deleted
C.The state file for the current workspace was deleted or corrupted
D.The workspace was not created via `terraform workspace new`
AnswerC

Correct! The blob key for the workspace's state is missing, so Terraform cannot find the state.

Why this answer

Option C is correct because the error 'blob (key) not found' indicates that Terraform cannot locate the state file for the current workspace in the Azure storage container. After a network outage, the state file may have been deleted or corrupted, preventing Terraform from reading the existing state. This error is specific to the missing blob key, not to authentication or storage account availability.

Exam trap

HashiCorp often tests the distinction between authentication/authorization errors and resource-not-found errors; the trap here is that candidates may confuse a missing state file with a misconfigured backend or deleted storage account, but the specific 'blob (key) not found' message points directly to the state file blob being absent.

How to eliminate wrong answers

Option A is wrong because an incorrect access key would produce an authentication error (e.g., 'Failed to obtain existing workspaces: storage: service returned error: StatusCode=403'), not a 'blob not found' error. Option B is wrong because if the storage account were deleted, the error would indicate that the container or account does not exist (e.g., 'The specified storage account was not found'), not that a specific blob key is missing. Option D is wrong because workspaces are created via `terraform workspace new` only when using multiple workspaces; the default workspace exists without explicit creation, and the error is about the state file itself, not workspace existence.

34
MCQeasy

What is the most likely cause of this error?

A.The AWS credentials used do not have permission to launch EC2 instances.
B.The Terraform configuration has a syntax error.
C.The instance type 't2.micro' is not available in the region.
D.The AMI ID is invalid or does not exist in the region.
AnswerA

UnauthorizedOperation error indicates lack of permissions.

Why this answer

The error is most likely caused by insufficient AWS permissions because Terraform uses the configured AWS credentials to make API calls. If the IAM user or role lacks the `ec2:RunInstances` permission, the API will return an authorization error, even if the configuration is syntactically correct and the AMI/instance type are valid.

Exam trap

HashiCorp often tests the distinction between API authorization errors (HTTP 403) and resource validation errors (HTTP 400), leading candidates to confuse permission issues with configuration mistakes like invalid AMIs or unavailable instance types.

How to eliminate wrong answers

Option B is wrong because a syntax error in Terraform configuration would be caught during `terraform validate` or `terraform plan` with a specific parser error message, not an AWS API authorization error. Option C is wrong because if 't2.micro' were unavailable in the region, the error would indicate an 'Unsupported' or 'InsufficientInstanceCapacity' message, not a permissions failure. Option D is wrong because an invalid or missing AMI ID would return an 'InvalidAMIID.NotFound' or 'InvalidAMIID.Malformed' error from the EC2 API, not an authorization error.

35
MCQeasy

What is the primary purpose of 'terraform init'?

A.To format the Terraform configuration files.
B.To apply changes to the infrastructure.
C.To preview infrastructure changes before applying them.
D.To initialize the working directory, download providers, and set up the backend.
AnswerD

Init prepares the directory for other commands.

Why this answer

The 'terraform init' command is the first step in the core Terraform workflow. Its primary purpose is to initialize the working directory containing Terraform configuration files, download and install the required provider plugins (e.g., AWS, Azure, GCP), and configure the backend (e.g., local, S3, Terraform Cloud) for state storage. Without running 'terraform init', subsequent commands like 'terraform plan' or 'terraform apply' will fail because the providers and backend are not set up.

Exam trap

HashiCorp often tests the distinction between the initialization phase and the planning/execution phases, so the trap here is that candidates confuse 'terraform init' with 'terraform plan' or 'terraform apply' because they all appear early in the workflow, but only 'init' handles provider and backend setup.

How to eliminate wrong answers

Option A is wrong because 'terraform fmt' is the command used to format Terraform configuration files, not 'terraform init'. Option B is wrong because 'terraform apply' is the command that applies changes to the infrastructure, not 'terraform init'. Option C is wrong because 'terraform plan' is the command used to preview infrastructure changes before applying them, not 'terraform init'.

36
MCQhard

A company uses Terraform workspaces to manage environments. They have a monorepo with separate configurations for each environment. They want to introduce a new team that will manage only the staging environment. The new team will run terraform commands only on the staging workspace. They are using a single S3 backend for all workspaces. The team is concerned about accidentally applying changes to other workspaces. What is the best way to restrict the team's access?

A.Create a separate S3 bucket for staging and configure a different backend.
B.Use Terraform Cloud with team-based permissions.
C.Use terraform workspace select staging in the CI/CD pipeline and only allow that.
D.Use IAM policies to restrict access to the state files of other workspaces.
AnswerB

Terraform Cloud allows workspace-level permissions, making it easy to restrict access to specific workspaces.

Why this answer

Option B is correct because Terraform Cloud provides native workspace-level permissions, allowing you to grant the new team access only to the staging workspace while preventing them from applying changes to other workspaces. This is the most secure and manageable approach, as it leverages Terraform Cloud's RBAC (Role-Based Access Control) to enforce separation of duties without modifying the backend configuration or relying on error-prone manual processes.

Exam trap

The trap here is that candidates often confuse IAM-based state file access control with workspace-level command restrictions, not realizing that Terraform commands are executed client-side and IAM cannot prevent a user from running `terraform apply` on a different workspace if they have the state file path and credentials.

How to eliminate wrong answers

Option A is wrong because creating a separate S3 bucket for staging would require changing the backend configuration for the staging environment, which breaks the single-backend design and adds operational complexity; it also does not prevent the team from accidentally using the wrong backend configuration. Option C is wrong because relying on `terraform workspace select staging` in the CI/CD pipeline is a procedural control that can be bypassed if the team runs commands locally or if the pipeline is misconfigured; it does not enforce access restrictions at the infrastructure level. Option D is wrong because IAM policies can restrict access to S3 objects (state files) but cannot prevent the team from running `terraform apply` against other workspaces if they have access to the state file; Terraform commands are executed locally or in CI/CD, and IAM does not control which workspace is selected.

37
Multi-Selecthard

Which THREE are valid methods to manage Terraform state files? (Choose three.)

Select 3 answers
A.terraform state push
B.Local state file
C.Terraform Cloud state storage
D.terraform state mv
E.Remote backends (e.g., S3, AzureRM, GCS)
AnswersB, C, E

Store state locally in terraform.tfstate.

Why this answer

Option B is correct because Terraform can manage state using a local file (terraform.tfstate) stored on the machine where Terraform is run. This is the default behavior and is valid for single-user or test scenarios, though it lacks locking and remote collaboration features.

Exam trap

HashiCorp often tests the distinction between state management methods (storage backends) and state manipulation commands (like push, mv, rm), causing candidates to confuse operational commands with valid storage approaches.

38
MCQhard

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

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

Correct! If the resource exists in state and configuration matches, no changes are needed.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

39
MCQeasy

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

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

terraform show outputs the plan in human-readable form, including the reason for each change.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

40
Multi-Selecthard

Which THREE are valid uses of the `terraform state` command? (Select THREE.)

Select 3 answers
A.Force unlock the state lock
B.Move a resource from one state file to another
C.Remove a resource from state without destroying it
D.List all resources tracked in the state
E.Import an existing resource into state
AnswersB, C, D

Correct! `terraform state mv` moves resources between states.

Why this answer

Option B is correct because `terraform state mv` allows you to move a resource from one state file to another, which is useful for refactoring configurations or splitting state files. This command updates the resource's address in the target state while preserving its tracked attributes and lifecycle.

Exam trap

HashiCorp often tests the distinction between the `terraform state` subcommands and other standalone commands like `terraform import` and `terraform force-unlock`, expecting candidates to know that only `list`, `mv`, and `rm` are valid `terraform state` operations.

41
Multi-Selectmedium

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

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

Why this answer

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

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

Exam trap

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

42
MCQmedium

During a 'terraform plan', you see the following output: 'Plan: 1 to add, 2 to change, 0 to destroy.' However, after running 'terraform apply', the actual number of resources changed is different. What is the most likely reason?

A.Terraform state locking prevented the apply from executing correctly.
B.The state file was corrupted during the apply.
C.The configuration was modified after the plan was generated.
D.The 'terraform apply' command includes an implicit refresh that changes the plan.
AnswerC

If the configuration changes between plan and apply, the apply uses the new config, so the plan is outdated.

Why this answer

The plan is based on the state and configuration at the time of planning. If someone else applies changes concurrently or if the configuration changes between plan and apply, the plan becomes stale. Option A is wrong because refreshing state doesn't change the plan.

Option C is wrong because 'terraform apply' does not modify configuration. Option D is wrong because locking prevents concurrent applies but doesn't cause discrepancy if the plan is still valid.

43
MCQmedium

An engineer accidentally destroys a critical resource by running `terraform apply` after an incorrect `terraform plan`. They want to recover the resource quickly. What should they do?

A.Modify the configuration to match the destroyed resource and run `terraform import`
B.Use `terraform force-unlock` to unlock the state and then run `terraform plan`
C.Restore the previous version of the configuration and run `terraform apply` again
D.Run `terraform state rm` to remove the destroyed resource from state and then re-import it
AnswerC

Correct! Applying the previous config will recreate the resource as long as state still has the resource.

Why this answer

If the resource was destroyed, Terraform's state still knows about it (unless state was also deleted). The best recovery is to revert the configuration to the previous version and run `terraform apply`. If state is intact, Terraform will recreate the resource.

44
MCQeasy

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

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

Plan only detects changes in the current directory's .tf files.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

45
Multi-Selectmedium

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

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

Plan is the second step in the core workflow.

Why this answer

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

Exam trap

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

46
MCQeasy

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

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

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

Why this answer

By default, `terraform init` downloads provider plugins into a `.terraform` subdirectory of the current working directory. This is the standard location for the Terraform working directory's local cache.

47
MCQmedium

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

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

Correct! Terraform will refresh state, determine what's already created, and apply only remaining changes.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

48
MCQmedium

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

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

With count=0, the resource is not created, so no change.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

49
MCQmedium

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

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

Correct! The "default" workspace is always present and cannot be deleted.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

50
MCQmedium

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

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

Correct! The conditional check fails because the lock item's version does not match, meaning it's locked.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

51
Multi-Selectmedium

Which TWO scenarios could cause 'terraform plan' to show 'No changes' even though the configuration file was recently modified? (Choose two.)

Select 2 answers
A.The user ran 'terraform plan' from a different directory that does not contain the modified configuration.
B.A lifecycle block with ignore_changes was applied to the modified attribute.
C.The resource was manually updated in the cloud provider console.
D.A new resource block was added.
E.The provider version was changed in the required_providers block.
AnswersA, B

Plan only reads .tf files from the current directory.

Why this answer

Option A is correct because `terraform plan` operates on the configuration files in the current working directory. If the user runs the command from a different directory that does not contain the modified configuration, Terraform will compare the state against the unmodified files in that directory, resulting in 'No changes'. Option B is correct because a `lifecycle` block with `ignore_changes` tells Terraform to disregard changes to specified attributes when planning, so even if the configuration file modifies that attribute, Terraform will not detect a diff and will report 'No changes'.

Exam trap

HashiCorp often tests the misconception that manual cloud console changes always cause plan output to show changes, but the trap here is that `ignore_changes` can suppress those diffs, and running `terraform plan` from the wrong directory can cause the command to read unmodified files, both leading to a false 'No changes' result.

52
MCQeasy

When running `terraform plan`, an engineer sees that Terraform proposes to destroy an existing resource even though the configuration file appears unchanged. What is the most likely cause?

A.The resource's `count` or `for_each` meta-argument was removed from the configuration
B.Another user ran `terraform destroy` without the engineer's knowledge
C.The state file was corrupted and lost the resource
D.The resource was manually deleted from the cloud provider console
AnswerA

Correct! Removing the count or for_each reduces the number of instances, leading to planned destruction.

Why this answer

Option A is correct because removing the `count` or `for_each` meta-argument from a resource block causes Terraform to interpret the resource as no longer being managed by the configuration. Since Terraform tracks resources by their logical address in the state, the absence of the meta-argument means the existing resource (previously indexed, e.g., `resource.name[0]`) no longer matches any configuration block, so Terraform plans to destroy it. This is a common source of unexpected destruction when the resource count is reduced or the loop construct is removed entirely.

Exam trap

HashiCorp often tests the misconception that state corruption or manual deletion causes destruction plans, but the trap here is that candidates overlook how removing `count` or `for_each` changes the resource address, leading to an unexpected destroy without any change to the resource's own attributes.

How to eliminate wrong answers

Option B is wrong because if another user ran `terraform destroy`, the resource would already be removed from the state and infrastructure, so Terraform would not propose to destroy it again; instead, it would show a creation plan if the configuration still exists. Option C is wrong because a corrupted state file would typically cause Terraform to fail with an error or show all resources as new additions, not specifically target a single existing resource for destruction. Option D is wrong because if a resource is manually deleted from the cloud provider console, Terraform would detect the drift and plan to recreate it, not destroy it again.

53
MCQhard

A team is using Terraform with multiple environments (dev, staging, prod) and wants to use separate state files. They are considering workspaces. A senior engineer suggests using separate directory structures instead of workspaces for prod. What is the strongest reason for this recommendation?

A.Workspaces share the same backend configuration, increasing the risk of accidental changes to production.
B.Workspaces cannot isolate state files.
C.Workspaces make it harder to refactor configurations.
D.Workspaces do not support state locking.
AnswerA

With workspaces, all states are in the same backend; misconfiguration could target prod from dev workspace.

Why this answer

Workspaces share the same backend configuration, meaning all workspaces (including prod) use the same state storage location and access controls. This increases the risk of accidental changes to production because a single backend misconfiguration or a mistaken workspace switch can lead to unintended modifications to the production state file. Separate directory structures allow for independent backend configurations, enabling stricter access controls and isolation for production.

Exam trap

HashiCorp often tests the misconception that workspaces provide full isolation, when in fact they only isolate state file keys, not the backend configuration or access controls, making separate directories safer for production environments.

How to eliminate wrong answers

Option B is wrong because workspaces do isolate state files by storing them under the same backend with a workspace-specific key, but they do not isolate the backend configuration itself. Option C is wrong because workspaces do not inherently make refactoring harder; in fact, they can simplify configuration reuse across environments. Option D is wrong because workspaces fully support state locking via the backend (e.g., DynamoDB for S3), just like separate directories.

Ready to test yourself?

Try a timed practice session using only Use the core Terraform workflow questions.