Courseiva

CCNA Use the core Terraform workflow Questions

39 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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

3
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

4
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

5
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

6
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

7
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

8
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

When a Terraform operation fails midway, it can leave a state lock in place, preventing subsequent operations. The `terraform force-unlock` command is specifically designed to manually release such a "stuck" lock. It requires the lock ID, which can typically be found in the error message of the failed operation or by inspecting the backend. While effective, it must be used with extreme caution to avoid concurrent state modifications and potential corruption, ensuring no other operations are genuinely running.

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.

9
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

When infrastructure resources have been modified outside of Terraform (a condition known as drift), `terraform apply -refresh-only` is the precise command to update Terraform's state file to reflect these real-world changes. This operation queries the cloud provider for the current attributes of all managed resources and updates the state file accordingly, without making any alterations to the actual infrastructure. It effectively synchronizes Terraform's understanding with reality, acknowledging external modifications and preventing Terraform from attempting to revert them in subsequent `apply` operations.

Why this answer

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

10
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

Writing Terraform configuration files, typically in HashiCorp Configuration Language (HCL), is the initial and foundational step in the core workflow. These files declaratively define the desired state of infrastructure resources, specifying providers, resources, data sources, variables, and outputs. This configuration serves as the single source of truth for Terraform to understand what infrastructure to manage.

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

11
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

terraform refresh reads the current state of real infrastructure and updates the Terraform state file to reflect any changes, including the absence of resources that were previously tracked but have since been deleted manually. This process ensures the state file accurately represents the infrastructure, marking deleted resources as "not found" and preparing them for removal from the state.

Why this answer

The `terraform refresh` command updates the state file to match real-world infrastructure. Option A is correct because if resources were deleted outside Terraform, refresh removes them from state. Option B is correct because refresh detects drift by comparing state with actual infrastructure.

Option D is correct because manual changes to resources are recorded in state after refresh. Option C is incorrect because importing infrastructure requires `terraform import`, not refresh. Option E is incorrect because refresh updates the state file, not the Terraform configuration.

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.

12
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

Terraform identifies resources by their unique address, which is composed of their type and local name (e.g., `aws_instance.web`). If either the resource type (e.g., changing `aws_instance` to `aws_ami`) or the local name (e.g., changing `web` to `app`) is altered in the configuration, Terraform considers this a completely different resource from what is recorded in the state file. It will then plan to destroy the old resource (if it exists in state) and create a brand new one with the updated address, resulting in a `(- destroy, + create)` action for that specific 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.

13
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

A JSON validator tool is highly effective for identifying fundamental syntax errors within an IAM policy string embedded in Terraform configuration. These tools can quickly pinpoint issues like malformed JSON structure, incorrect escaping, missing commas, or unclosed brackets, which are common causes of policy validation failures. Catching these errors locally prevents terraform apply from failing due to basic JSON parsing issues, allowing the DevOps engineer to correct the policy before deployment attempts.

Why this answer

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.

14
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

The `terraform.workspace` variable provides the name of the currently selected workspace, allowing for dynamic configuration based on the execution context. By incorporating this variable into resource arguments, such as `name = "my-resource-${terraform.workspace}"` or conditional logic using `count` or `for_each`, the same configuration can provision distinct resources or resource attributes across different workspaces. This direct manipulation of resource definitions based on the workspace name is the most common and intended mechanism for generating varying `terraform plan` outputs from a single set of configuration files.

Why this answer

If the `terraform.workspace` variable is used directly in a resource configuration (e.g., in a name, tag, or identifier), the resource definition will differ between workspaces. Since the prod workspace has a different workspace name than dev, the plan will show changes to resources that are otherwise identical, as Terraform detects the difference in the interpolated value.

Exam trap

A common misconception in Terraform is that workspace differences are solely due to state management issues (like copying state or versioning) rather than configuration logic. The trap here is assuming that identical resource definitions across workspaces are automatically enforced without checking for workspace-aware variables like 'terraform.workspace' in the configuration.

How to eliminate wrong answers

Option A is wrong because copying state from dev to prod would not cause unexpected plan changes for resources that should be identical; it would simply replicate the same state, and any differences would stem from configuration, not state copying. Option B is wrong because S3 bucket versioning affects state file history and rollback capabilities, not the content of the plan or the detection of configuration differences across workspaces. Option D is wrong because provider versions are defined in the Terraform configuration (e.g., required_providers block) and are consistent across all workspaces in the same directory; differing provider versions would require separate configurations or manual overrides, not workspace isolation.

15
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

16
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

17
Multi-Selecteasy

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

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

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

Why this answer

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

Exam trap

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

18
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

