Courseiva

CCNA Implement and maintain state Questions

64 questions · Implement and maintain state · All types, answers revealed

1
MCQhard

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

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

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

Why this answer

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

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

2
MCQeasy

A team is using a shared backend for Terraform state. After running terraform apply, the state file is locked for an extended period, causing other team members to fail with 'Error acquiring the state lock'. What is the most likely cause?

A.A previous terraform apply command was interrupted or crashed, leaving a stale lock.
B.Another team member is actively running terraform apply on the same state.
C.The backend configuration was changed without running terraform init.
D.The state file contains resources that no longer exist in the cloud provider.
AnswerA

When a `terraform apply` command is interrupted unexpectedly, such as due to a process crash, network failure, or manual termination, Terraform might fail to release the state lock it acquired at the beginning of the operation. This leaves a "stale" lock entry in the backend, preventing any subsequent Terraform commands from acquiring the necessary lock to modify the state. Terraform's state locking mechanism is designed to prevent concurrent modifications, so a persistent stale lock effectively blocks all further state-modifying operations until it is manually released, directly causing an "Error acquiring state lock" message.

Why this answer

Terraform uses a locking mechanism (typically via DynamoDB for AWS S3 backends) to prevent concurrent state modifications. If a `terraform apply` is interrupted or crashes, the lock may not be released, leaving a stale lock entry. This causes subsequent operations to fail with 'Error acquiring the state lock' until the lock is manually removed or expires (if TTL is configured).

Exam trap

HashiCorp often tests the distinction between a legitimate lock held by another user (Option B) and a stale lock from a crashed process (Option A), where candidates mistakenly think any lock error means someone else is actively working.

How to eliminate wrong answers

Option B is wrong because if another team member is actively running `terraform apply`, the lock is legitimate and not 'stale' — the error message is expected behavior, not a misconfiguration or bug. Option C is wrong because changing the backend configuration without `terraform init` would cause a backend initialization error, not a state lock error; the lock mechanism is backend-specific and would not be triggered by a config mismatch. Option D is wrong because resources that no longer exist in the cloud provider cause drift or refresh errors during `terraform plan` or `apply`, but do not affect the state locking mechanism, which operates at the backend level independently of resource state.

3
MCQhard

An organization uses Terraform with the AzureRM backend. The team recently split a large configuration into multiple smaller configurations, each with its own state file. They want to share outputs from one configuration (networking) as inputs to another (compute). Which approach should they use to reference the networking state from the compute configuration without duplicating data?

A.Define output values in the networking configuration and they will be automatically available in the compute configuration.
B.Run 'terraform output' on the networking state and save the values to a JSON file, then use 'terraform_remote_state' to read them.
C.Use a 'data' 'terraform_remote_state' block in the compute configuration to read the networking state.
D.Hardcode the subnet IDs from the networking configuration into the compute configuration.
AnswerC

The `data "terraform_remote_state"` block is the standard and recommended method for sharing information, specifically output values, between separate Terraform configurations. By configuring this data source in the compute configuration to point to the networking configuration's remote state, it can securely and dynamically retrieve the defined output values, such as subnet IDs, for use in creating compute resources. This establishes a clear dependency and promotes modularity.

Why this answer

The `terraform_remote_state` data source allows one Terraform configuration to read the root-level output values from another configuration's state file stored in the AzureRM backend. This enables sharing of networking outputs (e.g., subnet IDs) into the compute configuration without duplicating data or manually exporting values. The data source retrieves the state directly from the configured backend, ensuring the compute configuration always uses the latest networking outputs.

Exam trap

HashiCorp often tests the misconception that `terraform output` or automatic sharing between configurations is sufficient, but the correct approach is always to use the `terraform_remote_state` data source to read outputs from a separate state file.

How to eliminate wrong answers

Option A is wrong because Terraform does not automatically share outputs between separate configurations; each configuration has its own state file and outputs must be explicitly referenced. Option B is wrong because while `terraform output` can produce a JSON file, the `terraform_remote_state` data source reads the state file directly from the backend, not from a local JSON file; saving to a JSON file introduces manual steps and risks stale data. Option D is wrong because hardcoding subnet IDs violates the principle of infrastructure as code, creates duplication, and requires manual updates whenever networking changes.

4
Multi-Selectmedium

Which THREE actions should be taken when migrating Terraform state from local to a remote backend?

Select 3 answers
A.Remove the local state file before running terraform init.
B.Run terraform init to initialize the backend and migrate state.
C.Manually import all existing resources into the remote state.
D.Confirm migration by typing 'yes' when prompted.
E.Add a backend block to the configuration.
AnswersB, D, E

This command handles the migration.

Why this answer

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

Exam trap

HashiCorp often tests the misconception that you must manually delete or move the local state file before initializing a remote backend, when in fact `terraform init` handles the migration automatically and safely.

5
MCQhard

Refer to the exhibit. An engineer runs the commands shown in sequence. After executing 'terraform state rm', the next 'terraform plan' shows that the resource will be created. What is the most likely reason?

A.The 'terraform state rm' command only removes the resource from the state file, not the actual infrastructure. The next plan sees the configuration and attempts to create a new resource.
B.The 'terraform state rm' command triggers an automatic recreation of the resource.
C.The resource was destroyed by a separate process.
D.The state file was corrupted after removal.
AnswerA