19
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

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

21
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

When a child module receives input values, it must explicitly declare those inputs as variables within its own scope, typically in a `variables.tf` file inside the module's directory. If the root module attempts to pass a value like `environment = var.environment` to a child module, the child module must have a corresponding `variable "environment" {}` block defined to accept that input. Without this declaration, the child module will report an error indicating an undefined variable when it tries to use `var.environment` internally, as it does not recognize `environment` as a valid input.

Why this answer

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.

22
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

Running terraform plan is the most appropriate first step after a terraform apply crash. This command safely reads the current Terraform state, compares it against the desired configuration, and then queries the actual remote infrastructure to detect any drift or incomplete changes. The resulting detailed execution plan provides crucial visibility into the current perceived state of resources and precisely what Terraform intends to do, allowing the operator to assess the situation, identify inconsistencies, and formulate a recovery strategy without making any further modifications.

Why this answer

Terraform plan will show the current state and pending changes, allowing you to diagnose the situation. Option A is wrong because force-unlock is only for lock issues, not state inconsistency. Option B is wrong because re-running apply may fail again or cause further issues.

Option D is wrong because terraform destroy would remove all resources, not just the half-created ones.

23
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

When Terraform executes `terraform apply`, it compares the desired state defined in the configuration with the known state recorded in its state file. If a resource is defined in the configuration but is entirely absent from the state file, Terraform assumes this resource needs to be provisioned. If an identical resource, perhaps with the same unique name or identifier, was previously created directly within the cloud provider environment, the cloud API will reject Terraform's creation request, resulting in an 'already exists' error.

Why this answer

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.

24
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 HashiCorp's policy-as-code framework, deeply integrated with Terraform Cloud to enforce governance rules. It allows organizations to define granular policies that evaluate Terraform plans and states, preventing non-compliant infrastructure changes before they are applied. Policies can enforce various rules, such as mandatory tagging, allowed AWS regions, or resource size limits, ensuring compliance and security.

Why this answer

Sentinel is HashiCorp's policy-as-code framework that integrates directly with Terraform Cloud. It allows you to define fine-grained, logic-based policies (e.g., 'deny resources with public IPs unless a specific approval tag is present') that are enforced during the plan phase before any resources are created. This is the correct feature for enforcing custom governance rules on infrastructure provisioning.

Exam trap

A common mistake in Terraform Cloud is confusing Sentinel policies with run tasks. Run tasks are for integrating external tools (like security scanners), not for enforcing custom governance rules. Sentinel is the built-in policy-as-code engine.

How to eliminate wrong answers

Option B (VCS integration) is wrong because it only connects a version control repository to Terraform Cloud for triggering runs; it does not evaluate or enforce policies on resource configurations. Option C (Workspaces) is wrong because workspaces are logical containers for managing state and variables, not a mechanism for policy enforcement or approval workflows. Option D (Run tasks) is wrong because run tasks are used to integrate third-party tools (e.g., security scanners) into the run lifecycle, not to define native policy rules like Sentinel does.

25
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

When Terraform reports a "blob not found" error in an Azure backend, it specifically means that the expected state file object, identified by its unique blob path (which includes the workspace name), does not exist within the configured storage container. This directly indicates that the state file for the currently selected Terraform workspace has either been inadvertently deleted from the Azure Blob Storage or has become corrupted in a way that makes it unretrievable by its expected key. Terraform successfully connected to the storage account and container but failed to locate the specific state object.

Why this answer

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.

26
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

This option correctly describes the primary purpose of `terraform init`. It performs essential bootstrapping tasks, including discovering and downloading the necessary provider plugins specified in the configuration, which enable Terraform to interact with various cloud services. Furthermore, `terraform init` configures the backend, determining where Terraform stores its state file, which is crucial for tracking infrastructure changes and enabling collaboration. These steps collectively prepare the local working directory for subsequent Terraform operations like `plan` and `apply`.

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

27
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 provides robust Role-Based Access Control (RBAC) capabilities, enabling granular permissions to be set at the workspace level. This allows administrators to define specific teams or users who can interact with, modify, or even view particular workspaces, such as a "staging" workspace. By enforcing these permissions, Terraform Cloud effectively prevents team members from accidentally or intentionally targeting production or other sensitive environments, as their access would be explicitly denied by the platform.

Why this answer

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.

28
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

The `terraform apply` command reporting "No changes. Your infrastructure matches the configuration." indicates that all resources defined in the Terraform configuration files are already present in the Terraform state file, and their current attributes align perfectly with the desired state. This means the `random_pet` resource was successfully created during a previous `terraform apply` operation and its existence and configuration are accurately tracked within the state, requiring no further action.

Why this answer

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.

29
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

After running `terraform plan -out=tfplan`, executing `terraform show tfplan` is the definitive method to inspect the proposed changes in detail. This command renders the plan file in a human-readable format, explicitly listing each resource modification, including creations, updates, and destructions. Crucially, for destructive changes, it often indicates the specific attribute modifications that necessitate resource replacement or deletion, providing the "why" behind the planned action.

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.

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

31
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

Terraform commands, including `terraform plan`, operate strictly within the current working directory where the command is executed, unless explicitly specified otherwise with the `-chdir` option. If configuration files were modified in a separate directory, `terraform plan` run in the original directory would not detect those changes, as it only evaluates the `.tf` files present in its execution context, comparing them against the associated state file.

Why this answer

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.

32
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

terraform plan is a fundamental command in the core Terraform workflow, serving as the crucial second step after initialization. This command generates an execution plan, detailing exactly what actions Terraform will perform to achieve the desired state defined in the configuration files. It allows users to review proposed changes—such as creating, updating, or destroying resources—before any actual modifications are made to the real infrastructure, ensuring predictability and preventing unintended consequences.

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.

33
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 and installs provider plugins into a `.terraform` subdirectory within the current working directory. This local directory acts as the plugin cache for the specific configuration, ensuring that each Terraform project has its own isolated set of provider binaries. The `.terraform` directory is created automatically during initialization and is managed by Terraform to store plugins, modules, and state data.

Exam trap

The trap here is that candidates confuse the legacy `~/.terraform.d/plugins` directory (used in Terraform versions before 0.13) with the modern default `.terraform` directory, leading them to select Option C instead of A.

How to eliminate wrong answers

Option B is wrong because Terraform does not use a system-wide plugin directory like `/usr/share/terraform/plugins`; provider plugins are stored per-project in the `.terraform` directory, not in a global system path. Option C is wrong because `~/.terraform.d/plugins` is a legacy plugin directory used in older versions of Terraform (prior to v0.13) and is not the default location for provider plugins in modern Terraform; the default is now the `.terraform` directory within the project. Option D is wrong because provider plugins are not stored in a temporary directory that is deleted after `terraform init` completes; they are persisted in the `.terraform` directory for subsequent `terraform plan` and `terraform apply` operations.

34
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

When `terraform plan` is executed, it first performs a state refresh, comparing the current configuration against the actual state of resources in the cloud and the Terraform state file. If a previous `apply` was incomplete, this refresh will accurately identify which resources were successfully created or modified. Consequently, the new plan will only propose actions for the remaining resources that are either missing, require further modification, or need to be destroyed according to the desired state defined in the configuration.

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.

35
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

The `count` meta-argument in a resource block controls the number of identical resource instances Terraform should manage. When `count` is explicitly set to `0`, Terraform is instructed to manage zero instances of that specific resource. Consequently, if the resource does not currently exist in the state, `terraform plan` will show no changes because it is not intended to be created. If the resource *did* exist, setting `count` to `0` would cause `terraform plan` to propose its destruction.

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.

36
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

The "default" workspace is a fundamental component of Terraform's workspace management, automatically created when `terraform init` is first run in a directory. This workspace serves as the initial and fallback environment for state management. It cannot be deleted using `terraform workspace delete default` because Terraform requires at least one active workspace to manage state, ensuring continuity and preventing accidental loss of the primary state file.

Why this answer

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.

37
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

When Terraform attempts to acquire a state lock using DynamoDB, it performs a conditional write operation to a specific item in the lock table. A "conditional check fails" error specifically indicates that this write could not proceed because the expected conditions were not met, typically meaning another process has already written a lock item or the version ID does not match. This mechanism prevents concurrent state modifications, signifying that another Terraform process is actively holding the lock to protect state integrity and avoid race conditions.

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.

38
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

terraform plan operates strictly within the current working directory, scanning for .tf configuration files to build its desired state. If a user executes terraform plan from a directory that does not contain the relevant configuration files, or an outdated set, Terraform will not detect any changes made to files in other directories. Consequently, the plan output will reflect no changes, as it's comparing the current state to an unchanged or non-existent desired state from its perspective.

Why this answer

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

39
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

Workspaces, by design, share the same backend configuration, meaning a single `terraform init` command configures access to a specific remote state location (e.g., an S3 bucket or Azure Storage Account) for all workspaces. This shared backend increases the risk that an operator might accidentally switch to a production workspace while intending to work in a development environment, leading to unintended modifications or destruction of critical production infrastructure. The underlying backend access credentials and configuration are identical across all workspaces within that directory.

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.