The 'terraform state rm' command specifically targets the Terraform state file, removing the record of a managed resource without interacting with the actual cloud provider API to destroy the resource itself. When 'terraform plan' is subsequently executed, it compares the current configuration (which still declares the resource) against the modified state file (which no longer contains the resource's record). This discrepancy leads Terraform to identify the resource as "missing" from its management, prompting a plan to create a new instance to align the infrastructure with the desired configuration.

Why this answer

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

6
Multi-Selecthard

Which TWO statements are correct about Terraform state when using the S3 backend with DynamoDB for state locking?

Select 2 answers
A.The DynamoDB table must exist before running terraform init
B.The S3 bucket should be versioned to provide consistency checks and recovery options
C.State can be stored without specifying a key in the backend configuration
D.State is encrypted at rest by default using SSE
E.State locking prevents any read operations on the state file
AnswersA, B

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

Why this answer

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

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

7
MCQhard

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

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

This command releases the lock from the previous session.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

8
MCQhard

A team is migrating from local state to an S3 remote backend. They have existing state files in the working directory. After configuring the backend block and running `terraform init`, what is the correct next step to migrate the existing state?

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

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

Why this answer

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

9
MCQhard

Refer to the exhibit. A developer creates a new Terraform configuration with this backend block and runs terraform init. What will happen?

A.Terraform will initialize with a local backend because the remote backend configuration is incomplete.
B.Terraform will return an error and fail to initialize.
C.Terraform will use default values for the missing arguments and initialize successfully.
D.Terraform will prompt the developer interactively for the missing arguments.
AnswerB

Terraform's 'init' command performs validation of the backend configuration early in its execution. When a remote backend, like AWS S3, is declared but critical, non-optional arguments such as 'bucket' or 'region' are omitted, Terraform identifies this as an invalid configuration. Consequently, it will immediately terminate the initialization process and output a specific error message indicating the missing required arguments, preventing any further operations.

Why this answer

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

10
Multi-Selectmedium

Which four of the following statements about Terraform state management are correct? (Choose all that apply. There are four correct answers.)

Select 4 answers
.Using remote state storage with a backend like S3 or Azure Storage provides locking to prevent concurrent modifications.
.The `terraform state rm` command can be used to remove a resource from state without destroying the real infrastructure.
.Sensitive data stored in state files can be protected by encrypting the state backend at rest.
.The `terraform import` command updates the state file to include an existing resource, enabling Terraform to manage it.
.Terraform automatically backs up the previous state file every time a new state is written.
.The `terraform state list` command can modify the state file to rename a resource.

Why this answer

Remote state backends like S3 or Azure Storage support state locking (via DynamoDB or Azure Blob lease) to prevent concurrent modifications, ensuring consistency. The `terraform state rm` command removes a resource from state without destroying the real infrastructure, which is useful for detaching management. Encrypting the state backend at rest (e.g., S3 server-side encryption or Azure Storage encryption) protects sensitive data like passwords or keys stored in the state file.

The `terraform import` command updates the state file to include an existing resource, allowing Terraform to take over its management without recreating it.

Exam trap

HashiCorp often tests the misconception that `terraform state list` can modify state or that automatic backups are built-in, when in fact Terraform requires explicit backend versioning or manual backup configuration.

11
MCQeasy

A developer is working on a Terraform configuration that manages a single resource. They want to import an existing AWS EC2 instance into state. Which command should they use?

A.terraform apply
B.terraform refresh
C.terraform import
D.terraform state mv
AnswerC

The `terraform import` command is the designated tool for bringing existing infrastructure resources, which were provisioned outside of Terraform's management, into the Terraform state file. It establishes a link between a specified remote resource and a corresponding resource block defined in the Terraform configuration. This crucial command enables developers to adopt pre-existing infrastructure and manage it subsequently with Terraform, integrating it into the desired state.

Why this answer

`terraform import` is the dedicated command for bringing an existing infrastructure resource (like an AWS EC2 instance) under Terraform management by attaching it to a resource block in the state file. It requires the resource address and the provider-specific ID (e.g., `aws_instance.my_instance i-1234567890abcdef0`) to map the real-world resource into the Terraform state without modifying the resource itself.

Exam trap

HashiCorp often tests the distinction between `terraform import` (which only updates state) and `terraform apply` (which modifies infrastructure), so the trap here is that candidates mistakenly think `terraform apply` can also import resources because it can create new ones, but it cannot attach to an existing resource that is not already in state.

How to eliminate wrong answers

Option A is wrong because `terraform apply` is used to create, update, or destroy resources based on the configuration, not to import existing resources into state. Option B is wrong because `terraform refresh` updates the state file to match real-world infrastructure but does not add new resources that are not already tracked in state; it cannot import a resource that has no corresponding state entry. Option D is wrong because `terraform state mv` moves a resource from one state address to another within the same state file or between state backends, but it does not bring an external resource into state for the first time.

12
MCQmedium

An organization uses Terraform workspaces to manage multiple environments (dev, staging, prod) with the same configuration. What is the primary benefit of using workspaces for state management?

A.Workspaces reduce the number of Terraform configurations needed
B.Workspaces automatically synchronize state across team members
C.Each workspace has its own independent state file, preventing environment conflicts
D.Workspaces enable role-based access control to state
AnswerC

This statement is correct because the fundamental purpose of Terraform workspaces is to provide independent state files for different environments or contexts. When a new workspace is created or selected, Terraform ensures that all subsequent operations, like `plan` and `apply`, interact with that specific, isolated state. This critical separation prevents accidental modifications or resource conflicts between distinct environments, such as development, staging, and production, even when using the exact same configuration code.

Why this answer

Terraform workspaces allow each environment (dev, staging, prod) to maintain its own independent state file within the same backend configuration. This isolation prevents state conflicts, such as one environment's resources being accidentally overwritten or destroyed by operations intended for another environment, which is critical for safe multi-environment management.

Exam trap

The trap here is that candidates confuse workspaces with environment-specific configurations or assume workspaces provide built-in state locking or access control, when in fact they only provide state isolation and require separate backend mechanisms for locking and RBAC.

How to eliminate wrong answers

Option A is wrong because workspaces do not reduce the number of Terraform configurations; they reuse the same configuration but separate state, so you still need a single configuration (or module) that works across environments. Option B is wrong because workspaces do not automatically synchronize state across team members; state synchronization requires a remote backend (e.g., S3 with DynamoDB locking) and is not a built-in feature of workspaces themselves. Option D is wrong because workspaces do not enable role-based access control (RBAC) to state; RBAC is implemented at the backend level (e.g., IAM policies on S3 buckets) and is independent of workspace functionality.

13
MCQeasy

A team uses an S3 backend for Terraform state. During a `terraform apply`, another team member accidentally runs a plan that also modifies the same state. Which feature prevents state corruption in this scenario?

A.The `-lock=false` flag
B.Terraform Cloud remote operations
C.State locking via DynamoDB
D.State versioning in S3
AnswerC

State locking via DynamoDB is the correct and recommended mechanism for protecting Terraform state when using an S3 backend. Terraform utilizes a DynamoDB table to acquire and release a distributed lock before and after state modifications, ensuring that only one `terraform apply` or `terraform destroy` operation can proceed at a time. This prevents race conditions, safeguards state consistency, and avoids corruption in shared development or production environments.

Why this answer

State locking via DynamoDB prevents concurrent modifications to the state file, ensuring that only one operation can modify the state at a time. Option A (-lock=false) disables locking, which would allow concurrent modifications and risk corruption. Option B (Terraform Cloud remote operations) is not directly related to state locking in this S3 backend scenario.

Option D (state versioning) helps recover from corruption but does not prevent simultaneous writes.

14
MCQmedium

Refer to the exhibit. A Terraform configuration includes an `aws_instance.web` resource. The state shows the instance with a specific AMI and instance type. After running `terraform plan`, Terraform reports no changes. However, an engineer observes that the actual instance in AWS has a different AMI ID but the same instance type. What is the most likely cause?

A.The instance type was modified after the last apply, but AMI was not
B.The state file has not been refreshed since the manual AMI change; it still reflects the old AMI
C.The `terraform plan` command ignores drift by default
D.The AMI data source is returning a different value each time
AnswerB

Terraform compares state to config, not state to real world, unless refresh happens.

Why this answer

The state file is stale because it has not been refreshed since the AMI was manually changed outside of Terraform. When `terraform plan` runs, by default it first refreshes the state, but if the manual change occurred before the last refresh, the plan would have detected drift. However, if no refresh has occurred after the manual change, the plan compares the configuration with the old state, showing no changes.

The issue is that the state file still reflects the old AMI. Option B correctly identifies that the state has not been refreshed since the manual change.

15
MCQhard

A user accidentally ran `terraform state rm` on a critical resource, removing it from state but not destroying the actual infrastructure. Later, they need to re-import the resource. Which sequence of commands correctly accomplishes this?

A.`terraform state push` with the original state file
B.`terraform plan` and then `terraform apply`
C.`terraform refresh` and then `terraform plan`
D.`terraform import` using the resource address and ID of the resource
AnswerD

terraform import is the correct and intended method for bringing existing infrastructure under Terraform management. When a resource is accidentally removed from the state file via terraform state rm, the remote resource still exists. By specifying the resource's address (e.g., aws_instance.web) from the configuration and its actual cloud provider ID (e.g., i-0abcdef1234567890), terraform import reads the resource's current configuration from the provider and adds it back into the Terraform state file, linking it to the specified configuration block without modifying the live resource.

Why this answer

After removal, the resource is unmanaged. `terraform import` re-associates it with state. Option D is the correct sequence.

16
MCQmedium

A team manages infrastructure with Terraform and uses a remote backend in an S3 bucket. After a recent state migration, a developer runs 'terraform plan' and gets an error: 'Error: Error loading state: NoSuchKey: The specified key does not exist.' The developer confirms that the state file exists in the bucket. What is the most likely cause?

A.The backend configuration in the Terraform code does not match the actual state file path.
B.Terraform state locking is enabled but the lock was not released.
C.The S3 bucket policy does not allow reading the state file.
D.S3 bucket versioning is enabled, and the state file is a non-current version.
AnswerA

This is the correct answer. A "NoSuchKey" error from an S3 backend explicitly indicates that Terraform attempted to retrieve a state file at a specific S3 key (path) but found no object there. This frequently occurs when the 'key' parameter in the 'backend "s3"' configuration, or the active Terraform workspace, does not precisely align with the actual location of the state file in the S3 bucket, causing Terraform to look for a non-existent object.

Why this answer

The error 'NoSuchKey: The specified key does not exist' indicates that Terraform is looking for the state file at a specific key (path) in the S3 bucket, but that key does not exist. Since the developer confirms the state file exists in the bucket, the most likely cause is a mismatch between the backend configuration in the Terraform code (e.g., the `key` argument) and the actual path where the state file is stored. This often happens after a state migration if the backend configuration was not updated to reflect the new location.

Exam trap

HashiCorp often tests the distinction between access denied errors (403) and missing key errors (404), so the trap here is that candidates might confuse a permission issue with a path mismatch, especially when the state file is confirmed to exist in the bucket.

How to eliminate wrong answers

Option B is wrong because state locking uses a separate lock file (e.g., a DynamoDB table entry) and does not affect the existence or retrieval of the state file itself; a released lock would not cause a 'NoSuchKey' error. Option C is wrong because if the S3 bucket policy denied read access, the error would typically be an access denied (403) error, not a 'NoSuchKey' (404) error. Option D is wrong because versioning does not change the current key; Terraform by default retrieves the latest version of the state file, and a non-current version would still be accessible via the same key with a version ID, but the error indicates the key itself is missing.

17
Multi-Selecteasy

Which TWO of the following are valid strategies to migrate Terraform state from a local backend to a remote backend?

Select 2 answers
A.Use terraform import for each resource
B.Manually copy the local state file to the remote backend storage
C.Change backend configuration and run terraform init -reconfigure
D.Use terraform init with the -migrate-state flag
E.Use the terraform state push command
AnswersB, D

Manually copying the local state file (`terraform.tfstate`) to the remote backend storage location is a valid, albeit less automated, strategy. This approach requires direct interaction with the remote storage system (e.g., uploading to an S3 bucket or Azure Blob Storage). After the manual copy, you must then run `terraform init` (without the `-migrate-state` flag, as the state is already present) to configure Terraform to recognize and use the state file now residing in the remote backend.

Why this answer

The valid strategies for migrating state from local to remote backend are: manually copying the state file to the remote location (B) or using `terraform init -migrate-state` (D). Option C is incorrect because `terraform init -reconfigure` only reconfigures the backend without migrating the existing state.

18
MCQhard

You are a DevOps engineer for a company that uses Terraform to manage infrastructure across multiple AWS accounts (production, staging, development). Each account has its own Terraform configuration and remote state stored in an S3 bucket with DynamoDB locking. Recently, the production deployment pipeline failed with the error: 'Error: Error loading state: AccessDenied: Access Denied'. The pipeline runs under an IAM role that has been working for months. The S3 bucket policy and IAM role permissions have not been changed. However, the team did recently enable S3 bucket versioning and added a lifecycle policy to transition objects to Glacier after 30 days. The state file was last modified 35 days ago. What is the most likely cause of the error?

A.The DynamoDB lock table has a stale lock from a previous deployment that is blocking read access.
B.The IAM role's permissions were inadvertently revoked due to a recent AWS policy change.
C.The S3 bucket policy now denies access to objects older than 30 days due to a new condition key.
D.The state file was transitioned to Amazon S3 Glacier by the lifecycle policy, and Terraform cannot read it without restoration.
AnswerD

When an S3 object, such as a Terraform state file, is transitioned to the Amazon S3 Glacier or Glacier Deep Archive storage class by a lifecycle policy, it is no longer immediately accessible via standard S3 GetObject requests. Attempting to retrieve an object in Glacier without first initiating a restoration job will result in an AccessDenied error from S3. Terraform requires immediate, direct read access to its state file, making restoration a necessary prerequisite for any operations if the state is archived in Glacier.

Why this answer

D is correct because the S3 lifecycle policy transitions objects to the Glacier storage class after 30 days. The state file was last modified 35 days ago, so it has been moved to Glacier. Terraform cannot read objects in the Glacier storage class directly; it requires a restoration (e.g., using `aws s3api restore-object`) before the state can be accessed, resulting in the 'AccessDenied' error.

Exam trap

HashiCorp often tests the distinction between 'AccessDenied' errors caused by storage class transitions (e.g., Glacier) versus permission-based denials, and the trap here is that candidates may assume the error is due to a policy change or stale lock, ignoring the lifecycle policy's effect on object accessibility.

How to eliminate wrong answers

Option A is wrong because a stale DynamoDB lock would cause a 'lock acquisition' error (e.g., 'Error acquiring the state lock'), not an 'AccessDenied' error when loading state. Option B is wrong because the scenario explicitly states that the IAM role permissions and S3 bucket policy have not been changed, so a policy revocation is not the cause. Option C is wrong because S3 bucket policies do not automatically deny access based solely on object age unless a specific condition key (e.g., `s3:ObjectAgeInDays`) is explicitly added to the policy, and the scenario says the policy was not changed.

19
MCQmedium

Refer to the exhibit. After applying the plan, the state serial number is 2. What was the serial number before the apply?

A.0
B.1
C.3
D.2
AnswerB

The Terraform state serial consistently increments by exactly one (1) for every successful modification to the state file, regardless of the number of resources added, changed, or destroyed within that single `terraform apply` operation. This behavior ensures a clear, sequential version history of the infrastructure's configuration as managed by Terraform. Therefore, after applying a plan that modifies the state, the serial will increase by 1.

Why this answer

The serial number increments by 1 each time state is modified. Initially the state had serial 1 (or 0 if fresh). After the apply adding one resource, serial becomes 2, so previous serial was 1.

20
Multi-Selectmedium

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

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

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

Why this answer

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

Exam trap

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

21
MCQeasy

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

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

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

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

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

22
MCQeasy

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

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

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

Why this answer

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

23
Multi-Selectmedium

Which TWO of the following are true about Terraform workspaces?

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

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

Why this answer

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

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

Exam trap

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

24
MCQmedium

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

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

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

Why this answer

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

25
MCQeasy

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

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

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

Why this answer

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

26
Multi-Selectmedium

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

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

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

Why this answer

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

27
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

28
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

29
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

30
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

31
Multi-Selectmedium

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

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

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

Why this answer

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

Exam trap

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

32
MCQhard

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

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

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

Why this answer

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

33
Multi-Selecthard

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

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

Remote backends enable sharing and locking.

Why this answer

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

Exam trap

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

34
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

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

35
MCQeasy

A user runs `terraform apply` and receives an error: 'Error acquiring the state lock'. What is the most likely cause?

A.Another user is running a Terraform command that modifies state.
B.The state file is missing.
C.The backend configuration is invalid.
D.The Terraform provider is incompatible.
AnswerA

When multiple Terraform operations attempt to modify the state file concurrently, Terraform employs a state locking mechanism to prevent corruption. If one user initiates a command like `terraform apply` or `terraform destroy` that acquires the state lock, any subsequent operation attempting to modify the state will encounter an "error acquiring state lock" message. This ensures data integrity by serializing state-modifying actions, preventing race conditions and inconsistent infrastructure deployments.

Why this answer

The error 'Error acquiring the state lock' means that another operation currently holds the lock on the state file. Option A is correct because if another user is running a Terraform command that modifies state (such as apply or destroy), the lock will be acquired and subsequent operations will fail. Option B is incorrect because a missing state file would produce a different error (e.g., 'No state file found').

Option C is incorrect because invalid backend configuration is caught during 'terraform init', not during 'apply'. Option D is incorrect because provider incompatibility typically leads to plugin-related errors, not state lock errors.

36
Multi-Selectmedium

Which TWO statements about Terraform state locking are correct?

Select 2 answers
A.State locking prevents concurrent modifications to the same state file.
B.State locking is enabled by default when using a local state backend.
C.State locking is not supported in Terraform Cloud.
D.State locking is only necessary when multiple team members are running terraform apply simultaneously.
E.State locking requires a backend that supports locking, such as S3 with DynamoDB table.
AnswersA, E

State locking is a critical mechanism that serializes access to the Terraform state file, ensuring that only one operation can modify it at any given time. This prevents race conditions and data corruption that could occur if multiple `terraform apply` or `terraform plan` operations attempted to write to the state simultaneously. By enforcing exclusive access, it maintains the integrity and consistency of the infrastructure's recorded state, which is essential for reliable infrastructure management.

Why this answer

State locking prevents concurrent modifications to the same state file, ensuring consistency. Option E is correct because state locking relies on backend support; for example, S3 requires a DynamoDB table to enable locking. Option B is false because local state backends do not support locking; it is not enabled by default.

Option C is false because Terraform Cloud fully supports state locking automatically. Option D is false because state locking is necessary for any operation that modifies state, even with a single user, to prevent corruption.

37
MCQhard

A Terraform state file is stored in an S3 bucket with versioning enabled. During a deployment, the state file becomes corrupted due to a network error. What is the best way to recover?

A.Use `terraform state pull` to overwrite the corrupted state.
B.Run `terraform import` to import all resources.
C.Restore the previous version of the state file from S3 versioning.
D.Delete the state file and run `terraform apply` to recreate all resources.
AnswerC

S3 versioning, when enabled on the bucket storing the Terraform state file, automatically retains multiple historical versions of the state object. In the event of state file corruption, an administrator can directly access the S3 bucket, locate the corrupted state file, and restore a previous, known-good version of that file. This action effectively rolls back the Terraform state to a functional point, allowing operations to resume without data loss or manual reconciliation.

Why this answer

S3 versioning preserves previous versions of objects, including Terraform state files. When the current state file becomes corrupted, you can restore a prior, uncorrupted version directly from the S3 bucket without data loss or manual re-creation of resources. This is the safest and most efficient recovery method.

Exam trap

A common trap is assuming that `terraform state pull` can fix corruption, but it only retrieves the current state; the real recovery mechanism is S3 versioning.

How to eliminate wrong answers

Option A is wrong because `terraform state pull` retrieves the current state from the configured backend (S3), but if the state file is already corrupted, pulling it will only fetch the corrupted data, not fix it. Option B is wrong because `terraform import` is used to bring existing infrastructure under Terraform management, not to recover a corrupted state file; it would require manually importing every resource, which is error-prone and time-consuming. Option D is wrong because deleting the state file and running `terraform apply` would cause Terraform to attempt to create new resources, potentially leading to duplicate infrastructure or conflicts with existing resources, and it does not recover the previous state.

38
MCQmedium

An organization stores state files in an S3 backend with encryption. However, some resource attributes (e.g., database passwords) are stored in plaintext within the state. What is the recommended approach to avoid storing sensitive values in state?

A.Use a secrets backend like Vault to retrieve secrets at runtime and store only references in state
B.Set the `sensitive` parameter on all resources
C.Enable state encryption with a stronger algorithm
D.Use the `terraform state rm` command after apply to remove sensitive attributes
AnswerA

Integrating Terraform with a dedicated secrets backend, such as HashiCorp Vault, allows sensitive values to be retrieved dynamically at runtime using data sources. This approach ensures that the actual secret values are never directly written into the Terraform state file. Instead, the state only contains non-sensitive references or identifiers, significantly reducing the risk of exposure if the state file is ever compromised, even if encrypted. This method adheres to the principle of least privilege by keeping secrets out of persistent storage.

Why this answer

Terraform can mark outputs as sensitive to hide them from display, but they may still be stored in state. Option A is a common practice to avoid storing secrets directly.

39
MCQmedium

A team of five engineers manages infrastructure using Terraform with remote state stored in an S3 bucket and state locking via a DynamoDB table. After a power outage, an engineer notices that a terraform apply command fails with the message: 'Error: Error acquiring the state lock'. The engineer suspects that a lock from a previous run has not been released. The team needs to proceed with applying changes. Which action should the engineer take to resolve the issue safely?

A.Wait for the lock to expire automatically (locks have a 5-minute TTL).
B.Delete the lock record from the DynamoDB table using the AWS CLI.
C.Run terraform force-unlock with the lock ID obtained from the error message.
D.Run terraform apply with the -lock=false flag to bypass locking.
AnswerC

The `terraform force-unlock` command is the officially supported and safest method for releasing a persistent state lock when the original process that acquired it has crashed or is no longer active. This command specifically requires the lock ID, which is typically provided within the error message when an operation attempts to acquire an already held lock. Using `force-unlock` ensures that Terraform's backend properly acknowledges the lock's release, preventing potential state corruption that could arise from manual intervention.

Why this answer

The `terraform force-unlock` command is the intended safe method to release a stuck lock when the lock holder process is confirmed dead. The lock ID is provided in the error message. Option A is incorrect because Terraform state locks do not have a default automatic expiration; they must be explicitly released.

Option B is risky: directly deleting the lock record from DynamoDB can lead to inconsistent state if not done carefully, and is not recommended as a standard practice. Option D bypasses locking entirely with `-lock=false`, which can cause state corruption if other operations are in progress, so it is unsafe.

40
MCQhard

Refer to the exhibit. An engineer sees this error. Which command should they run to force-unlock?

A.terraform force-unlock my-company-terraform-state/prod/terraform.tfstate
B.terraform unlock -id=123456
C.terraform state unlock 123456
D.terraform init -force-unlock=123456
E.terraform force-unlock 123456
AnswerE

The `terraform force-unlock` command is the correct and designated method for manually releasing a Terraform state lock that has become stale or orphaned. This command requires the specific lock ID, which is typically provided in the error message when a lock prevents an operation, or can be retrieved from the backend's locking mechanism. Providing the correct lock ID ensures that only the intended lock is released, allowing subsequent Terraform operations to proceed.

Why this answer

`terraform force-unlock <LOCK_ID>` is the exact command Terraform provides to manually release a state lock when the automatic unlocking mechanism fails (e.g., after a crash or network interruption). The lock ID is a unique identifier assigned by the backend (such as DynamoDB or Consul) when the lock was acquired, and this command bypasses the normal safety checks to force the unlock.

Exam trap

The Terraform exam often tests the exact syntax of `terraform force-unlock <LOCK_ID>` versus similar-sounding commands like `terraform state unlock` or `terraform unlock`, exploiting the fact that candidates may confuse the command name or the required argument (lock ID vs. state file path).

How to eliminate wrong answers

Option A is wrong because `terraform force-unlock` does not accept a state file path as an argument; it requires the lock ID, not a file path. Option B is wrong because `terraform unlock` is not a valid Terraform command; the correct command is `force-unlock`. Option C is wrong because `terraform state unlock` is not a valid subcommand; the `state` subcommand does not have an `unlock` action.

Option D is wrong because `terraform init` does not accept a `-force-unlock` flag; that flag belongs to `terraform force-unlock`.

41
MCQhard

An organization uses Terraform Cloud workspaces to manage multiple environments. They notice that after promoting a configuration change from development to production workspace, the production workspace's state file contains references to resources that were only created in development. What is the most likely cause?

A.The workspaces were configured to use the same S3 backend and prefix, causing state overlap.
B.The user ran `terraform state mv` to move resource instances from development to production workspace.
C.A user manually edited the production state file to include development resources.
D.The development workspace's output values were used in production via `terraform_remote_state`.
AnswerB

The `terraform state mv` command is the standard and intended method for relocating resource instances within or between Terraform state files. When executed against a remote backend like Terraform Cloud, it directly modifies the state of the target workspace, effectively transferring the management of specific resources from one state to another, such as from a development to a production workspace.

Why this answer

The `terraform state mv` command can move resource instances from one workspace's state file to another, which explains why production state contains references to development resources. Option A (same backend/prefix) could cause state corruption but would not selectively move resources. Option C is unlikely and error-prone.

Option D would allow reading outputs but not modify production state.

42
MCQeasy

A user wants to use a remote state backend for the first time. After adding the backend configuration, which command must they run to migrate the state from local to remote?

A.`terraform plan`
B.`terraform init`
C.`terraform apply`
D.`terraform state push`
AnswerB

The `terraform init` command is essential for preparing a working directory for Terraform operations, which includes configuring the backend. When a backend configuration is present for the first time, `init` detects it, initializes the connection, and crucially, prompts the user to migrate any existing local state file to the newly configured remote backend. This makes it the correct and primary command for setting up remote state.

Why this answer

When you add a remote backend configuration to your Terraform code, `terraform init` is the required command to initialize the backend and migrate the existing local state file to the remote backend. During initialization, Terraform detects the backend change, prompts for confirmation, and automatically copies the state from the local `terraform.tfstate` to the configured remote store (e.g., S3, Azure Storage, or Terraform Cloud). Without running `init`, the remote backend is not configured and local state remains unchanged.

Exam trap

A common misconception is that `terraform apply` or `terraform state push` can handle backend migration, but only `terraform init` performs the full initialization and state migration workflow.

How to eliminate wrong answers

Option A is wrong because `terraform plan` only creates an execution plan by comparing the current state with the configuration; it does not initialize backends or migrate state. Option C is wrong because `terraform apply` executes changes to infrastructure but relies on an already-initialized backend; it cannot set up or migrate state to a remote backend. Option D is wrong because `terraform state push` is used to manually overwrite the remote state with a local state file, but it is not the correct or safe command for initial migration; it bypasses the proper initialization workflow and can cause state conflicts.

43
MCQhard

Refer to the exhibit. After importing an AWS instance, the state file shows the resource. However, the configuration file (main.tf) does not yet contain the resource definition. What will happen when 'terraform plan' is run?

A.It will show a plan to destroy the resource because it exists in state but not in configuration.
B.It will show a plan to create the resource because the configuration is missing.
C.It will error because the configuration and state are out of sync.
D.It will show no changes because the resource is already in state.
AnswerA

When a resource is present in the Terraform state file but its corresponding definition is absent from the configuration files, Terraform's `plan` command identifies this discrepancy. The configuration explicitly defines the *desired* state of the infrastructure. If a resource exists in the actual infrastructure (and thus in state) but is not desired per the configuration, Terraform will propose to destroy it to align the real world with the declared configuration.

Why this answer

Terraform plan compares the state to the configuration. Since the resource exists in state but not in configuration, Terraform will plan to destroy the resource because it is no longer managed (configuration is the source of truth for what should exist).

44
MCQhard

Refer to the exhibit. A developer updates the network state and runs terraform apply. The aws_instance.web is not recreated. Which statement explains this behavior?

A.The instance resource does not reference the remote state data source, so changes to the remote state do not trigger recreation.
B.Terraform automatically locks the remote state to prevent changes during apply.
C.The security group resource depends on the remote state, and it was updated, but the instance was not affected.
D.The remote state data source is cached and only refreshes every hour.
AnswerA

The instance resource's configuration arguments did not change as a direct result of the remote state update because it does not explicitly reference any outputs from the `terraform_remote_state` data source. Terraform's core principle for resource recreation is based on detecting a diff in the resource's *own* defined arguments or its direct dependencies. Since the instance resource's definition remained stable and independent of the remote state, it was not marked for recreation, even if other resources that *did* depend on the remote state were updated.

Why this answer

The data source data.terraform_remote_state.network is read during planning and is not stored in state. If the remote state changes, Terraform will see the new vpc_id and may update the security group, but the instance resource does not depend on the remote state, so it is not affected.

45
MCQmedium

A team is using a remote backend in Terraform Cloud. After a failed apply, the state file is locked. The team lead wants to unlock the state immediately. What should be done?

A.Delete the state file from the backend and reinitialize
B.Run terraform force-unlock with the lock ID
C.Manually edit the state file to remove the lock
D.Run terraform unlock
AnswerB

The terraform force-unlock command with the lock ID manually releases the lock.

Why this answer

The `terraform force-unlock` command with the lock ID is the correct way to manually unlock a state file in Terraform Cloud after a failed apply. This command overrides the backend's lock mechanism, which is designed to prevent concurrent modifications and state corruption. Deleting or editing the state file would bypass Terraform's safety guarantees and risk data loss or inconsistency.

Exam trap

The trap here is that candidates may confuse `terraform force-unlock` with a non-existent `terraform unlock` command, or mistakenly think that deleting or editing the state file is a valid workaround, when in fact Terraform's state locking is enforced at the backend API level and requires the proper command with the lock ID.

How to eliminate wrong answers

Option A is wrong because deleting the state file from the backend destroys the entire state history and can cause Terraform to lose track of managed resources, leading to orphaned infrastructure or re-creation attempts. Option C is wrong because manually editing the state file is unsupported and dangerous; it can corrupt the state, break Terraform's internal structure, and is not a valid operation for removing a lock. Option D is wrong because `terraform unlock` is not a valid Terraform command; the correct command is `terraform force-unlock`, which requires the lock ID as an argument.

46
Multi-Selecteasy

Which two statements about Terraform state files are true? (Choose two.)

Select 2 answers
A.State files are automatically encrypted at rest by all backends.
B.State files should be stored in version control.
C.State files are used to map configuration to real-world resources.
D.State files can be shared across multiple users simultaneously without issues.
E.State files can contain sensitive data such as database passwords.
AnswersC, E

State files are indeed used to map configuration to real-world resources, which is their primary and most fundamental function. The state file serves as the definitive source of truth, meticulously recording the unique identifiers and attributes of all infrastructure components provisioned by Terraform. This mapping allows Terraform to understand the current state of the infrastructure and accurately determine the necessary actions to reconcile it with the desired configuration defined in your HCL files.

Why this answer

Terraform state files serve as a mapping between configuration and real-world resources (C). They can contain sensitive data such as database passwords or resource attributes (E). However, state files are not automatically encrypted by all backends; encryption depends on the backend configuration (A false).

State files should not be stored in version control due to potential sensitive content (B false). Concurrent writes to state files can cause corruption or conflicts, so sharing without locking is problematic (D false).

47
MCQeasy

Refer to the exhibit. A user has this backend configuration. The user then runs `terraform init` and receives an error: 'NoSuchBucket: The specified bucket does not exist'. What is the most likely cause?

A.The bucket does not exist and needs to be created.
B.The AWS region is wrong.
C.The DynamoDB table is missing.
D.The credentials lack S3 permissions.
AnswerA

The NoSuchBucket error explicitly indicates that the Amazon S3 bucket specified in the Terraform backend configuration does not exist within the AWS region where Terraform is attempting to initialize. Terraform's S3 backend requires a pre-existing S3 bucket to securely store the state file, which tracks the infrastructure managed by Terraform. Therefore, this error mandates that the user must manually create the S3 bucket with the exact name and in the correct region before terraform init can successfully configure the remote state.

Why this answer

The error 'NoSuchBucket: The specified bucket does not exist' directly indicates that the S3 bucket referenced in the backend configuration does not exist in the AWS account. Terraform requires the S3 bucket to already exist before running `terraform init` because it needs to store the state file; it does not create the bucket automatically. Therefore, the most likely cause is that the bucket has not been created yet.

Exam trap

Many candidates assume Terraform will automatically create the S3 bucket when the backend is configured, but Terraform requires the bucket to exist beforehand. Understanding this prerequisite is key for the exam.

How to eliminate wrong answers

Option B is wrong because if the AWS region were incorrect, the error would typically be 'BucketRegionError' or a timeout, not 'NoSuchBucket'; the bucket name is globally unique and the error specifically says the bucket does not exist, not that it cannot be reached. Option C is wrong because a missing DynamoDB table would cause an error related to state locking (e.g., 'ResourceNotFoundException') during `terraform apply`, not during `terraform init`; `terraform init` only checks the S3 bucket existence, not the DynamoDB table. Option D is wrong because insufficient S3 permissions would produce an 'AccessDenied' or 'Forbidden' error, not 'NoSuchBucket'; the error indicates the bucket is absent, not that access is denied.

48
MCQmedium

A user wants to inspect the current attributes of a specific resource in the Terraform state. Which command should they use?

A.terraform state list <resource>
B.terraform output
C.terraform state show <resource>
D.terraform plan
E.terraform show
AnswerC

The `terraform state show <resource>` command precisely fulfills the requirement by displaying the complete, current state data for a specified resource address. This includes all recorded attributes, dependencies, and metadata as stored in the Terraform state file. It provides a detailed snapshot of the resource's last known configuration and status, making it ideal for inspecting specific resource attributes.

Why this answer

The `terraform state show <resource>` command is specifically designed to inspect the current attributes of a single resource within the Terraform state file. It reads the state directly and outputs the resource's attributes in a human-readable format, making it the correct tool for this task.

Exam trap

Terraform often tests the distinction between commands that list resources (`state list`) versus those that show detailed attributes (`state show`), and candidates frequently confuse `terraform show` (which dumps the entire state) with the resource-specific `terraform state show`.

How to eliminate wrong answers

Option A is wrong because `terraform state list` only lists resource addresses in the state, not their attributes; it does not show detailed attribute values. Option B is wrong because `terraform output` displays only output values defined in the configuration, not the attributes of arbitrary resources in the state. Option D is wrong because `terraform plan` compares the current state with the configuration to show changes, but it does not simply inspect current attributes of a specific resource.

Option E is wrong because `terraform show` displays the entire state or plan file in a formatted way, but it is not scoped to a single resource and does not provide the focused attribute inspection that `terraform state show` does.

49
MCQeasy

Refer to the exhibit. What does the output indicate?

A.The Terraform configuration defines three resources
B.The state file tracks three resources
C.Three providers are configured
D.Three workspaces are in use
E.The plan will create three resources
AnswerB

The output of `terraform state list` explicitly displays the addresses of all resource instances that Terraform is currently managing within its state file for the active workspace. In the exhibit, three distinct resource addresses are clearly enumerated (e.g., `aws_instance.web`, `aws_s3_bucket.mybucket`, `null_resource.example`). This command's primary purpose is to provide an inventory of the resources recorded in the state, directly confirming that the state file is tracking exactly three resources.

Why this answer

The `terraform state list` command lists all resources currently tracked in the state file. Here it shows three resources: a VPC, a subnet, and an EC2 instance.

50
MCQhard

Refer to the exhibit. A user runs `terraform plan` and receives this error. The user is using a local backend. Which of the following is the most likely cause?

A.The workspace is not selected correctly.
B.The configured state file path's directory does not exist.
C.The state file is corrupted.
D.The backend is misconfigured for remote state.
AnswerB

"The configured state file path's directory does not exist." This is the correct explanation. Terraform requires the parent directory for its state file (e.g., `terraform.tfstate` by default, or a custom path specified in a `local` backend block) to exist on the file system *before* it can write or update the state file. If the directory specified in the backend configuration, or the default `.terraform` directory where state files are typically stored, is missing, Terraform cannot proceed, resulting in an error indicating the directory does not exist.

Why this answer

With a local backend, Terraform stores state in a local file, typically `terraform.tfstate`. The error indicates that the directory specified for the state file path does not exist. Terraform requires the parent directory to exist before it can write the state file; if it is missing, the plan fails with this error.

Exam trap

A common trap in Terraform exams is confusing a missing directory for the local state file with state file corruption or an incorrect workspace selection. The error typically indicates that the parent directory path does not exist, not that the file itself is unreadable.

How to eliminate wrong answers

Option A is wrong because the workspace is selected correctly by default (the `default` workspace) and a missing directory error is unrelated to workspace selection. Option C is wrong because a corrupted state file would produce a parse or checksum error, not a missing directory error. Option D is wrong because the user is explicitly using a local backend, so remote state misconfiguration is irrelevant.

51
Multi-Selectmedium

Which THREE of the following are best practices for Terraform state management in a team environment?

Select 3 answers
A.Use separate state files for different environments (dev, prod)
B.Store state files in a version control repository
C.Enable state locking to prevent concurrent modifications
D.Store state files in a remote backend shared by the team
E.Manually edit the state file to correct drift
AnswersA, C, D

Utilizing distinct state files for each environment, such as development and production, is a critical best practice. This isolation significantly reduces the "blast radius" of potential errors or accidental changes, preventing a misconfiguration in one environment from impacting another. It ensures that infrastructure changes are applied only to their intended target, enhancing stability and operational safety.

Why this answer

Best practices for Terraform state management in a team environment include using separate state files for different environments (dev, prod) to isolate changes, enabling state locking to prevent concurrent modifications and conflicts, and storing state files in a remote backend shared by the team to enable collaboration and persistence. Option B (storing state in a version control repository) is not recommended because state files can contain sensitive data and are prone to conflicts when multiple team members apply changes concurrently. The correct options are A, C, and D.

52
MCQmedium

A developer runs `terraform apply` and receives the error: 'Error acquiring the state lock'. Another engineer is currently running `terraform plan`. What should the developer do?

A.Run terraform init to reinitialize the backend
B.Wait for the lock to be released automatically
C.Run terraform force-unlock with the lock ID
D.Run terraform plan with -lock=false to bypass the lock
E.Delete the lock file from the S3 bucket
AnswerB

The lock will be released when the other engineer's plan completes. Waiting is the safest approach.

Why this answer

Terraform uses a state locking mechanism to prevent concurrent modifications that could corrupt the state file. When another engineer is running `terraform plan`, the lock is held for the duration of the plan to ensure consistency. The lock will be automatically released once the plan completes or times out, so waiting is the appropriate action.

Exam trap

A common misconception is that running `terraform force-unlock` is the standard way to resolve a lock error. In reality, this command should only be used to clear orphaned locks after confirming no other process is using the state. When another engineer is actively running `terraform plan`, the lock will be released automatically upon completion.

How to eliminate wrong answers

Option A is wrong because `terraform init` reinitializes the backend configuration but does not release or bypass an active state lock; it would fail with the same lock error. Option C is wrong because `terraform force-unlock` should only be used as a last resort when the lock is orphaned (e.g., due to a crash), not when another legitimate process holds the lock. Option D is wrong because `terraform plan -lock=false` bypasses the lock for the plan itself, but the developer is trying to run `terraform apply`, and using `-lock=false` on apply risks state corruption if another operation modifies state concurrently.

Option E is wrong because deleting the lock file from the S3 bucket is a manual, unsafe action that can lead to state corruption; Terraform manages the lock via DynamoDB (for S3 backends) and deleting it does not properly release the lock.

53
MCQeasy

Which of the following is NOT a valid backend type for storing Terraform state?

A.terraform cloud
B.local
C.kubernetes
D.s3
E.http
AnswerC

Kubernetes is not a supported Terraform backend for state storage.

Why this answer

Kubernetes is not a valid backend type for storing Terraform state. Terraform backends determine where state is stored and how operations are executed; the officially supported backends include local, remote backends like S3, HTTP, and Terraform Cloud, but Kubernetes is not among them. While Kubernetes can be used to run Terraform in a pod, it does not serve as a state storage backend.

Exam trap

A common misconception is that Kubernetes can be used as a Terraform backend because it is a container orchestration platform, but Terraform backends are specific storage mechanisms (e.g., local, S3, HTTP, Terraform Cloud) and Kubernetes is not one of them.

How to eliminate wrong answers

Option A is wrong because Terraform Cloud is a fully supported remote backend that stores state and runs operations, with features like state locking and versioning. Option B is wrong because local is the default backend that stores state on the local filesystem, and is valid for single-user or testing scenarios. Option D is wrong because S3 is a standard remote backend that stores state in an AWS S3 bucket, often paired with DynamoDB for locking.

Option E is wrong because HTTP is a valid backend that stores state via a RESTful HTTP endpoint, allowing custom state storage solutions.

54
MCQmedium

A DevOps engineer manages infrastructure with Terraform using an S3 backend with DynamoDB locking. During a `terraform apply`, the engineer's network connection drops. After reconnecting, they run `terraform plan` and get an error: "Error acquiring the state lock." The lock is from the previous session. The engineer has verified that no other operations are running. What is the appropriate next step to proceed?

A.Delete the DynamoDB table and recreate it
B.Wait 15 minutes for the lock to expire automatically
C.Use `terraform force-unlock <lock_id>` to remove the stale lock
D.Run `terraform init` to reset the backend connection
AnswerC

When a Terraform operation fails or is interrupted, it can leave behind a stale state lock in the remote backend, such as an entry in the DynamoDB table. The `terraform force-unlock <lock_id>` command is specifically designed to remove such persistent, but no longer active, lock entries. By providing the unique `lock_id`, this command directly instructs the backend to clear the specific lock, enabling subsequent Terraform operations to proceed safely.

Why this answer

`terraform force-unlock` is the intended mechanism to manually remove a stale lock from the DynamoDB table when the process that held the lock has terminated abnormally. The engineer has confirmed no other operations are running, so the lock is orphaned and safe to remove. This command requires the specific lock ID, which is provided in the error message.

Exam trap

Candidates often mistakenly think that Terraform locks have a timeout or that `terraform init` can reset backend state issues, leading them to choose waiting or reinitializing instead of using the explicit `force-unlock` command.

How to eliminate wrong answers

Option A is wrong because deleting and recreating the DynamoDB table would destroy all lock records and potentially other metadata, and is an unnecessarily destructive action that violates infrastructure-as-code best practices. Option B is wrong because Terraform's DynamoDB locks do not have a built-in expiry timeout; they persist until explicitly released or removed, so waiting 15 minutes would not resolve the issue. Option D is wrong because `terraform init` reinitializes the backend configuration and downloads providers, but does not interact with or release existing locks in DynamoDB.

55
MCQmedium

A team uses an S3 backend with DynamoDB locking. They accidentally delete the DynamoDB table used for state locking. What is the immediate consequence?

A.Terraform commands that require state locking will fail with a locking error.
B.State operations will continue without locking, risking corruption.
C.Terraform will automatically create a new DynamoDB table.
D.The state file will be migrated to local storage.
AnswerA

When the configured DynamoDB table for state locking is unavailable or missing, Terraform cannot acquire the necessary lock before executing state-modifying commands like `terraform apply` or `terraform plan`. This immediately results in a locking error, preventing any operation that could potentially corrupt the remote state file. Terraform prioritizes state integrity by failing explicitly rather than proceeding unsafely.

Why this answer

When the DynamoDB table is deleted, Terraform cannot acquire or release locks, so any command needing locking (apply, plan, destroy) will fail. Option A is correct. Option B is incorrect because Terraform will not proceed without lock; it returns an error.

Options C and D are not automatic behaviors.

56
Multi-Selecthard

A team uses an S3 backend for state storage with DynamoDB locking. They want to migrate to a new S3 bucket. Which two steps are necessary to perform a successful state migration? (Choose two.)

Select 2 answers
A.Run `terraform plan` to verify no resource changes before migration.
B.Delete the old state file after migration.
C.Run `terraform init -reconfigure` to update the backend configuration.
D.Manually copy the state file from the old bucket to the new bucket.
E.Update the `backend` block in the Terraform configuration with the new bucket name.
AnswersC, E

This command initializes the new backend and copies state.

Why this answer

`terraform init -reconfigure` forces Terraform to reinitialize the backend and apply the new backend configuration from the `backend` block without prompting for confirmation. Option E is correct because the `backend` block in the Terraform configuration must be updated to reference the new S3 bucket name; Terraform reads this block during initialization to determine where to store and retrieve state. Together, these steps ensure Terraform knows the new backend location and can properly manage state going forward.

Exam trap

A common misconception is that manually copying the state file is required or that `terraform plan` can validate backend changes, when in fact the correct workflow is to update the backend block and run `terraform init -reconfigure` to reinitialize the backend.

57
MCQmedium

A company uses Terraform to manage infrastructure across multiple AWS accounts. They want to use a single S3 bucket to store state files for all accounts, but ensure that state files are isolated per account. What is the best approach?

A.Use Terraform workspaces with a single state file
B.Use separate state files with unique S3 key prefixes per account
C.Store all state in the same S3 key
D.Use a DynamoDB table with different lock IDs per account
AnswerB

This approach correctly isolates Terraform state for each distinct AWS account. By configuring the S3 backend with unique `key` prefixes (e.g., `account-a/terraform.tfstate`, `account-b/terraform.tfstate`), each account's infrastructure state is stored in its own dedicated path within the S3 bucket. This prevents state file collisions, ensures independent management, and maintains clear separation of concerns across different environments or accounts.

Why this answer

Using separate state files with unique S3 key prefixes per account ensures that each AWS account's Terraform state is stored in the same S3 bucket but logically isolated. This approach leverages S3's hierarchical key structure to prevent cross-account state contamination, while still allowing centralized management. Terraform's backend configuration supports dynamic key prefixes (e.g., `key = "account-${var.account_id}/terraform.tfstate"`), enabling per-account isolation without requiring separate buckets or workspaces.

Exam trap

The trap here is that candidates confuse Terraform workspaces with true state isolation across accounts, not realizing that workspaces only provide logical separation within a single backend path and do not prevent cross-account state conflicts when using a shared S3 bucket.

How to eliminate wrong answers

Option A is wrong because Terraform workspaces store state files within the same backend path (same S3 key) by default, using a directory-like structure (e.g., `env:/workspace_name`), which does not provide true isolation per AWS account—state files can still be accidentally overwritten or accessed across workspaces if the backend key is not carefully managed. Option C is wrong because storing all state in the same S3 key would cause all accounts to share a single state file, leading to conflicts, corruption, and inability to manage separate infrastructure stacks. Option D is wrong because DynamoDB lock IDs are used for state locking and consistency, not for isolating state files per account; different lock IDs do not prevent state file collisions when multiple accounts write to the same S3 key.

58
MCQhard

Refer to the exhibit. A developer runs terraform plan and sees "No changes". However, the developer knows that manual changes were made to the infrastructure outside Terraform. What is the most likely reason terraform plan does not detect the drift?

A.The manual changes were made to resources not managed by Terraform.
B.Terraform only detects drift when running terraform apply.
C.The manual changes were reverted before the plan was run.
D.Terraform plan does not refresh state by default; it uses the existing state file.
AnswerA

This is the correct explanation. Terraform's `plan` command operates by comparing the desired state (from configuration files) with the actual state of *managed* resources (as recorded in the state file and refreshed from the cloud provider). If manual changes were applied to resources that were provisioned outside of Terraform's control, or to attributes of managed resources that Terraform does not explicitly track, these changes would not be reflected in the Terraform state file and thus would be invisible to `terraform plan`.

Why this answer

Terraform plan detects drift by comparing the current configuration against the state file, but only for resources that Terraform manages. If manual changes are made to resources that are not recorded in Terraform's state (i.e., resources created outside of Terraform or not imported), then plan will not detect them because those resources are unknown to Terraform. Options B, C, and D are incorrect: B is false because plan can detect drift with refresh; C is not necessarily true as the changes may still exist; D is false because modern Terraform refreshes state by default before planning, but that refresh only applies to managed resources.

Exam trap

A common mistake is assuming that `terraform plan` detects any infrastructure drift, but it only detects changes to resources that Terraform manages. Manual changes to unmanaged resources are invisible to Terraform.

How to eliminate wrong answers

Option A is wrong because even if manual changes are made to resources managed by Terraform, the plan will still show 'No changes' if the state is not refreshed — the issue is not about whether the resource is managed, but about the state being stale. Option B is wrong because Terraform can detect drift during `terraform plan` if the refresh step is enabled (which it is by default in recent versions), but the question's scenario assumes the default behavior where the plan does not refresh; `terraform apply` also refreshes by default, but drift detection is not exclusive to apply. Option C is wrong because the question explicitly states that manual changes were made and not reverted; the 'No changes' result is due to the state not reflecting those changes, not because they were undone.

59
MCQhard

After running terraform apply, you see the error: 'Error: Error loading state: state snapshot was created by Terraform v0.12.0, but this is Terraform v1.2.0'. What should you do to resolve this?

A.Run terraform state upgrade
B.Run terraform apply with no changes to upgrade the state format
C.Delete the state file and reimport resources
D.Downgrade Terraform to v0.12.0
AnswerB

When an older Terraform state file is detected by a newer version of the Terraform CLI, running `terraform apply` will automatically initiate an upgrade of the state format to the current version. Even if there are no configuration changes to apply, Terraform processes the existing state and writes it back in the updated format, resolving compatibility issues. This is the standard and recommended procedure for state file upgrades.

Why this answer

Running `terraform apply` with no changes triggers Terraform to automatically upgrade the state file format to the version compatible with the current Terraform binary (v1.2.0). Terraform state files are versioned internally, and when a newer version of Terraform reads an older state format, it performs an in-place upgrade during the next state write operation, such as an apply that results in no changes. This avoids manual intervention or data loss.

Exam trap

HashiCorp often tests the misconception that there is a dedicated `terraform state upgrade` command, leading candidates to choose Option A, but Terraform handles state format upgrades implicitly during apply operations, not via a separate command.

How to eliminate wrong answers

Option A is wrong because `terraform state upgrade` is not a valid Terraform command; the correct command for upgrading state format is `terraform apply` with no changes or `terraform init -upgrade` for provider upgrades, not a dedicated state upgrade command. Option C is wrong because deleting the state file and reimporting resources is unnecessarily destructive and error-prone; it would require manual re-import of every resource, losing any existing state metadata and risking configuration drift. Option D is wrong because downgrading Terraform to v0.12.0 is a backward step that would lose access to features and fixes in v1.2.0, and it does not resolve the version mismatch; the state file would still be in the older format and would need to be upgraded eventually.

60
MCQhard

In a CI/CD pipeline, Terraform state is stored in Terraform Cloud. A pipeline run fails with the error: 'State version conflict'. What is the most likely cause?

A.Authentication failure with Terraform Cloud
B.Missing or incorrect backend configuration
C.State file exceeds maximum size limit
D.Terraform version mismatch between local and remote
E.Two runs started at the same time
AnswerE

This is the most likely cause. When two runs are started at the same time, the second run may be based on an outdated state version because the first run's state write completes before the second run's state read. Terraform Cloud then detects the version mismatch and throws a 'State version conflict' error.

Why this answer

A 'State version conflict' in Terraform Cloud typically occurs when two runs attempt to modify the same state concurrently. Even though Terraform Cloud serializes runs via a queue, a conflict arises if a run completes before another run that started based on an older state version. Terraform Cloud detects that the state has changed externally, resulting in a version conflict.

Missing or incorrect backend configuration (option B) would cause errors like 'backend initialization required' or 'workspace not found', not specifically a state version conflict. Authentication failures (A) yield access denied errors. State size limits (C) produce size-related errors.

Version mismatches (D) cause compatibility warnings.

61
Drag & Dropmedium

Drag and drop the steps to use Terraform modules from the registry in the correct order.

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

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

Why this order

Registry modules are sourced; init downloads, variables configure, plan/apply deploy.

62
MCQhard

Refer to the exhibit. A team member receives this error when running terraform apply. What is the most likely cause?

A.The state file is corrupted and needs to be restored from backup.
B.Another user is currently running terraform apply on the same state.
C.The S3 bucket containing the state has been deleted.
D.A previous Terraform process was terminated abruptly, leaving a stale lock.
AnswerD

When a Terraform process terminates unexpectedly, it may fail to release the state lock gracefully, leaving behind a 'stale' lock entry in the backend. This stale lock can contain incomplete or malformed metadata, such as an 'OperationTypeInvalid' value, preventing subsequent Terraform commands from acquiring a new lock. The existing lock is improperly defined and not actively held by a running process, causing the error.

Why this answer

The lock info shows an operation type "OperationTypeInvalid", which typically occurs when a previous Terraform process was terminated abruptly (e.g., Ctrl+C, crash), leaving the lock in place.

63
MCQmedium

A team uses a remote state backend with partial configuration. They have a `backend` block with only the `bucket` attribute, and the rest of the backend configuration is provided via CLI during `terraform init`. Which of the following best describes the purpose of partial configuration?

A.It reduces the number of files needed for configuration.
B.It is required when using Terraform Cloud.
C.It enables state locking.
D.It allows sensitive backend configuration to be provided dynamically, avoiding hardcoding.
AnswerD

The primary advantage of partial backend configuration is its ability to facilitate the dynamic provision of sensitive backend configuration attributes. This approach allows critical credentials, such as access keys, secret tokens, or database connection strings, to be supplied at runtime via CLI arguments or environment variables. Consequently, these sensitive details are prevented from being hardcoded directly into Terraform configuration files and committed to version control, significantly enhancing security posture.

Why this answer

Partial configuration in Terraform remote state backends allows you to split backend settings between the `backend` block in your configuration and dynamic inputs provided at `terraform init` time. This is especially useful for sensitive values like access keys or secret tokens, which can be supplied via CLI flags, environment variables, or interactive prompts, thereby avoiding hardcoding them in version-controlled files. Option D correctly identifies this primary purpose of enhancing security and flexibility.

Exam trap

A common misconception is that partial configuration is primarily for reducing file count or enabling state locking, when in fact its core purpose is to allow dynamic, secure injection of sensitive backend parameters without hardcoding.

How to eliminate wrong answers

Option A is wrong because partial configuration does not reduce the number of files; it merely separates backend settings across different input sources, and you still need at least one configuration file. Option B is wrong because partial configuration is optional when using Terraform Cloud; Terraform Cloud can also use full configuration or environment variables, and it is not a requirement. Option C is wrong because state locking is enabled by the backend type (e.g., S3 with DynamoDB) and is independent of whether the backend configuration is partial or complete; partial configuration does not inherently enable or disable locking.

64
MCQhard

A company manages multiple microservices across AWS accounts. Each service has its own Terraform configuration and state file stored in a shared S3 bucket. The team uses `terraform_remote_state` data sources to read outputs from other services' state files. A service team recently changed the output structure in their state, breaking the `terraform_remote_state` calls from other services. The affected services now show errors during plan. What is the best practice to avoid such cross-service dependency issues?

A.Publish service outputs to a dedicated data store (e.g., AWS SSM Parameter Store or Consul) and have other services consume those values instead of reading state directly
B.Use versioning on the S3 bucket and revert to a previous state version
C.Lock the state files and require approval for any changes
D.Store outputs in a configuration management database and read from there
AnswerA

Publishing service outputs to a dedicated data store like AWS SSM Parameter Store or HashiCorp Consul provides a robust mechanism for inter-service communication. This approach effectively decouples Terraform configurations, preventing direct dependencies on another service's remote state file, which can be fragile and prone to breaking changes. By consuming values from a stable, versioned API, services can reliably access necessary parameters without needing direct read access to potentially sensitive or rapidly evolving state files. This promotes a more resilient and scalable microservices architecture.

Why this answer

The best practice is to decouple services by using a dedicated data store (e.g., AWS SSM Parameter Store or Consul) as a service registry or contract. This avoids tight coupling to the internal state representation of another service. Option A correctly implements this pattern.

Option D (CMDB) is overly generic and not specifically designed for Terraform state outputs. Options B and C are reactive measures, not proactive best practices.

Ready to test yourself?

Try a timed practice session using only Implement and maintain state questions.