Courseiva

CCNA Use Terraform outside the core workflow Questions

75 of 80 questions · Page 1/2 · Use Terraform outside the core workflow · Answers revealed

1
MCQeasy

A team needs to share a Terraform module across multiple projects within their organization. What is the best practice?

A.Use a remote module source such as a Git repository.
B.Copy the module code into each project's directory.
C.Use 'terraform state push' to share state.
D.Use workspace variables to store module code.
AnswerA

Leveraging a remote Git repository as a module source allows teams to centralize module definitions, promoting reusability and consistency across multiple projects. This approach enables robust version control, ensuring that all consuming projects can pin to specific module versions, facilitating controlled updates and preventing unexpected changes. Terraform's `source` attribute directly supports Git URLs, making this a standard and highly effective method for module sharing and management.

Why this answer

Using a remote module source such as a Git repository is the best practice because it allows the module to be versioned, centrally maintained, and consumed by multiple projects without duplication. Terraform's module system supports sources like Git, Mercurial, and HTTP URLs, enabling teams to pin specific versions via tags or refs, ensuring consistency across environments.

Exam trap

A common pitfall is confusing state sharing or workspaces with module distribution. State and workspaces are runtime constructs, not code sharing mechanisms, whereas a remote module source allows centralized version control.

How to eliminate wrong answers

Option B is wrong because copying module code into each project's directory leads to configuration drift, duplicated maintenance, and violates the DRY (Don't Repeat Yourself) principle; Terraform modules are designed to be sourced remotely, not copied. Option C is wrong because 'terraform state push' is used to manually upload state to a configured backend, not to share module code; state files contain resource metadata, not module definitions. Option D is wrong because workspace variables store input values for workspaces, not module code; module code must be sourced from a defined module source, not from variable assignments.

2
MCQeasy

What is the purpose of the 'terraform validate' command?

A.To check the validity of provider credentials.
B.To format Terraform configuration files.
C.To check syntax and internal consistency of configuration files.
D.To run unit tests on Terraform modules.
AnswerC

The `terraform validate` command performs a crucial static analysis of the Terraform configuration files in the current working directory. It meticulously checks for correct HashiCorp Configuration Language (HCL) syntax, ensuring all required arguments are present and correctly typed. Furthermore, it verifies the internal consistency of the configuration, confirming that all references between resources, variables, and outputs are resolvable and adhere to the provider's schema without needing to connect to any remote state or cloud provider APIs.

Why this answer

The 'terraform validate' command checks the syntax and internal consistency of Terraform configuration files, ensuring that the code is syntactically valid and that references between resources, data sources, and variables are correctly formed. It does not interact with providers or cloud APIs, so it cannot verify credentials or run tests.

Exam trap

HashiCorp often tests the distinction between 'validate' (syntax/consistency check) and 'plan' (which actually contacts providers and checks real-world state), leading candidates to mistakenly think 'validate' verifies credentials or remote resources.

How to eliminate wrong answers

Option A is wrong because 'terraform validate' does not check provider credentials; credential validation occurs during 'terraform init' or 'terraform plan' when the provider attempts to authenticate with the cloud API. Option B is wrong because formatting Terraform files is the purpose of 'terraform fmt', not 'validate'. Option D is wrong because 'terraform validate' does not execute unit tests; testing modules is done with external tools like Terratest or the 'terraform test' command (introduced in later versions), not with 'validate'.

3
MCQmedium

Refer to the exhibit. An operator runs terraform plan and gets the following output. They have not modified the Terraform configuration since the last successful apply. What is the most likely cause of the planned changes?

A.Terraform provider was updated to a new version.
B.The instance was terminated and recreated.
C.Terraform state was corrupted.
D.The instance was modified manually via the AWS console.
AnswerD

When an infrastructure resource managed by Terraform is altered directly through the cloud provider's console or API, its actual state diverges from the desired state defined in the Terraform configuration and the last known state recorded in the Terraform state file. Running `terraform plan` detects this 'drift' by comparing the actual infrastructure's current attributes with the desired state, then proposing actions to reconcile them, such as updating the attribute back to its configured value.

Why this answer

When terraform plan shows changes but the configuration was not modified, the most common cause is out-of-band drift — someone changed the resource directly in the AWS console (or via CLI/another tool), so the real infrastructure no longer matches the recorded state. Terraform compares desired config to state, and state to real resources, so manual changes surface as planned updates to bring the resource back to the declared configuration.

Exam trap

TF-004 often tests the assumption that any unexpected plan change must be a Terraform bug or state corruption, when the far more common cause is manual out-of-band modification of the resource.

How to eliminate wrong answers

Option A is wrong because a provider version update alone does not change resource attributes unless the schema or defaults changed, and it would not typically produce this drift pattern. Option B is wrong because if the instance had been terminated and recreated, Terraform would show a destroy/create or replacement plan, not a simple in-place update. Option C is wrong because a corrupted state file usually produces errors, missing resources, or a full re-create plan — not a clean, targeted diff on one attribute.

4
Multi-Selecthard

Which THREE of the following are capabilities of Terraform Cloud's Sentinel policy framework? (Choose three.)

Select 3 answers
A.Block Terraform runs based on the time of day
B.Enforce that resources have mandatory tags
C.Check that resources comply with security best practices
D.Restrict the creation of certain resource types
E.Estimate the cost of infrastructure changes
AnswersB, C, D

Sentinel can inspect planned resource attributes and reject configurations lacking required tags, enforcing the stem's tagging mandate before apply. This is a policy-as-code capability operating on the Terraform plan, not a runtime or post-deployment control.

Why this answer

Sentinel is a policy-as-code framework embedded in Terraform Cloud that evaluates plan data before apply, so option B is correct because a policy can inspect planned resource attributes and fail the run when required tags (e.g., CostCenter, Environment) are missing. Option C is correct because Sentinel policies can encode organizational security rules—such as requiring encrypted S3 buckets, private subnets, or approved instance types—and reject non-compliant plans. Option D is correct because Sentinel can match on resource type (e.g., aws_instance, azurerm_virtual_machine) and forbid or conditionally allow their creation.

Option A is not a Sentinel capability because policies evaluate Terraform configuration/plan data, not wall-clock scheduling; time-based run control would come from CI/CD or API triggers. Option E is not a Sentinel capability because cost estimation in Terraform Cloud is provided by the separate cost estimation feature (run tasks/infracost-style integrations), not by Sentinel policy logic.

Exam trap

The trap here is that candidates may confuse Sentinel's policy enforcement with Terraform Cloud's other features, such as cost estimation or run triggers, and incorrectly assume Sentinel can handle time-based or cost-related logic natively.

5
Multi-Selecthard

Which THREE of the following are necessary steps to configure OIDC (OpenID Connect) for authenticating Terraform in a CI/CD pipeline?

Select 3 answers
A.Generate a long-lived API token and store it as a secret.
B.Set up an OIDC provider in the target cloud (e.g., AWS IAM OIDC provider).
C.Configure remote backend with static credentials.
D.Add a provider block with assume_role and web_identity_token attributes in Terraform configuration.
E.Create an IAM role in the cloud that the CI job can assume.
AnswersB, D, E

Setting up an OIDC provider in the target cloud, such as an AWS IAM OIDC provider, is a foundational step. This establishes a trust relationship where the cloud environment explicitly trusts identity tokens issued by your CI/CD system (the OIDC issuer). Without this configured trust anchor, the cloud would have no mechanism to verify the authenticity or validity of the identity tokens presented by your CI/CD pipeline.

Why this answer

To authenticate Terraform in a CI/CD pipeline using OIDC, you must first establish trust between the CI platform and the cloud provider by creating an OIDC identity provider (e.g., an AWS IAM OIDC provider). This provider validates the JSON Web Token (JWT) issued by the CI platform (e.g., GitHub Actions, GitLab CI) and maps it to an IAM role, enabling token-based authentication without long-lived secrets.

Exam trap

HashiCorp often tests the misconception that OIDC requires storing a long-lived token (Option A) or that the remote backend must use static credentials (Option C), when in fact OIDC replaces both with a trust-based, token-exchange mechanism that uses the `assume_role` and `web_identity_token` attributes.

6
MCQhard

A company uses Terraform to manage multi-cloud infrastructure. They have separate Terraform configurations for AWS and Azure, each with its own state file. They want to share a common set of networking variables (e.g., allowed IP ranges) between these configurations without duplicating data. Which approach best achieves this?

A.Create a module that contains the variable definitions and reference it in both configurations.
B.Define the variables in a 'terraform.tfvars' file and copy it to each configuration directory.
C.Store the variables in a JSON file and use the 'jsondecode' function in each configuration.
D.Use a remote state data source to read the outputs from a dedicated 'globals' workspace.
AnswerD

Using a remote state data source to read outputs from a dedicated 'globals' workspace is the most robust solution for sharing common configuration values. A 'globals' workspace can define and manage these shared parameters as its outputs, which are then securely stored in a remote state backend. Other Terraform configurations can then use the `terraform_remote_state` data source to directly consume these outputs, establishing a single, version-controlled source of truth and eliminating data duplication.

Why this answer

Using a remote state data source allows you to read outputs from a dedicated 'globals' Terraform workspace that stores shared networking variables. This approach avoids data duplication and ensures that both AWS and Azure configurations can dynamically consume the same canonical set of values without manual copying or file sharing. It leverages Terraform's native remote state mechanism to securely and consistently share data across separate configurations.

Exam trap

HashiCorp often tests the misconception that modules or variable files can share actual runtime data between separate configurations, when in fact they only define structure or require manual distribution, whereas remote state data sources provide dynamic, centralized sharing without duplication.

How to eliminate wrong answers

Option A is wrong because creating a module with variable definitions only provides a reusable template for declaring variables; it does not share actual values between configurations, so each configuration would still need to supply its own data. Option B is wrong because copying a 'terraform.tfvars' file to each configuration directory duplicates the data, violating the requirement to avoid duplication and introducing drift risk. Option C is wrong because storing variables in a JSON file and using 'jsondecode' still requires the file to be present in each configuration's working directory, leading to duplication and synchronization challenges.

7
Multi-Selectmedium

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

Select 3 answers
A.Manually edit state files to fix configuration drift.
B.Commit state files to version control.
C.Use workspaces to manage different environments.
D.Store state file in a remote backend with locking enabled.
E.Use 'terraform state rm' to remove resources from state when needed.
AnswersC, D, E

Terraform workspaces provide a robust mechanism for managing multiple distinct environments, such as development, staging, and production, using the same configuration code. Each workspace maintains its own isolated state file, preventing resource conflicts and accidental modifications across environments. This isolation ensures that changes intended for one environment do not inadvertently affect another, promoting safer and more organized infrastructure deployments without duplicating configuration files.

Why this answer

Terraform workspaces allow you to manage multiple distinct state files for the same configuration, enabling environment separation (e.g., dev, staging, prod) without duplicating code or backends. Each workspace maintains its own state, preventing cross-environment interference and simplifying infrastructure lifecycle management.

Exam trap

HashiCorp often tests the misconception that state files should be version-controlled like code, but the trap is that state files contain sensitive data and are not idempotent, making remote backends with locking the correct practice.

8
MCQmedium

Your team stores Terraform state in an AWS S3 bucket and uses DynamoDB for state locking. A junior engineer runs `terraform apply` locally while a CI pipeline is also running `terraform apply` against the same state. The apply succeeds in both cases, but the resulting infrastructure is inconsistent and resources are missing from state. What is the most likely cause?

A.The `terraform apply` command was run with the `-parallelism=1` flag, which disabled locking.
B.The DynamoDB table was created in a different region than the S3 bucket, so locking was not enforced.
C.The S3 backend was configured without `dynamodb_table`, so state locking was not enabled.
D.The S3 bucket versioning was disabled, so Terraform could not read the latest state file.
AnswerC

Without the `dynamodb_table` argument in the S3 backend configuration, Terraform cannot acquire a lock, allowing concurrent applies to overwrite each other's state. Both applies succeed independently, but the final state reflects only one run's view, leaving resources untracked. This matches the symptom of inconsistent infrastructure and missing resources after simultaneous applies.

Why this answer

State locking prevents concurrent operations from modifying the same state file simultaneously. When the S3 backend is configured without a `dynamodb_table`, Terraform cannot acquire a lock, so two applies can run at once. Each apply reads the state, plans changes, and writes back, overwriting the other's updates.

This leads to a state file that does not reflect all created resources, causing drift and inconsistencies.

Exam trap

The trap here is assuming that S3 backend automatically provides locking, when in fact locking requires an explicitly configured DynamoDB table.

9
MCQmedium

A company uses Terraform Cloud and wants to enforce policy checks before any apply. They have a set of Sentinel policies. Where should they configure these policies to run automatically on all runs?

A.In the terraform apply command with -policy flag.
B.Configure a webhook in the VCS to run policy checks.
C.Create a Policy Set in Terraform Cloud and attach to workspaces.
D.Deploy a Terraform Enterprise instance with custom policy.
AnswerC

Terraform Cloud enforces policies through Policy Sets, which are collections of Sentinel or OPA policies designed to evaluate infrastructure plans. To enforce a specific policy, an administrator must create a Policy Set, add the desired policy to it, and then attach that Policy Set to the relevant workspaces. During a Terraform Cloud run, these policies are evaluated after the plan phase and before the apply phase, blocking non-compliant infrastructure changes from being provisioned.

Why this answer

Terraform Cloud uses Policy Sets to group Sentinel policies and enforce them automatically on all runs for attached workspaces. When a Policy Set is associated with one or more workspaces, the policies are evaluated during the plan phase before any apply, blocking the run if any policy fails. This is the native mechanism in Terraform Cloud for automated policy enforcement without manual intervention.

Exam trap

The trap here is that candidates confuse the VCS webhook trigger (which starts a run) with the policy enforcement mechanism, or mistakenly think Sentinel policies can be invoked via CLI flags, when in fact Terraform Cloud requires Policy Sets attached to workspaces for automatic policy checks.

How to eliminate wrong answers

Option A is wrong because the `terraform apply` command does not support a `-policy` flag; Sentinel policies are evaluated server-side in Terraform Cloud, not via CLI flags. Option B is wrong because webhooks in the VCS trigger runs but do not execute policy checks; policy enforcement is handled by Terraform Cloud's built-in policy engine, not external webhooks. Option D is wrong because deploying a Terraform Enterprise instance is unnecessary when Terraform Cloud already provides Sentinel policy enforcement; the question specifies the company uses Terraform Cloud, so a separate TFE deployment is not required.

10
MCQhard

Refer to the exhibit. A user encounters this error while running 'terraform plan'. What is the best course of action?

A.Run 'terraform force-unlock' with the lock ID after verifying no other process holds the lock
B.Change the backend to local and run plan again
C.Delete the state file and run terraform init
D.Wait for 5 minutes and retry
AnswerA

When Terraform encounters a state lock, it prevents concurrent operations that could corrupt the state file. If a previous operation failed or was interrupted, the lock might persist, becoming "stale." The `terraform force-unlock <LOCK_ID>` command is specifically designed to release such a stale lock, but it must only be used after confirming that no other legitimate Terraform process is actively holding the lock to prevent state corruption.

Why this answer

The error indicates that the state file is locked, which prevents concurrent operations to avoid corruption. Running 'terraform force-unlock' with the lock ID is the correct recovery step, but only after verifying that no other Terraform process is actively using the state. This command releases the lock from the backend (e.g., S3, Consul, or Terraform Cloud), allowing subsequent plans or applies to proceed.

Exam trap

Terraform exams often test the misconception that waiting or changing backends is a safe workaround, when in fact only verifying the lock holder and then using 'force-unlock' is the proper recovery procedure.

How to eliminate wrong answers

Option B is wrong because changing the backend to local would bypass the remote state lock but also lose the shared state, potentially causing state conflicts or data loss in a team environment. Option C is wrong because deleting the state file destroys all tracked infrastructure state, leading to orphaned resources or requiring a full re-import; it does not address the lock itself. Option D is wrong because the lock does not automatically expire after a fixed time; it persists until explicitly released via 'force-unlock' or the holding process completes, so waiting is ineffective.

11
MCQmedium

An organization wants to use Terraform to manage infrastructure in multiple environments (dev, staging, prod) with the same configuration but different variable values. Which approach should they use?

A.Create separate directories with duplicated configurations
B.Use Terraform workspaces and separate variable files
C.Use a single state file with environment variables
D.Use different versions of Terraform for each environment
AnswerB

Terraform workspaces allow for managing multiple distinct states for a single configuration, effectively isolating environments like `dev`, `staging`, and `prod` within the same codebase. By combining workspaces with separate `*.tfvars` files for each environment, organizations can reuse the core infrastructure definition while providing environment-specific values for variables. This method ensures state isolation and parameter differentiation without duplicating the underlying configuration, promoting consistency and maintainability.

Why this answer

Terraform workspaces allow you to manage multiple distinct sets of infrastructure resources within the same configuration by maintaining separate state files. By combining workspaces with separate variable definition files (e.g., `dev.tfvars`, `prod.tfvars`), you can reuse the same configuration code while applying environment-specific variable values, avoiding duplication and ensuring consistency across environments.

Exam trap

HashiCorp often tests the misconception that workspaces are the only way to manage multiple environments, but the trap here is that candidates may overlook the need for separate variable files alongside workspaces, or incorrectly think that a single state file with environment variables is sufficient for isolation.

How to eliminate wrong answers

Option A is wrong because creating separate directories with duplicated configurations violates the DRY (Don't Repeat Yourself) principle, leading to configuration drift and increased maintenance overhead. Option C is wrong because using a single state file with environment variables would cause all environments to share the same state, resulting in conflicts and potential corruption when applying changes concurrently. Option D is wrong because using different versions of Terraform for each environment introduces unnecessary complexity and version incompatibility risks, and Terraform version does not solve the need for separate state or variable isolation.

12
Multi-Selectmedium

Which THREE are valid methods to create and manage Terraform workspaces?

Select 3 answers
A.Using version control branches
B.Using tags in AWS
C.Using 'terraform workspace' commands (new, select, delete)
D.Using the Terraform Cloud API
E.Using the Terraform Cloud web UI
AnswersC, D, E

The `terraform workspace` CLI commands provide direct, granular control over local and remote Terraform workspaces. Specifically, `terraform workspace new <name>` creates a new workspace, `terraform workspace select <name>` switches the current working context to an existing one, and `terraform workspace delete <name>` removes a workspace. These commands are fundamental for isolating different environments or stages of infrastructure within a single Terraform configuration, managing their respective state files.

Why this answer

Option C is correct because the Terraform CLI provides the native 'terraform workspace' subcommands — 'terraform workspace new', 'terraform workspace select', and 'terraform workspace delete' — which create, switch between, and remove workspaces within a working directory, storing state per workspace. Option D is correct because Terraform Cloud exposes a REST API that lets you programmatically create, list, and delete workspaces (e.g., via the /organizations/:organization_name/workspaces endpoints), enabling automation and CI/CD integration. Option E is correct because the Terraform Cloud web UI allows users to create and manage workspaces through the graphical interface, including setting variables, VCS connections, and team access.

Option A is not a valid Terraform mechanism: version control branches are a general Git practice and are not tied to Terraform workspace state management. Option B is not valid either: AWS tags are metadata applied to cloud resources and have no role in creating or managing Terraform workspaces.

Exam trap

The Terraform exam often tests the distinction between Terraform's native workspace commands and external tools like version control or cloud provider tags, trapping candidates who confuse code management with state management.

13
MCQmedium

A team is using Terraform Cloud and wants to enforce that all AWS resources created by Terraform have a specific tag. Which feature should they use?

A.Cost estimation
B.Sentinel policies
C.Workspace variables
D.Run tasks
AnswerB

Sentinel policies enforce policy-as-code within Terraform Cloud, evaluating planned changes against rules such as mandatory AWS tags and blocking non-compliant runs before apply. This provides governance across all workspaces, unlike manual review or provider defaults.

Why this answer

Sentinel policies are Terraform Cloud's policy-as-code framework that allows teams to enforce mandatory rules on infrastructure configurations before they are applied. By writing a Sentinel policy that checks for the presence and value of a specific tag on all AWS resources, the team can reject any run that does not comply, ensuring consistent tagging across all resources created by Terraform.

Exam trap

Candidates often confuse Sentinel policies (native policy-as-code in Terraform Cloud) with run tasks (which integrate external tools). Sentinel is the correct choice for enforcing mandatory tags directly within Terraform Cloud's workflow.

How to eliminate wrong answers

Option A is wrong because cost estimation provides a forecast of the cost of resources defined in a plan but does not enforce tagging or any other compliance rules. Option C is wrong because workspace variables store configuration values like region or credentials but cannot enforce policies or validate resource attributes. Option D is wrong because run tasks allow integration with external systems for custom checks or notifications, but they are not a built-in feature for writing and enforcing policy rules like Sentinel; run tasks rely on external tooling and do not natively support policy-as-code for tagging enforcement.

14
MCQmedium

A team uses Terraform Cloud for remote state management. They want to ensure that state file changes are only made through the Terraform Cloud API and not through direct access to the storage backend. Which feature should they enable?

A.Sentinel policy enforcement
B.Remote state locking
C.VCS integration
D.Team tokens
AnswerB

Remote state locking is a critical mechanism within Terraform Cloud that ensures state modifications occur exclusively through its controlled API. When a Terraform operation (like a plan or apply) begins, Terraform Cloud acquires a lock on the state, preventing concurrent modifications and ensuring consistency. This lock is managed by Terraform Cloud, effectively forcing all state-altering operations to pass through its API, thereby preventing any direct, uncontrolled access or modification of the state file.

Why this answer

Remote state locking ensures that only one operation can modify the Terraform state at a time. When using Terraform Cloud as the remote backend, locking is automatically managed and prevents any direct modifications to the state file outside of a Terraform run. Because Terraform Cloud handles locking through its API, any attempt to directly access the storage backend would fail to acquire a lock, thus preventing changes.

This effectively enforces that all state modifications go through the Terraform Cloud API.

Exam trap

The trap is that many candidates assume Sentinel policy enforcement is needed to prevent direct state modifications, but Terraform Cloud's remote backend automatically uses state locking, which ensures only API-based changes are possible.

How to eliminate wrong answers

Option B is wrong because remote state locking prevents concurrent operations on the same state file but does not prevent direct access to the storage backend; it only manages locking during Terraform runs. Option C is wrong because VCS integration automates runs from version control commits but does not restrict direct state file access via the storage backend API. Option D is wrong because team tokens authenticate API calls but do not enforce that state changes must originate from the Terraform Cloud API; they can be used to directly access the storage backend if permissions allow.

15
MCQeasy

An operator runs `terraform apply` and receives an error that the state file is locked. What is the most likely cause?

A.The state file is outdated and needs refresh
B.The configuration has a syntax error
C.Another user is running a Terraform operation
D.The user lacks write permissions to the state file
AnswerC

Terraform state locking is a critical mechanism designed to prevent data corruption when multiple operators attempt to modify the state file concurrently. When one user initiates a `terraform apply` or other state-modifying operation, Terraform attempts to acquire an exclusive lock on the state. If another user is already holding that lock, the subsequent operation will fail with a state lock error, indicating that the state is currently in use and preventing simultaneous, conflicting updates.

Why this answer

Terraform uses a state locking mechanism (typically via a backend like S3 with DynamoDB, or Consul) to prevent concurrent operations from corrupting the state file. When another user or process is running a Terraform operation (e.g., `apply`, `plan`, `destroy`), the lock is held, and any subsequent `terraform apply` will fail with a 'state file is locked' error. This is a fundamental safety feature to ensure state consistency.

Exam trap

The trap here is that candidates confuse state locking with file permissions (Option D) or assume the error is due to a stale state (Option A), but The TF-003 exam specifically tests the understanding that locking is a concurrency control mechanism, not a permission or syntax issue.

How to eliminate wrong answers

Option A is wrong because an outdated state file does not cause a lock error; it would instead cause a refresh prompt or drift detection, not a lock conflict. Option B is wrong because a syntax error in the configuration would be caught during `terraform validate` or `plan`, not during `apply` as a state lock error. Option D is wrong because insufficient write permissions would result in a permissions error (e.g., 'AccessDenied' or 'permission denied'), not a lock error; locking is a separate mechanism from filesystem permissions.

16
Multi-Selectmedium

Which TWO are valid methods to import existing infrastructure into Terraform?

Select 2 answers
A.Use 'terraform state rm' to remove existing state before running apply.
B.Run 'terraform import' with the resource address and ID.
C.Use 'terraform console' to inspect and import.
D.Add resource blocks manually and run 'terraform import' for each resource.
E.Use 'terraform init -migrate-state' to import from another backend.
AnswersB, D

Running 'terraform import' with the resource address and ID is a correct and fundamental method for bringing existing infrastructure under Terraform's management. This command explicitly takes a pre-existing cloud resource, identified by its unique cloud provider ID, and associates it with a corresponding resource block defined in the Terraform configuration. This action adds the resource's details to the state file, allowing Terraform to manage its lifecycle going forward.

Why this answer

`terraform import` is the primary command for bringing existing infrastructure under Terraform management. It requires both the resource address (as defined in your configuration) and the provider-specific ID of the real-world object. This command maps the existing resource into the Terraform state, enabling subsequent `apply` operations to manage it.

Exam trap

Candidates often mistakenly believe that `terraform import` automatically generates configuration code, but it only updates the state file. You must manually write the resource block before running import.

17
MCQhard

A team has a monolithic Terraform configuration managing multiple AWS accounts. They want to decompose it into smaller configurations that can be managed independently. What is the recommended strategy?

A.Split the configuration into separate directories per account and resource type, and use remote state sharing.
B.Use Terraform workspaces to separate environments within the same configuration.
C.Create a single super-module that contains all resources.
D.Move everything to Terraform Cloud and use different workspaces.
AnswerA

Splitting a monolithic configuration into separate directories, perhaps by account or resource type, creates smaller, more manageable units of infrastructure. Each directory then manages its own independent state file, typically stored remotely (e.g., S3, Azure Blob Storage, Terraform Cloud). This approach allows different teams or individuals to work on distinct parts of the infrastructure concurrently without interfering with others, facilitating independent deployment, testing, and lifecycle management for specific components or environments. It directly addresses the challenges of a monolithic setup by promoting modularity and reducing blast radius.

Why this answer

Splitting a monolithic Terraform configuration into separate directories per account and resource type, combined with remote state sharing, enables independent management of each configuration while allowing them to consume outputs from one another via `terraform_remote_state` data sources. This approach aligns with the recommended practice of using separate root modules for distinct environments or accounts, avoiding tight coupling and state lock contention.

Exam trap

A common misconception in the Terraform exam is that Terraform workspaces (or Terraform Cloud workspaces) are a valid decomposition strategy, but they only separate state files for the same configuration, not the configuration itself, which fails the requirement for independent management.

How to eliminate wrong answers

Option B is wrong because Terraform workspaces are designed for managing multiple environments (e.g., dev, staging, prod) within the same configuration and state backend, but they do not decompose a monolithic configuration into independently managed pieces; all resources still reside in a single state file per workspace, which defeats the goal of independent management. Option C is wrong because creating a single super-module that contains all resources would increase complexity and coupling, making independent management impossible and violating modular design principles. Option D is wrong because moving to Terraform Cloud and using different workspaces is essentially the same as using local workspaces—it does not decompose the configuration into smaller, independently managed configurations; it only shifts the state management to a remote service without addressing the monolithic structure.

18
MCQeasy

A small startup is using Terraform to deploy AWS resources. They have two separate environments: development and production. Currently, they manage two sets of Terraform configuration files in different directories, each with its own state file stored locally. The CEO wants to reduce duplication and simplify management. The team decides to restructure into a single configuration with workspaces. After implementing workspaces, they run `terraform workspace new dev` and `terraform workspace new prod`, then `terraform apply` in the dev workspace. However, when they switch to prod and run `terraform apply`, the plan shows that Terraform wants to recreate all resources instead of managing the existing production resources. What is the most likely reason for this behavior?

A.Workspaces cannot be used for different environments; only for temporary feature branches.
B.The Terraform configuration uses the same resource names in both workspaces, causing conflicts.
C.The team did not migrate the existing production state into the 'prod' workspace.
D.The team must configure a remote backend for workspaces to function correctly.
AnswerC

This is the correct explanation. When a new workspace, such as 'prod', is created, it initializes with an empty state file, meaning it has no knowledge of existing infrastructure. Any pre-existing production resources are not automatically associated with this new workspace; their state must be explicitly migrated or imported into the 'prod' workspace's state file using commands like `terraform state mv` or `terraform import` to bring them under Terraform management within that specific context.

Why this answer

When the team restructured into a single configuration with workspaces, they created new empty workspaces (`dev` and `prod`) but did not migrate the existing production state file into the `prod` workspace. Terraform workspaces maintain separate state files, so without importing the existing production state into the `prod` workspace, Terraform has no record of the existing production resources and plans to create them from scratch. The `terraform workspace new` command creates a fresh, empty state for that workspace.

Exam trap

HashiCorp often tests the misconception that workspaces automatically inherit or share state from previous configurations, when in fact each workspace starts with a completely empty state unless explicitly migrated.

How to eliminate wrong answers

Option A is wrong because workspaces are explicitly designed to manage multiple environments (e.g., dev, staging, prod) from a single configuration, not just for temporary feature branches. Option B is wrong because resource names within a workspace are scoped to that workspace's state; using the same resource names across workspaces does not cause conflicts—each workspace maintains its own independent state. Option D is wrong because while remote backends are recommended for team collaboration, workspaces function perfectly well with local backends; the issue here is the missing state migration, not the backend type.

19
MCQeasy

A developer needs to inspect the current state of a specific resource managed by Terraform without modifying any infrastructure. Which command should they use?

A.`terraform state show aws_instance.example`
B.`terraform refresh`
C.`terraform plan`
D.`terraform output`
AnswerA

The `terraform state show` command displays the attributes of a single resource in the state file. It is read-only and does not modify infrastructure or state. This allows the developer to inspect details such as IDs, IP addresses, and tags for the specified resource, fulfilling the requirement to view current state without changes.

Why this answer

The `terraform state show` command is designed to display the attributes of a single resource in the state file. It is read-only and does not alter infrastructure or state. Other commands like `refresh` modify state, `plan` shows planned changes, and `output` displays only defined outputs.

Therefore, `state show` is the correct choice for inspecting a specific resource without modifications.

Exam trap

The trap here is confusing `terraform state show` with `terraform show`, which displays the entire state or a plan file, not a single resource.

20
MCQeasy

Refer to the exhibit. Which command was most likely executed?

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

terraform init is the foundational command responsible for preparing a Terraform working directory for use. It performs several critical setup tasks, including discovering and downloading necessary provider plugins, configuring the backend for state storage, and recursively downloading all modules referenced in the configuration. The command's output explicitly includes messages like "Initializing modules," "Initializing provider plugins," and "Initializing the backend," directly matching the exhibit's likely "Initializing modules" output.

Why this answer

The exhibit shows Terraform downloading and installing provider plugins (e.g., hashicorp/aws) and initializing the backend configuration. This is the exact behavior of `terraform init`, which prepares the working directory for other commands by ensuring all required providers and modules are available.

Exam trap

The exam often tests the distinction between `terraform init` (which handles provider and backend setup) and `terraform get` (which only handles modules), leading candidates to confuse module downloading with provider initialization.

How to eliminate wrong answers

Option A is wrong because `terraform apply` executes the infrastructure changes defined in the configuration, not downloading providers or initializing backends. Option B is wrong because `terraform plan` creates an execution plan by comparing the current state with the configuration, but does not download providers or initialize backends. Option C is wrong because `terraform get` downloads and updates modules referenced in the configuration, but does not initialize backends or install provider plugins.

21
MCQmedium

An organization uses Terraform Cloud and wants to automate run triggers when a new version of a module is published in a private module registry. What is the recommended method?

A.Create a Git repository with versioned modules and use GitOps.
B.Configure a webhook in the private module registry to notify Terraform Cloud.
C.Schedule terraform plan to run periodically via cron.
D.Use the Terraform Cloud API to poll the registry for new versions.
AnswerB

Configuring a webhook in the private module registry allows for real-time, event-driven automation. When a new module version is published, the registry sends an HTTP POST request to a pre-configured endpoint in Terraform Cloud, notifying it of the change. This enables Terraform Cloud to immediately detect the new version and potentially trigger runs in workspaces that consume that module, facilitating seamless, automated updates without manual intervention or polling.

Why this answer

Terraform Cloud supports webhook notifications from private module registries. When a new module version is published, the registry can send an HTTP POST payload to a configured webhook URL in Terraform Cloud, which triggers a run in the associated workspace. This eliminates the need for polling or manual intervention, aligning with Terraform Cloud's event-driven automation model.

Exam trap

The trap is that candidates often confuse GitOps workflows (Option A) with Terraform Cloud's native webhook integration. Terraform Cloud uses webhooks from its own module registry (or Terraform Enterprise) to trigger runs when a new module version is published, not from general Git repository events.

How to eliminate wrong answers

Option A is wrong because Git repositories with versioned modules and GitOps workflows are not directly integrated with Terraform Cloud's run triggers; they require manual or CI/CD pipeline steps to initiate runs, not automatic triggers upon module publication. Option C is wrong because scheduling `terraform plan` via cron is inefficient, introduces latency, and does not provide real-time triggering when a new module version is published; it also wastes resources on unnecessary plan runs. Option D is wrong because polling the Terraform Cloud API for new module versions is not a recommended pattern; it adds complexity, API rate limits, and latency compared to the push-based webhook mechanism.

22
MCQhard

A company uses Terraform with a remote backend (AWS S3). They want to ensure that the state file is encrypted at rest. Which configuration approach guarantees this?

A.Configure the S3 backend with server-side encryption enabled (e.g., 'encrypt = true' and 'kms_key_id').
B.Enable encryption in the AWS provider block.
C.Use 'terraform state encrypt' command.
D.Use 'terraform init -encrypt-state' flag.
AnswerA

Enabling server-side encryption on the S3 backend satisfies the encryption-at-rest constraint, since Terraform delegates state storage to S3 and AWS encrypts objects before writing them to disk. Specifying `kms_key_id` uses SSE-KMS for customer-managed key control, while `encrypt = true` alone applies SSE-S3. Encryption therefore occurs at the storage layer, independent of Terraform itself.

Why this answer

The S3 backend configuration block supports the `encrypt` and `kms_key_id` arguments, which enable server-side encryption (SSE-S3 or SSE-KMS) for the state file stored in the S3 bucket. This ensures that the state file is encrypted at rest, meeting the requirement without any additional steps or external commands.

Exam trap

The trap here is that candidates confuse provider-level encryption settings (which don't exist) with backend-level encryption, or assume a CLI flag like `-encrypt-state` exists, when in fact encryption must be explicitly declared in the backend configuration block.

How to eliminate wrong answers

Option B is wrong because the AWS provider block configures authentication and region settings, not storage-level encryption; it has no effect on S3 server-side encryption for the state file. Option C is wrong because there is no `terraform state encrypt` command in Terraform; state encryption is handled at the backend level, not via a CLI subcommand. Option D is wrong because `terraform init` does not support an `-encrypt-state` flag; encryption is configured in the backend block, not during initialization.

23
MCQeasy

Refer to the exhibit. A team deploys this configuration. They run 'terraform apply' once and the instance is created. Later, they modify the instance type and run 'terraform apply' again. They notice the provisioner does not run on the second apply. Why?

A.Provisioners run only when the resource is destroyed.
B.The provisioner should be 'remote-exec' to run on updates.
C.The command syntax is incorrect.
D.Provisioners run only when the resource is created, not on subsequent updates.
AnswerD

Terraform provisioners are tied to resource lifecycle events, executing only during creation or destruction. Changing the instance type triggers an in-place update, not a recreate, so the creation-time provisioner is skipped on the second apply.

Why this answer

Provisioners in Terraform are designed to run only during resource creation, not during subsequent updates. When the instance type is modified and 'terraform apply' is run again, Terraform updates the existing resource in place without triggering the provisioner again. This behavior is intentional because provisioners are typically used for initial setup tasks like bootstrapping, not for ongoing configuration changes.

Exam trap

Terraform often tests the misconception that provisioners run on every 'terraform apply' regardless of the resource lifecycle, leading candidates to overlook the creation-only default behavior.

How to eliminate wrong answers

Option A is wrong because provisioners can run on creation, not only on destruction; they can also run on destroy if the 'on_failure' and 'when' attributes are set appropriately. Option B is wrong because the type of provisioner (local-exec vs remote-exec) does not affect whether it runs on updates; both types only run on creation by default. Option C is wrong because the command syntax is not the issue; the question explicitly states the instance is created successfully on the first apply, so the syntax is correct.

24
MCQmedium

Refer to the exhibit. The user runs 'terraform plan' and sees that Terraform wants to create the instance. However, the instance already exists in the AWS account with the same configuration. What is the most likely reason?

A.The instance type has changed
B.The instance is not in the Terraform state
C.The AMI ID has changed
D.The provider version is different
AnswerB

Terraform's `plan` command operates by comparing the desired state defined in the configuration files with the actual state recorded in its state file and the real-world infrastructure. If an `aws_instance` resource is defined in the configuration but is entirely absent from the Terraform state file, Terraform will interpret this as a new resource that needs to be provisioned. Consequently, even if an identical instance physically exists in AWS, Terraform will propose to `create` it because it has no record of managing that existing resource.

Why this answer

Terraform determines whether to create, update, or destroy resources by comparing the desired configuration in the .tf files against the current state stored in the state file. If the instance already exists in AWS but is not recorded in the Terraform state, Terraform has no knowledge of it and will plan to create a new resource. This is the most likely reason because the instance is present in the account but absent from the state, causing Terraform to treat it as a new resource.

Exam trap

The Terraform exam often tests the misconception that Terraform automatically detects existing resources in the cloud provider, but in reality Terraform relies entirely on its state file to know what it manages, and any resource not in the state is treated as new regardless of its existence in the cloud.

How to eliminate wrong answers

Option A is wrong because if the instance type had changed, Terraform would detect a drift and plan to update (modify) the existing resource, not create a new one. Option C is wrong because a changed AMI ID would also result in a planned update or replacement (destroy and recreate), not a pure create action. Option D is wrong because a different provider version might cause compatibility warnings or errors, but it would not cause Terraform to ignore an existing resource in the state; the state file is version-independent for resource tracking.

25
MCQhard

A company uses Terraform Cloud and wants to ensure that only approved modules from the private registry are used in configurations. How can they enforce this?

A.Restrict module sources in VCS
B.Configure workspace variables to limit module paths
C.Use Sentinel policies to check module sources
D.Use run tasks to scan for module types
AnswerC

Sentinel policies provide a robust, native policy-as-code framework within Terraform Cloud, designed to inspect the Terraform plan and enforce organizational governance rules before infrastructure changes are applied. By writing a Sentinel policy, an organization can directly access the `tfplan` data, specifically evaluating attributes like `tfplan.module_calls[*].source` to identify and validate all module sources being used. If an unauthorized module source is detected, the policy can be configured to soft-fail (warn) or hard-fail (block) the Terraform run, ensuring only approved modules are deployed.

Why this answer

Sentinel is HashiCorp's policy-as-code framework that can enforce governance rules on Terraform Cloud runs. By writing a Sentinel policy that inspects the `module` block's `source` attribute, you can restrict configurations to only use modules from the approved private registry, rejecting any run that references external or unapproved sources.

Exam trap

HashiCorp often tests the distinction between run tasks (external integrations) and Sentinel (native policy engine), leading candidates to incorrectly choose run tasks for in-plan policy enforcement when Sentinel is the correct answer.

How to eliminate wrong answers

Option A is wrong because restricting module sources in VCS (e.g., via branch protection or file patterns) does not prevent a user from committing a configuration that references an unapproved module source; VCS controls operate at the code storage layer, not at the Terraform plan/apply execution layer. Option B is wrong because workspace variables cannot limit module paths; variables are used to parameterize configurations, not to enforce source restrictions on module declarations. Option D is wrong because run tasks are external integrations that can perform arbitrary checks or actions (e.g., security scans), but they do not have native access to parse and enforce module source constraints within the Terraform plan; Sentinel policies are the designated mechanism for policy enforcement in Terraform Cloud.

26
Multi-Selecteasy

Which TWO of the following are valid ways to pass variables to Terraform in an automated pipeline?

Select 2 answers
A.Creating a .tfvars file and referencing it with -var-file.
B.Using interactive prompts during terraform apply.
C.Using the -var flag to specify individual variables.
D.Setting environment variables with prefix TERRAFORM_.
E.Using the -vars flag to pass JSON string.
AnswersA, C

Creating a .tfvars file, such as `production.tfvars`, allows for defining multiple input variables in a structured key-value format. This file can then be explicitly loaded using the `terraform plan -var-file=production.tfvars` or `terraform apply -var-file=production.tfvars` command-line flag. This method is highly effective for managing environment-specific configurations or large sets of variables, promoting reusability and version control of variable definitions.

Why this answer

Option A is correct because Terraform supports variable definition files (commonly with a .tfvars or .tfvars.json extension), and you can explicitly load one with the -var-file flag, e.g. terraform apply -var-file="prod.tfvars", which is ideal for automated pipelines where the file is committed or generated by the CI/CD system. Option C is correct because the -var flag lets you pass individual input variables directly on the command line, e.g. terraform apply -var="instance_type=t3.micro", which works non-interactively and is therefore suitable for pipeline execution. Option B is not valid for automation because interactive prompts require a human to type values at the terminal, which defeats unattended pipeline runs.

Option D is incorrect because Terraform reads input variables from environment variables prefixed with TF_VAR_, not TERRAFORM_. Option E is incorrect because there is no -vars flag in Terraform; the correct flags are -var and -var-file.

Exam trap

HashiCorp often tests the exact environment variable prefix (`TF_VAR_` vs `TERRAFORM_`) and the existence of non-existent flags like `-vars`, expecting candidates to confuse them with similar-sounding options from other tools.

27
MCQmedium

You are managing a Terraform configuration that deploys resources across multiple AWS accounts using provider aliases. The configuration uses a single backend (S3) to store the state file. Recently, you discovered that the state file has become very large (over 100 MB) and is causing slow operations and timeouts. The team wants to improve performance without losing the ability to manage all resources with a single `terraform apply`. You need to propose a solution. Which approach should you take?

A.Use state encryption to compress the state file
B.Switch the backend from S3 to Terraform Cloud to improve performance
C.Use Terraform workspaces to separate environments into different state files
D.Split the configuration into separate directories for each environment
AnswerB

Switching to Terraform Cloud provides a managed backend that can handle large state files efficiently with built-in state locking, remote execution, and caching. This allows you to continue using a single `terraform apply` to manage all resources.

Why this answer

Switching to Terraform Cloud can improve performance with large state files due to its optimized backend, remote state management, and built-in caching. It allows you to continue managing all resources with a single `terraform apply` command, as Terraform Cloud handles state operations efficiently. This approach does not require splitting the state file or using multiple workspaces, thus preserving the ability to apply all changes in one operation.

Exam trap

A common misconception is that Terraform workspaces allow a single `terraform apply` to manage all resources. In reality, each workspace requires its own apply, so workspaces do not satisfy the requirement of a single apply command.

How to eliminate wrong answers

Option A is wrong because state encryption (e.g., using AWS KMS) does not compress the state file; it only encrypts it at rest, so the file size remains unchanged and performance issues persist. Option B is wrong because switching to Terraform Cloud does not inherently reduce state file size; it may improve backend performance but the underlying large state file still causes slow operations. Option D is wrong because splitting the configuration into separate directories would require running `terraform apply` separately for each directory, breaking the requirement to manage all resources with a single `terraform apply`.

28
MCQeasy

A small startup uses Terraform to manage infrastructure on AWS. They store the state file directly in a Git repository (gitignored but accidentally committed) and have no remote backend. The team has two engineers: Alice and Bob. They both run Terraform from their local machines. Recently, they experienced state conflicts where Alice's apply would succeed but subsequently Bob's apply would fail due to state drift. They want a simple solution without adding too much complexity. What should they do?

A.Add the state file to .gitignore and stop versioning it.
B.Configure an S3 backend with DynamoDB locking and have both engineers use the remote state.
C.Continue with the current setup but ask Alice and Bob to coordinate via Slack before running apply.
D.Switch to Terraform Cloud with remote execution for automated locking.
AnswerB

Configuring an S3 backend centralizes the Terraform state file, establishing a single, authoritative source of truth accessible to all team members, which is crucial for collaborative infrastructure management. Integrating DynamoDB for state locking ensures that only one `terraform apply` operation can modify the state at any given time, effectively preventing concurrent changes from causing state corruption or overwriting each other's work. This combination is the industry standard for maintaining state consistency and preventing race conditions in shared environments.

Why this answer

Configuring an S3 backend with DynamoDB locking provides a remote state file that both engineers can access, along with state locking to prevent concurrent modifications. This directly solves the state conflicts without adding excessive complexity. Option A (adding .gitignore) does not address the conflict issue since the state is still local and not shared.

Option C (coordination via Slack) is unreliable and does not prevent race conditions. Option D (Terraform Cloud) is a valid solution but adds more complexity than the simple S3+DynamoDB setup, which is the recommended approach for small teams.

29
Multi-Selecteasy

Which TWO of the following are valid ways to use Terraform outside the core workflow? (Choose two.)

Select 2 answers
A.Using Terraform to manage application secrets lifecycle.
B.Using Terraform outputs as inputs for other tools like Ansible.
C.Using Terraform to install software on existing servers.
D.Using Terraform as a CI/CD pipeline tool.
E.Using Terraform state to generate infrastructure diagrams.
AnswersB, E

Terraform outputs provide a structured and machine-readable mechanism to expose specific values derived from the managed infrastructure, such as newly provisioned IP addresses, DNS names, or resource IDs. These exposed values are easily consumed by other automation tools, including configuration management systems like Ansible, custom scripts, or subsequent stages in a CI/CD pipeline, enabling seamless integration and data flow between different components of an automation stack.

Why this answer

Terraform outputs can be consumed by other tools like Ansible via the `terraform output` command or by referencing the state file, enabling integration in multi-tool workflows. Option E is correct because the Terraform state file (`.tfstate`) contains all resource attributes and dependencies, which can be parsed programmatically or with tools like `terraform graph` to generate infrastructure diagrams, extending Terraform's use beyond provisioning.

Exam trap

HashiCorp often tests the distinction between provisioning (Terraform) and configuration management (Ansible, Chef), so candidates mistakenly think Terraform can install software or manage secrets, when it is strictly for infrastructure lifecycle and state-driven outputs.

30
MCQhard

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

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

Sentinel policies enforce policy-as-code within Terraform Cloud, evaluating planned infrastructure against rules before apply. This satisfies the stem's constraint that only t2.micro or t2.small EC2 instance types are permitted, blocking non-compliant plans during the run rather than relying on post-deployment detection.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

31
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

32
MCQmedium

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

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

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

Why this answer

A CI/CD pipeline that runs terraform init with the correct backend configuration and restricts runs to the pipeline prevents developers from accidentally initializing with a local backend, which is the root cause of the drift. By centralizing init and plan/apply in an automated, auditable environment, the remote S3 backend and DynamoDB lock table are always used, and local state files cannot be created. This is the only option that structurally prevents the mistake rather than detecting it after the fact.

Exam trap

TF-004 often tests the misconception that state locking or workspace commands protect against backend misconfiguration, when in fact only enforcing the correct backend at init time prevents local state creation.

How to eliminate wrong answers

Option A is wrong because enabling state locking on a local backend does not prevent a developer from initializing locally — it only serializes access to the local state file, which is not the problem. Option C is wrong because 'terraform plan -check' is not a real Terraform command and does not warn about non-remote state; there is no such built-in check. Option D is wrong because switching workspaces does not affect which backend is used — the backend is determined at init time, so the developer would still be operating against local state.

33
Multi-Selectmedium

Which TWO Terraform backends support remote state locking?

Select 2 answers
A.s3
B.local
C.consul
D.inmem
E.http
AnswersA, C

The S3 backend leverages Amazon DynamoDB to provide robust remote state locking. When a Terraform operation requires a lock, it attempts to acquire it by writing a lock entry to a designated DynamoDB table. DynamoDB's strong consistency guarantees ensure that only one operation can successfully acquire the lock at any given time, preventing concurrent modifications to the remote state file stored in S3 and safeguarding against state corruption.

Why this answer

The S3 backend (A) supports remote state locking by using a DynamoDB table to acquire and release a lock, which prevents concurrent Terraform runs from corrupting state; this is configured via the dynamodb_table argument. The Consul backend (C) also supports remote state locking natively, since Consul's key-value store provides a locking mechanism (sessions and acquire/release operations) that Terraform uses to lock the state path. The local backend (B) stores state on the local filesystem and does not provide remote locking, only local file-based locking.

The inmem backend (D) keeps state in memory for testing purposes and offers no locking. The http backend (E) is a read-only backend for retrieving state over HTTP and does not support state locking.

Exam trap

The Terraform certification exam often tests the misconception that all remote backends support locking, but only a subset (S3, Consul, and a few others like AzureRM and GCS) implement native locking mechanisms.

34
MCQhard

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

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

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

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

35
MCQhard

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

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

Working on a feature branch means pushes do not touch main, so the VCS-backed auto-trigger never fires. Only the pull-request merge into main starts a run, letting the team fix the tag and validate via the PR plan before any apply occurs.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

36
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

37
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

38
Multi-Selecteasy

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

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

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

Why this answer

Option B is correct because a remote backend (for example, an S3 bucket, Azure Storage Account, GCS bucket, or Terraform Cloud workspace) stores the Terraform state file in a shared, remote location rather than on the local machine, allowing teams to collaborate on the same infrastructure. Option E is correct because most remote backends support state locking — such as S3 with a DynamoDB table, Azure Blob Storage, or Consul — which prevents concurrent runs from corrupting the state file. Option A is incorrect because migrating state to a remote backend is typically handled automatically by running `terraform init` with the new backend configuration, which offers to copy existing local state; manual migration is not a requirement.

Option C is incorrect because storing state in the local filesystem describes the default local backend, not a remote backend. Option D is incorrect because Terraform Cloud itself is a supported remote backend (configured via the `cloud` block or `remote` backend), so remote backends can absolutely be used with it.

Exam trap

TF-004 often tests the misconception that remote backends require manual state migration or that Terraform Cloud is incompatible with remote backends — both are false, and candidates who don't know 'terraform init -migrate-state' pick the wrong answer.

39
Multi-Selecthard

Which THREE are valid use cases for the 'terraform state replace-provider' command?

Select 3 answers
A.Migrating a provider from one registry to another (e.g., from registry.terraform.io to a private registry).
B.Upgrading the provider to a new major version.
C.Changing the provider's configuration region from us-east-1 to eu-west-1.
D.Migrating from a community provider to an official provider.
E.Changing the provider source from one namespace to another (e.g., hashicorp/aws to mycompany/aws).
AnswersA, D, E

Migrating a provider between registries requires rewriting every stored provider address in state, since Terraform resolves providers by registry-qualified source address. The replace-provider command performs exactly this state-wide substitution, updating the recorded provider references without touching real infrastructure, satisfying the registry-migration use case.

Why this answer

Option A is correct because 'terraform state replace-provider' rewrites the provider source address recorded in the state file, which is exactly what is needed when a provider moves from registry.terraform.io to a private registry. Option D is correct because migrating from a community provider to an official provider is a change of provider source address in state, and this command updates those references without forcing resource re-creation. Option E is correct because changing the provider source from one namespace to another (e.g., hashicorp/aws to mycompany/aws) is precisely the provider address substitution the command performs.

Option B is not correct because upgrading a provider to a new major version is done by changing the version constraint and running 'terraform init -upgrade', not by replacing the provider source in state. Option C is not correct because changing a provider's configuration region is a configuration change in the provider block, not a state provider address replacement.

Exam trap

The exam often tests the distinction between state-level provider address changes (source/registry) versus configuration-level changes (version, region, or provider block attributes), and candidates mistakenly think `state replace-provider` can handle version upgrades or configuration edits.

40
MCQhard

An organization uses Terraform Cloud with a VCS-backed workspace connected to a GitHub repository. They want to trigger a speculative plan without creating a run (i.e., without costing compute resources or being displayed in the workspace). Which approach is appropriate?

A.Push a new commit to the GitHub repository with a 'plan' label.
B.Use the 'plan -out' flag with a special path to avoid creating a run.
C.Use the Terraform Cloud API to queue a plan with 'auto-apply' disabled.
D.Run 'terraform plan' from a local CLI configured with the same workspace and a remote backend.
AnswerD

When the local Terraform CLI is configured with a remote backend (like Terraform Cloud) and targets a specific workspace, executing `terraform plan` by default performs the plan operation locally. It fetches the remote state and configuration but executes the planning logic on the local machine without initiating a formal "run" in Terraform Cloud's UI or run history. This allows for quick, iterative validation of changes without consuming Terraform Cloud run credits or cluttering the run history.

Why this answer

Running 'terraform plan' from a local CLI configured with the same workspace and a remote backend triggers a speculative plan that is computed on Terraform Cloud but does not create a run record or consume run credits. This allows the user to preview changes without affecting the workspace's run history or incurring costs.

Exam trap

The trap here is that candidates confuse 'speculative plans' with regular runs, assuming any plan triggered from a local CLI will create a run record, when in fact the remote backend distinguishes between speculative and non-speculative plans based on the command context.

How to eliminate wrong answers

Option A is wrong because pushing a commit with a 'plan' label would trigger a VCS-driven run in Terraform Cloud, which creates a full run record and consumes compute resources. Option B is wrong because the 'plan -out' flag generates a plan file locally or in the remote backend, but it still creates a run in Terraform Cloud when used with a remote backend, and there is no special path to avoid run creation. Option C is wrong because using the Terraform Cloud API to queue a plan with 'auto-apply' disabled still creates a run object in the workspace, which is displayed and consumes compute resources.

41
MCQhard

A DevOps team manages infrastructure for a large e-commerce platform using Terraform with a remote backend in an S3 bucket with DynamoDB state locking. Recently, a team member ran `terraform apply` from their local machine but the command failed with the error: 'Error acquiring the state lock: ConditionalCheckFailedException: The conditional request failed'. The state file is not locked according to the DynamoDB table. After investigation, the team finds that the DynamoDB table has a TTL attribute enabled on the 'LockID' field, and old lock records are automatically deleted after a few minutes. The team suspects that another engineer's `terraform plan` process from a CI/CD pipeline might have created a lock that was subsequently deleted by TTL before it was released, causing the conflict. Which action should the team take to prevent this issue from recurring?

A.Switch to using local state files to avoid the locking issue entirely.
B.Disable the TTL attribute on the DynamoDB table that stores lock information.
C.Increase the TTL value to 24 hours to ensure locks are not deleted during normal operations.
D.Use `terraform force-unlock` before each `terraform apply` to clear any stale locks.
AnswerB

Disabling the Time-To-Live (TTL) attribute on the DynamoDB table used for Terraform state locking is the correct solution. TTL automatically deletes items after a specified period, which can prematurely remove an active lock if a `terraform apply` operation takes longer than the TTL duration. This premature deletion would allow another concurrent operation to acquire a lock, leading to potential state corruption or resource conflicts. Ensuring locks persist until explicitly released by Terraform prevents such race conditions.

Why this answer

The error occurs because the DynamoDB table has a TTL attribute that automatically deletes lock records before the lock is released. Disabling TTL on the DynamoDB table ensures lock records persist until the lock is intentionally released, preventing false lock conflicts. Option A is incorrect because local state eliminates locking and central management.

Option C is incorrect because increasing TTL only delays deletion but does not guarantee the lock won't be deleted during a long-running operation. Option D is incorrect because force-unlock is a manual recovery step, not a preventive measure.

42
MCQeasy

A developer wants to use a module from the Terraform Registry in their configuration. Which block is required in the root module?

A.module "my-module" { source = "..." }
B.resource "my-module" { ... }
C.provider "my-module" { source = "..." }
D.data "my-module" { ... }
AnswerA

The `module` block is the correct and exclusive construct for calling a reusable collection of Terraform configurations. It encapsulates a set of resources, data sources, and other modules, promoting reusability and organization within your infrastructure code. The mandatory `source` argument specifies the module's origin, which can be the Terraform Registry, a local path, or a remote Git repository, enabling Terraform to fetch and utilize its defined infrastructure components.

Why this answer

To use a module from the Terraform Registry, you must declare a `module` block in your root configuration. The `source` argument inside that block specifies the module's location (e.g., a registry path like `hashicorp/consul/aws`). This is the only way Terraform knows to fetch, version, and instantiate the module's resources.

Exam trap

A common trap in Terraform is confusing the `module` block with a `resource` block. Some candidates incorrectly think modules are declared as resources or data sources, but the correct syntax is `module "<name>" { source = "..." }`. The `source` argument is required to locate the module, and without it Terraform cannot fetch and instantiate the module's resources.

How to eliminate wrong answers

Option B is wrong because `resource` blocks define infrastructure objects (e.g., `aws_instance`), not external modules; a module is not a resource type. Option C is wrong because `provider` blocks configure providers (e.g., `aws`), not modules; the `source` argument is invalid in a provider block. Option D is wrong because `data` blocks fetch read-only information from existing resources, not from modules; modules can contain data sources, but the block itself cannot reference a module.

43
MCQeasy

A team is migrating from using local state to a remote backend for collaboration. They want to ensure that team members cannot overwrite each other's changes. Which feature should they enable?

A.State locking (e.g., DynamoDB)
B.S3 bucket versioning
C.Force unlock command
D.Workspace isolation
AnswerA

When migrating to a remote backend, state locking is essential to prevent concurrent Terraform operations from corrupting the shared state file. This mechanism ensures that only one `terraform apply` or `terraform plan` operation can modify the state at any given time. Backends like S3, when configured with DynamoDB for locking, acquire an exclusive lock before modifying the state, releasing it upon completion. This critical feature maintains state integrity in collaborative environments.

Why this answer

State locking prevents concurrent modifications by ensuring that only one operation can modify the Terraform state at a time. When using a remote backend like S3 with DynamoDB, Terraform acquires a lock before writing to the state file and releases it after completion, preventing race conditions and state corruption.

Exam trap

HashiCorp often tests the distinction between state locking (preventing concurrent writes) and state versioning (enabling rollback), causing candidates to confuse S3 versioning as a solution for overwrite prevention.

How to eliminate wrong answers

Option B is wrong because S3 bucket versioning tracks changes and allows recovery of previous state versions, but does not prevent concurrent writes or overwrites. Option C is wrong because the force unlock command is a manual override to release a stuck lock, not a feature to prevent overwrites. Option D is wrong because workspace isolation separates state files for different environments but does not coordinate access within the same workspace.

44
MCQhard

During a `terraform apply`, the operation fails mid-way due to a network outage, leaving some resources created. The operator wants to resume applying from where it left off without destroying the already-created resources. What should they do?

A.Run terraform apply again
B.Run terraform destroy and then apply
C.Run terraform refresh
D.Run terraform apply -auto-approve
AnswerA

Running `terraform apply` again reconciles actual infrastructure against the state file, creating only the missing resources and leaving existing ones untouched. Terraform's declarative model makes this idempotent, satisfying the stem's requirement to resume without destroying already-created resources after the network outage interrupted the operation.

Why this answer

Terraform uses a state file to track the resources it manages. When `terraform apply` fails mid-way, the state file is updated to reflect the resources that were successfully created. Running `terraform apply` again will cause Terraform to compare the current state with the configuration, detect that the already-created resources exist, and proceed to create only the remaining resources, effectively resuming from where it left off without destroying anything.

Exam trap

The trap here is that candidates may think a failed apply requires a full destroy or refresh, but Terraform's state-driven design allows idempotent resumption, and the exam tests understanding that `terraform apply` is the correct command to re-run after any partial failure.

How to eliminate wrong answers

Option B is wrong because `terraform destroy` would delete all resources, including those already created, which defeats the goal of resuming without destruction. Option C is wrong because `terraform refresh` only updates the state file to match real-world infrastructure; it does not create any resources or resume a failed apply. Option D is wrong because `terraform apply -auto-approve` simply skips the interactive approval prompt; it does not change the core behavior of the apply command and would still work correctly, but the key issue is that the operator must run `terraform apply` again, and the `-auto-approve` flag is irrelevant to the question's focus on resuming without destruction.

45
MCQhard

A CI/CD pipeline runs 'terraform plan' and needs to automatically approve only if no resources will be destroyed. Which approach should be used?

A.Run 'terraform apply -auto-approve' after a successful plan.
B.Run 'terraform plan -destroy' and check the exit code.
C.Run 'terraform fmt' to check for formatting issues.
D.Run 'terraform validate' to ensure no destroys are needed.
E.Run 'terraform plan -out=plan.tfplan', then 'terraform show -json plan.tfplan' and parse the output for destroy actions.
AnswerE

This is the correct and recommended approach for programmatically inspecting a Terraform plan for specific actions. First, 'terraform plan -out=plan.tfplan' saves the detailed execution plan to a binary file. Subsequently, 'terraform show -json plan.tfplan' converts this binary plan into a machine-readable JSON format. This JSON output contains a comprehensive breakdown of all proposed changes, including resource creations, updates, and crucially, destructions, which can then be parsed by a CI/CD pipeline to detect and flag any destroy actions.

Why this answer

Running terraform plan -out=plan.tfplan saves the plan in a binary format, and terraform show -json plan.tfplan converts it to machine-readable JSON that includes resource_changes with actions like 'delete' or 'delete, create' (replace). The pipeline can then parse this JSON to detect any destroy actions and gate approval accordingly. This is the only option that programmatically inspects the plan for destroy operations before applying.

Exam trap

TF-004 often tests whether candidates know that terraform validate and terraform fmt do NOT inspect planned changes — only the JSON output of a saved plan reveals destroy actions.

How to eliminate wrong answers

Option A is wrong because terraform apply -auto-approve blindly applies whatever the plan contains, including destructive changes — it does not check for destroys. Option B is wrong because terraform plan -destroy generates a plan to destroy all resources, which is the opposite of what is needed and does not detect destroys in a normal plan. Option C is wrong because terraform fmt only reformats HCL files and has nothing to do with detecting resource destruction.

Option D is wrong because terraform validate only checks syntax and internal consistency of configuration, not the planned actions against state.

46
MCQmedium

A developer accidentally deleted a resource from the Terraform state file using 'terraform state rm'. The resource still exists in the cloud provider. How can the developer re-import the resource without affecting other resources?

A.Re-run 'terraform apply' to recreate the resource.
B.Use 'terraform state push' with a previous state backup.
C.Run 'terraform refresh' to discover and add the resource.
D.Use 'terraform import' with the resource address and ID.
AnswerD

"terraform import" is specifically designed to bring existing infrastructure resources, which were created outside of Terraform or are no longer tracked by its state, under Terraform's management. It requires the resource's Terraform address (e.g., `aws_instance.web`) and its unique identifier from the cloud provider (e.g., `i-0abcdef1234567890`). This command adds the resource to the state file, allowing Terraform to manage it going forward.

Why this answer

`terraform import` is the designated command to bring an existing cloud resource back under Terraform management without affecting other resources. It requires the resource address (as defined in the configuration) and the provider-specific resource ID, allowing Terraform to write the current state into the state file without modifying the actual infrastructure.

Exam trap

A common misconception is that `terraform refresh` can automatically discover and add untracked resources, when in fact it only updates state for resources already in the state file.

How to eliminate wrong answers

Option A is wrong because `terraform apply` would attempt to recreate the resource from scratch, which could cause downtime or duplicate resources if the existing resource is not destroyed first. Option B is wrong because `terraform state push` is used to overwrite the entire state file with a local state file, not to selectively re-import a single resource; using a previous state backup would revert all state changes, potentially losing other intentional modifications. Option C is wrong because `terraform refresh` only updates the state file with the current attributes of resources already tracked in state; it cannot discover or add a resource that was removed from the state file.

47
MCQhard

You are a platform engineer at a large e-commerce company that uses Terraform Enterprise to manage thousands of infrastructure resources across multiple teams. The company has a central 'networking' workspace that provisions shared VPCs and subnets, and several application workspaces that consume these networking resources via remote state data sources. Recently, the networking team changed the CIDR block of a shared subnet from '10.0.1.0/24' to '10.0.2.0/24' and applied the change successfully. However, the application teams are now reporting that their Terraform runs are failing with errors indicating that the subnet ID they reference does not exist. The application workspaces use the following configuration to consume the subnet: ```hcl data "terraform_remote_state" "networking" { backend = "remote" config = { organization = "mycompany" workspaces = { name = "networking" } } } resource "aws_instance" "app" { subnet_id = data.terraform_remote_state.networking.outputs.subnet_id ... } ``` The application workspaces have not been modified recently. The networking workspace output 'subnet_id' now contains the ID of the updated subnet. What is the most likely cause of the failures?

A.The application workspaces do not have permission to read the networking workspace's state.
B.The networking workspace output variable 'subnet_id' was removed or renamed.
C.The application workspaces are using a cached version of the remote state outputs and need to run 'terraform plan' to refresh.
D.The application workspaces need to update the remote state data source to reference the new subnet ID.
AnswerC

When Terraform references a remote state data source, it fetches the state data at the beginning of a `terraform plan` or `terraform apply` run and caches it for the duration of that specific operation. If the upstream networking workspace's state changes *after* the application workspace's last `plan` or `apply`, the application workspace will continue to use its locally cached, now stale, version of the `subnet_id`. A new `terraform plan` execution is required to re-fetch and update this cached remote state data.

Why this answer

Terraform caches remote state data during the planning phase, and the `terraform_remote_state` data source only fetches the latest state when `terraform plan` or `terraform apply` is executed. Since the application workspaces have not been modified or re-planned, they are using a stale cached version of the networking workspace's outputs, which still contains the old subnet ID. Running `terraform plan` forces a refresh of the remote state data, retrieving the updated `subnet_id` and resolving the error.

Exam trap

The trap here is that candidates may assume the remote state data source always reads the latest state on every run, when in fact Terraform caches the data from the last plan and only refreshes it during a new plan or apply operation.

How to eliminate wrong answers

Option A is wrong because if the application workspaces lacked permission to read the networking workspace's state, the error would be an authorization failure (e.g., 403 Forbidden), not a 'subnet ID does not exist' error. Option B is wrong because the scenario explicitly states that the networking workspace output 'subnet_id' now contains the ID of the updated subnet, meaning the output was not removed or renamed. Option D is wrong because the remote state data source configuration does not need to be updated; it already references the correct workspace and output name, and the issue is simply that the cached data is stale.

48
MCQmedium

A company has a Terraform configuration that creates many AWS resources. They want to check the estimated cost of the plan before applying. Which approach should they use?

A.Use 'terraform plan -cost' command.
B.Manually use 'terraform show -json' and parse pricing.
C.Enable cost estimation in Terraform Cloud.
D.Use 'terraform validate' with a custom script.
AnswerC

Terraform Cloud offers native cost estimation capabilities, particularly for AWS resources, by integrating directly into the planning workflow. When a "terraform plan" is executed in Terraform Cloud, it analyzes the proposed resource changes against current cloud provider pricing data. This feature provides an estimated monthly cost impact directly within the plan output, offering a streamlined and automated solution for financial oversight.

Why this answer

Terraform Cloud provides a built-in cost estimation feature that analyzes the resources in a plan against current cloud provider pricing APIs to estimate monthly costs. This is the recommended approach because it is integrated directly into the Terraform workflow and does not require manual parsing or external scripts. Option C is correct because it leverages Terraform Cloud's native capability to estimate costs before applying.

Exam trap

Terraform often tests the misconception that 'terraform plan' has a built-in cost flag, but no such flag exists in the Terraform CLI; cost estimation is exclusively a Terraform Cloud feature.

How to eliminate wrong answers

Option A is wrong because 'terraform plan -cost' is not a valid Terraform CLI command; the Terraform CLI does not have a built-in cost estimation flag. Option B is wrong because while 'terraform show -json' outputs the plan in JSON format, manually parsing it and integrating with pricing APIs is error-prone, unsupported, and not a standard or recommended approach. Option D is wrong because 'terraform validate' only checks configuration syntax and internal consistency, not cost estimation, and a custom script would not be integrated with Terraform's workflow or pricing data.

49
MCQeasy

Which Terraform command is used to validate the syntax of configuration files without accessing any cloud provider?

A.terraform validate
B.terraform fmt
C.terraform plan
D.terraform init
AnswerA

The `terraform validate` command performs a static analysis of the configuration files in the current working directory. It checks for syntactical correctness of the HashiCorp Configuration Language (HCL), verifies proper variable usage, and ensures internal consistency of resource and data source references. This crucial step identifies configuration errors early, without requiring any network calls to cloud providers or interacting with remote state, making it the ideal command for purely syntax validation.

Why this answer

`terraform validate` checks syntax and internal consistency of configuration files. `init` initializes backends and providers, `plan` accesses remote state, `fmt` formats code.

50
MCQeasy

A developer wants to see the list of resources currently managed by Terraform in the state file. Which command should they use?

A.terraform graph
B.terraform output
C.terraform show
D.terraform state list
AnswerD

The `terraform state list` command is precisely designed to enumerate all resources and data sources currently tracked within the Terraform state file. It provides a clean, hierarchical list of resource addresses (e.g., `aws_instance.web`, `aws_s3_bucket.my_bucket`), making it the most direct and efficient way to see exactly which infrastructure components Terraform is managing. This command directly addresses the developer's need for a simple, concise list of managed resources without displaying their full configurations.

Why this answer

`terraform state list` is the dedicated command to list all resources tracked in the Terraform state file. It reads the state directly and outputs the resource addresses (e.g., `aws_instance.web`), giving the developer a clear view of what Terraform currently manages.

Exam trap

The trap here is that candidates confuse `terraform show` (which dumps the full state) with `terraform state list` (which provides a concise, filtered list of resource addresses), leading them to pick C instead of D.

How to eliminate wrong answers

Option A is wrong because `terraform graph` generates a visual dependency graph of resources in DOT format, not a list of state-managed resources. Option B is wrong because `terraform output` displays only the output values defined in the configuration, not the full list of resources in the state. Option C is wrong because `terraform show` displays the state or plan file in a human-readable format, but it shows the entire state content (including attributes and metadata), not a simple list of resource addresses.

51
MCQmedium

Based on the exhibit, what will happen to the existing Elastic IP (aws_eip.web_eip) when this plan is applied?

A.It will remain unchanged
B.It will be updated in-place
C.It will be created
D.It will be destroyed
AnswerD

The '-' symbol in a Terraform plan output unambiguously signifies that the associated resource will be destroyed or removed from the managed infrastructure. This action typically occurs when a resource is removed from the Terraform configuration, or when a change to its attributes necessitates its replacement (destroy and then create). Consequently, the existing 'elastic' resource will be destroyed as indicated by this symbol.

Why this answer

The Terraform configuration shows that the `aws_eip.web_eip` resource is no longer defined in the configuration after the plan is applied. Terraform will detect that the resource exists in the state but is absent from the configuration, and by default, it will destroy the Elastic IP to reconcile the state with the configuration. This is standard Terraform behavior for resources removed from `.tf` files.

Exam trap

HashiCorp often tests the misconception that removing a resource from configuration leaves it unchanged in the cloud, but Terraform's default behavior is to destroy any resource not present in the configuration, unless lifecycle rules or `removed` blocks are used.

How to eliminate wrong answers

Option A is wrong because Terraform does not leave orphaned resources; if a resource is removed from the configuration, it will be destroyed unless explicitly protected with `prevent_destroy` or `lifecycle` settings. Option B is wrong because in-place updates occur only when the resource still exists in the configuration but has attribute changes; here the resource is entirely absent, so no update is possible. Option C is wrong because the resource already exists in the state (as indicated by the exhibit showing an existing Elastic IP), so Terraform will not create a new one; it will destroy the existing one.

52
MCQhard

A Terraform configuration uses a module from the public registry. After a provider update, the module's resources fail to create. What is the most probable cause?

A.The provider binary is corrupted
B.The state file is corrupted
C.The module is incompatible with the new provider version
D.The backend configuration is incorrect
AnswerC

When a Terraform configuration uses a module that was developed against an older provider version, upgrading the provider can introduce breaking changes. The module's internal resources might rely on arguments, attributes, or behaviors that have been deprecated, removed, or altered in the newer provider version. This incompatibility would specifically manifest as errors during resource creation or update within that module, as the provider no longer understands or supports the module's requested configuration.

Why this answer

C is correct because modules from the public registry often declare a `required_providers` block with version constraints. When the provider is updated outside those constraints (e.g., from v3.x to v4.x), the module may rely on deprecated attributes or changed resource schemas, causing resource creation to fail. Terraform will not automatically adjust module code to match provider API changes.

Exam trap

HashiCorp often tests the misconception that provider updates are always backward-compatible, leading candidates to incorrectly suspect state corruption or backend misconfiguration instead of module-provider version incompatibility.

How to eliminate wrong answers

Option A is wrong because a corrupted provider binary would typically cause a checksum error or crash during `terraform init`, not a failure during resource creation after a provider update. Option B is wrong because a corrupted state file would manifest as state read errors or inconsistency warnings during `terraform plan` or `apply`, not as a creation failure tied specifically to a provider version change. Option D is wrong because an incorrect backend configuration would prevent Terraform from loading or saving state entirely, often with an explicit error about backend initialization or authentication, not a resource creation failure after a successful provider update.

53
Multi-Selectmedium

Which TWO of the following are valid ways to use Terraform outside the core workflow (i.e., in automation or CI/CD pipelines)?

Select 2 answers
A.Using the Terraform CLI in a CI/CD pipeline with -auto-approve after a successful plan.
B.Using 'terraform state mv' to reorganize state files.
C.Using 'terraform init -from-module' to force module re-download.
D.Using the Terraform Cloud API to trigger runs and check results.
E.Using 'terraform graph' to generate visual output.
AnswersA, D

Automating Terraform deployments in a CI/CD pipeline is a standard practice for achieving continuous delivery of infrastructure. After a `terraform plan` confirms the intended infrastructure changes, `terraform apply -auto-approve` can be safely executed to provision or modify resources without requiring manual confirmation. This enables fully automated, hands-off deployments, crucial for maintaining infrastructure as code principles and accelerating release cycles.

Why this answer

The Terraform CLI's `-auto-approve` flag is designed for non-interactive environments like CI/CD pipelines, allowing automated execution of `terraform apply` after a successful plan without manual confirmation. This bypasses the interactive approval step, making it suitable for automation where human input is not possible.

Exam trap

HashiCorp often tests the distinction between commands that are part of the core workflow (plan, apply, destroy) versus auxiliary commands (state manipulation, graph generation, module initialization) that are not directly used for automated execution in CI/CD pipelines.

54
MCQeasy

A developer runs `terraform plan` and it fails with a provider plugin error. Which command should they run first to resolve the issue?

A.terraform validate
B.terraform apply
C.terraform fmt
D.terraform init
AnswerD

terraform init is the foundational command that prepares a working directory for all subsequent Terraform operations. It performs several crucial setup steps, including discovering and downloading the necessary provider plugins specified in the configuration, initializing the chosen backend for state storage, and setting up module sources. A "provider not found" error during `terraform plan` indicates that the required provider binaries were not downloaded or properly configured, which `terraform init` specifically addresses by fetching them.

Why this answer

The `terraform init` command is the correct first step because it initializes the working directory, downloads the required provider plugins, and sets up the backend configuration. A provider plugin error typically indicates that the provider plugins are missing, outdated, or not properly installed, and `terraform init` resolves this by fetching the correct versions from the Terraform registry.

Exam trap

HashiCorp often tests the misconception that `terraform validate` can fix runtime errors, but candidates must remember that `validate` only checks syntax and schema, not the availability of external dependencies like provider plugins.

How to eliminate wrong answers

Option A is wrong because `terraform validate` checks the syntax and internal consistency of the configuration files but does not download or install provider plugins, so it cannot fix a missing or corrupted provider. Option B is wrong because `terraform apply` attempts to execute the plan and apply changes, but it will fail if the provider plugins are not available, and it is not designed to resolve plugin installation issues. Option C is wrong because `terraform fmt` only reformats the configuration files for consistent style and has no effect on provider plugin availability or installation.

55
MCQmedium

A team uses an S3 backend with DynamoDB for state locking. They notice that sometimes terraform plan fails because the state is locked. What is the best practice to handle this in an automated pipeline?

A.Serialize pipeline runs to avoid concurrent execution
B.Use force-unlock before each plan
C.Increase the lock timeout
D.Use -lock=false in the pipeline
AnswerA

Serializing pipeline runs is the most effective and recommended approach to prevent state corruption when using a shared Terraform state backend. This strategy ensures that only one Terraform operation (e.g., plan or apply) can acquire the state lock and modify the state at any given time. By eliminating concurrent execution, it directly addresses the root cause of state locking conflicts and race conditions, maintaining the integrity of the remote state file.

Why this answer

Serializing pipeline runs is the best practice to prevent concurrent Terraform operations from competing for the same state lock. When multiple pipeline jobs attempt to run `terraform plan` or `terraform apply` simultaneously, DynamoDB-based state locking ensures only one operation holds the lock at a time, causing the others to fail. By enforcing sequential execution (e.g., via CI/CD stage dependencies or a mutex), you avoid lock contention entirely without risking data corruption or bypassing safety mechanisms.

Exam trap

The trap here is that candidates often assume increasing timeouts or disabling locking is acceptable for automation, but HashiCorp tests the understanding that state locking is a safety mechanism and the correct fix is to prevent concurrent access, not to bypass or extend the lock.

How to eliminate wrong answers

Option B is wrong because `force-unlock` is a manual intervention to remove a stale lock (e.g., after a crash) and should never be used in an automated pipeline — it can lead to concurrent state modifications and corruption. Option C is wrong because increasing the lock timeout does not resolve concurrent execution conflicts; it only delays the failure and can cause longer pipeline stalls without addressing the root cause. Option D is wrong because `-lock=false` disables state locking entirely, which can cause multiple operations to modify the state simultaneously, leading to state corruption or lost updates.

56
MCQeasy

Which Terraform command is used to bring existing infrastructure that was created outside of Terraform under Terraform management?

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

The "terraform import" command is the designated tool for incorporating existing infrastructure resources into Terraform's state management. This process requires specifying the Terraform resource address and the unique identifier of the existing cloud resource, effectively linking them within the state file. Once imported, Terraform can then manage the lifecycle of that previously unmanaged resource, allowing subsequent "terraform plan" and "apply" operations to detect and propose changes to it based on the corresponding HCL configuration.

Why this answer

`terraform import` is the dedicated command to bring existing infrastructure that was created outside of Terraform under Terraform management. It maps the real-world resource ID to a Terraform resource address in state, allowing Terraform to track and manage that resource without recreating it.

Exam trap

The exam often tests the distinction between `terraform import` (which adds external resources to state) and `terraform refresh` (which only syncs state for already-managed resources), leading candidates to mistakenly choose `terraform refresh` when they need to bring new resources under management.

How to eliminate wrong answers

Option A is wrong because `terraform state push` is used to manually upload a state file to a configured backend, not to import existing infrastructure. Option B is wrong because `terraform apply` applies configuration changes to create, update, or destroy resources, but it cannot import resources that were created outside of Terraform; it would attempt to create them anew, causing conflicts. Option D is wrong because `terraform refresh` updates the state file with the real-world state of already-managed resources, but it does not add new resources that were created outside of Terraform to the state.

57
MCQeasy

A user wants to see the current state of resources in a human-readable format without making changes. Which command should they use?

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

The `terraform show` command is the definitive tool for inspecting the current state of resources managed by Terraform. It reads the `terraform.tfstate` file and presents a detailed, human-readable representation of all tracked resources, including their attributes and their current values. This command is invaluable for auditing, debugging, and understanding the exact configuration of your deployed infrastructure as recorded in the state file.

Why this answer

`terraform show`, is correct because it displays the current state of managed resources in a human-readable format (defaulting to plain text) without making any changes. This command reads the state file directly and presents its contents, making it ideal for inspection and debugging. Unlike `terraform plan`, it does not generate an execution plan or propose modifications.

Exam trap

HashiCorp often tests the distinction between commands that inspect state (`terraform show`, `terraform state list`) versus those that generate plans or modify state, and the trap here is confusing `terraform plan` (which can show proposed changes) with a read-only view of the current state.

How to eliminate wrong answers

Option A is wrong because `terraform output` only shows the values of defined output variables, not the full state of all resources. Option B is wrong because `terraform state list` merely lists resource addresses in the state without displaying their attributes or configuration details. Option C is wrong because `terraform plan` creates an execution plan that compares current state with configuration and can propose changes, which is not a read-only view of the current state.

58
MCQeasy

A team wants to import an existing AWS S3 bucket named 'my-bucket' into Terraform state. The resource block is defined as 'aws_s3_bucket.my_bucket'. Which command should be used?

A.terraform import my-bucket aws_s3_bucket.my_bucket
B.terraform import 'aws_s3_bucket.my_bucket' 'my-bucket'
C.terraform import aws_s3_bucket.my_bucket my-bucket
D.terraform import aws_s3_bucket.my-bucket my-bucket
AnswerC

This command correctly follows the `terraform import <ADDRESS> <ID>` syntax, which is essential for bringing existing infrastructure under Terraform management. `aws_s3_bucket.my_bucket` accurately specifies the desired Terraform resource address, indicating it should be managed as an `aws_s3_bucket` resource named `my_bucket` within the configuration. `my-bucket` correctly identifies the exact ID of the pre-existing AWS S3 bucket to be imported into Terraform's state.

Why this answer

The correct syntax for `terraform import` is `terraform import <resource_address> <id>`, where the resource address is the Terraform resource block identifier (e.g., `aws_s3_bucket.my_bucket`) and the ID is the actual AWS resource identifier (e.g., the bucket name `my-bucket`). Option C follows this exact order: `terraform import aws_s3_bucket.my_bucket my-bucket`, making it the correct command to import the existing S3 bucket into Terraform state.

Exam trap

The Terraform exam often tests the argument order in `terraform import` — candidates frequently confuse the resource address and the resource ID, mistakenly thinking the ID comes first (as in some cloud CLI tools), but Terraform strictly requires the address before the ID.

How to eliminate wrong answers

Option A is wrong because it reverses the argument order, placing the bucket name first and the resource address second, which violates the required `terraform import <address> <id>` syntax. Option B is wrong because it wraps both arguments in single quotes unnecessarily (though quoting is not the primary error), but more critically it still places the resource address second and the ID first, which is the incorrect order. Option D is wrong because it uses a hyphen in the resource address (`aws_s3_bucket.my-bucket`), but the Terraform resource block name must use underscores, not hyphens, so `my-bucket` is invalid as a Terraform resource name.

59
Matchingmedium

Match each Terraform meta-argument to its purpose.

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

Concepts
Matches

Create multiple instances from one resource block

Create multiple instances from a map or set of strings

Explicitly specify hidden resource dependencies

Control resource creation/destruction behavior

Select a non-default provider configuration

Why these pairings

Terraform meta-arguments are available across all resource types. depends_on declares hidden dependencies, count creates N copies, for_each creates copies from a collection, and lifecycle controls behavior like create_before_destroy. Common confusions include mixing the purposes of count and depends_on, or associating lifecycle with instance creation.

60
MCQeasy

A DevOps team is integrating Terraform into a CI/CD pipeline using Jenkins. They want to ensure that the pipeline fails if the Terraform plan contains destructive changes. Which approach best achieves this?

A.Run terraform apply and parse the output for destroy messages.
B.Run terraform validate and check output for errors.
C.Run terraform destroy --target and fail if any resources are destroyed.
D.Run terraform plan -detailed-exitcode and fail pipeline if exit code is 2.
AnswerD

Executing `terraform plan -detailed-exitcode` is the correct approach because it generates an execution plan and signals the outcome through a specific exit code, ideal for CI/CD automation. An exit code of `2` explicitly indicates that a non-empty plan was generated, meaning there are proposed infrastructure changes. Failing the pipeline on this exit code ensures that any intended or unintended modifications are halted for review before an `apply` operation can proceed.

Why this answer

`terraform plan -detailed-exitcode` returns exit code 2 when there are any changes, including destructive changes. While it does not specifically detect only destructive changes, failing on any changes ensures that destructive changes are caught before apply, which is a common safety practice in CI/CD pipelines. Options A, B, and C are incorrect because A requires applying changes first, B does not detect changes, and C would actually destroy resources.

Exam trap

A common misconception is that `terraform plan -detailed-exitcode` only signals destructive changes; in reality, exit code 2 indicates any changes (additions, modifications, or deletions). However, failing on all changes is often acceptable to prevent unintended infrastructure changes.

How to eliminate wrong answers

Option A is wrong because parsing the output of `terraform apply` for destroy messages is unreliable (output format can change) and runs the apply before detecting destruction, which defeats the purpose of failing early. Option B is wrong because `terraform validate` only checks syntax and configuration validity, not whether the plan will destroy resources. Option C is wrong because `terraform destroy --target` is used to selectively destroy resources, not to detect destructive changes in a plan; it would actually perform destruction, not just report it.

61
MCQmedium

An organization uses Terraform Cloud for team collaboration. They have a workspace that manages production infrastructure. Due to a security policy, they must ensure that all changes go through a peer review process before they are applied. How can they enforce this requirement?

A.Enable 'apply on merge' and set the workspace to require approval before applying.
B.Require all changes to be submitted via a VCS pull request.
C.Use run triggers to automatically apply after a successful plan in another workspace.
D.Lock the workspace and only unlock it for approved changes.
AnswerA

Enabling 'apply on merge' configures the workspace to automatically initiate a Terraform run (plan) whenever code is merged into the configured VCS branch. By additionally setting the workspace to require explicit approval before applying, Terraform Cloud ensures that the planned changes are reviewed and approved by an authorized user within the TFC UI before they are actually provisioned. This combination provides a robust, automated, yet controlled deployment pipeline, aligning VCS changes with a mandatory human gate.

Why this answer

Enabling 'apply on merge' combined with requiring approval before applying enforces a peer review process: changes must be merged via a VCS pull request (triggering the plan), and then a separate approval step is needed before Terraform Cloud applies the changes. This ensures that no change is applied without explicit human approval after the plan is reviewed.

Exam trap

The trap here is that candidates confuse 'requiring a VCS pull request' (option B) with enforcing peer review, but without the approval step, the apply can still happen automatically after merge, bypassing the intended review gate.

How to eliminate wrong answers

Option B is wrong because requiring all changes to be submitted via a VCS pull request alone does not enforce peer review before apply; it only ensures changes are proposed via PR, but the apply could still happen automatically without manual approval. Option C is wrong because run triggers automatically apply after a successful plan in another workspace, bypassing any peer review or approval step for the target workspace. Option D is wrong because locking the workspace and only unlocking it for approved changes is a manual, error-prone process that does not enforce a consistent peer review workflow and does not integrate with VCS or Terraform Cloud's native approval mechanisms.

62
MCQmedium

A company uses Terraform with remote state stored in an S3 bucket. An operator accidentally runs 'terraform destroy' on a production workspace and wants to recover the state before the operation. What is the best course of action?

A.Re-run 'terraform apply' to recreate resources.
B.Restore the state file from a DynamoDB backup.
C.Use 'terraform state pull' to retrieve the last known state.
D.Restore the state file from the S3 bucket's versioning if enabled.
AnswerD

If S3 bucket versioning is enabled, every modification or deletion of the Terraform state file creates a new version, preserving previous states. This feature allows an administrator to easily retrieve and restore a previous, known-good version of the state file directly from the S3 bucket's version history. This is the most robust and recommended method for recovering from accidental state file deletion or corruption when using the S3 backend.

Why this answer

S3 bucket versioning, when enabled, automatically retains all versions of an object, including overwrites and deletions. By restoring the previous version of the state file (e.g., via the AWS console, CLI, or SDK), the operator can recover the exact state that existed before the 'terraform destroy' command was run, allowing Terraform to resume managing the infrastructure correctly.

Exam trap

A common misconception in the Terraform exam is that 'terraform state pull' can recover a previous state, but it only fetches the current state from the backend, which after a destroy is the empty state, not a historical version.

How to eliminate wrong answers

Option A is wrong because re-running 'terraform apply' without a valid state file would cause Terraform to attempt to recreate all resources from scratch, which may fail or create duplicate resources, and it does not recover the previous state. Option B is wrong because DynamoDB is used for state locking and consistency checks, not for storing state file backups; restoring from DynamoDB would not recover the state file itself. Option C is wrong because 'terraform state pull' retrieves the current state from the configured backend (the S3 bucket), which after 'terraform destroy' would reflect the destroyed state (empty or minimal), not the last known state before the operation.

63
Multi-Selectmedium

Which TWO of the following are best practices when using Terraform in a CI/CD pipeline? (Choose two.)

Select 2 answers
A.Run terraform apply automatically after plan
B.Use version control for configurations
C.Store state in the source repository
D.Use remote state with locking
E.Use terraform import to manage existing resources
AnswersB, D

Using version control systems like Git for Terraform configurations is a fundamental best practice for managing infrastructure as code. It provides a complete, auditable history of all infrastructure code changes, enabling teams to track who made what modifications and when. This facilitates seamless collaboration among multiple developers, allows for easy rollback to previous stable states, and supports robust auditing and compliance requirements by maintaining an immutable record of infrastructure evolution.

Why this answer

Option B is correct because storing Terraform configurations in version control (e.g., Git) provides an auditable history, enables peer review via pull requests, and allows the pipeline to trigger on commits, which is fundamental to any CI/CD workflow. Option D is correct because remote state with locking (e.g., an S3 backend with DynamoDB state locking, or Terraform Cloud) prevents concurrent pipeline runs from corrupting the state file and keeps state out of individual machines, which is essential for reliable automated deployments. Option A is not a best practice because automatically applying after plan without a manual approval gate or policy check can push unintended changes to production; a plan should be reviewed before apply.

Option C is wrong because committing state to the source repository risks exposing secrets in plaintext and causes conflicts when multiple pipeline runs modify state. Option E is not a CI/CD best practice per se; terraform import is a one-off remediation command for bringing existing resources under management, not a routine pipeline practice.

Exam trap

TF-004 often tests the misconception that 'automate everything' means applying without approval, and that state can be treated like ordinary code in Git—both lead candidates away from the correct remote-state-with-locking and version-control answers.

64
MCQmedium

A company wants to use Terraform to manage resources across AWS and Azure. They need a single workflow that can apply changes to both providers. What is the best practice?

A.Use separate Terraform configurations for each provider
B.Use Terraform Cloud workspaces with different providers
C.Use Terraform workspaces to separate providers
D.Define both providers in a single configuration
AnswerD

Defining multiple providers within a single Terraform configuration allows for a truly unified infrastructure as code workflow. This approach enables the declaration and management of resources from different cloud providers (e.g., AWS and Azure) within the same set of `.tf` files, facilitating the creation of cross-provider dependencies and ensuring that `terraform plan` and `apply` operations consider the entire infrastructure holistically.

Why this answer

Terraform allows multiple providers to be defined in a single configuration, enabling a unified workflow to manage resources across AWS and Azure. By declaring both providers in the same root module, a single `terraform apply` can create, update, or destroy resources from both clouds in the correct order, leveraging Terraform's dependency graph to handle cross-provider dependencies. This is the recommended best practice for multi-cloud management with a single workflow.

Exam trap

The trap here is that candidates confuse workspaces (which isolate state for different environments) with provider separation, leading them to choose option C, when in fact workspaces do not change the provider definitions in a configuration.

How to eliminate wrong answers

Option A is wrong because using separate configurations for each provider would require separate `terraform apply` runs, breaking the single workflow requirement and introducing manual coordination or external orchestration. Option B is wrong because Terraform Cloud workspaces are designed to manage multiple environments (e.g., dev, prod) with the same provider configuration, not to separate providers; using different workspaces for different providers would still require separate configurations or state files, not a single workflow. Option C is wrong because Terraform workspaces are a state isolation mechanism for the same configuration, not a way to separate providers; they cannot change which providers are used in a single configuration, and using workspaces to separate providers would still require multiple configurations or manual switching.

65
Multi-Selectmedium

Which TWO of the following are benefits of using Terraform Cloud Run Tasks?

Select 2 answers
A.Integrate with third-party tools for security scanning.
B.Simplify state management by offloading to Terraform Cloud.
C.Provide an approval gate for manual intervention.
D.Enforce custom policies before allowing an apply.
E.Automatically reduce costs by identifying unused resources.
AnswersA, D

Terraform Cloud Run Tasks enable seamless integration with third-party security scanning tools by allowing them to execute as part of the `terraform plan` or `terraform apply` workflow. These tasks can invoke external services to perform static analysis, vulnerability checks, or compliance scans on the planned infrastructure. If the security tool identifies issues, the Run Task can fail the Terraform run, preventing the deployment of non-compliant or insecure resources.

Why this answer

Terraform Cloud Run Tasks allow integration with third-party tools for security scanning, policy enforcement, or other validations during the plan/apply lifecycle. This is achieved by configuring run tasks that call external services via webhooks, enabling automated checks before provisioning proceeds.

Exam trap

The exam often tests the distinction between Run Tasks (automated, third-party integrations) and other Terraform Cloud features like Sentinel policies (custom policy enforcement) or manual approvals, leading candidates to confuse Run Tasks with approval gates or cost-saving features.

66
Multi-Selecteasy

Which THREE of the following are valid methods to manage Terraform state in a team environment? (Choose three.)

Select 3 answers
A.Storing state in a version control system
B.Using a remote backend like S3 with DynamoDB locking
C.Using Terraform workspaces with a remote backend
D.Storing state locally and sharing via network drive
E.Using Terraform Cloud to manage state
AnswersB, C, E

Using a remote backend like Amazon S3 for state storage, combined with DynamoDB for state locking, is a highly recommended and standard practice for collaborative Terraform environments. S3 provides durable, highly available, and versioned storage for the state file, while DynamoDB ensures mutual exclusion, preventing multiple users or processes from concurrently modifying the state and thereby avoiding corruption during `terraform apply` operations.

Why this answer

Options B, C, and E are all valid methods for managing Terraform state in a team environment. Option B uses a remote backend like S3 with DynamoDB locking to centralize state and prevent concurrent modifications. Option C leverages Terraform workspaces with a remote backend to isolate state for different environments while maintaining a single backend configuration.

Option E uses Terraform Cloud, which provides a managed state backend with built-in locking and versioning, simplifying team collaboration. Option A is incorrect because version control systems lack state locking and can lead to corruption. Option D is incorrect because storing state locally on a network drive introduces consistency and locking issues, making it unsuitable for concurrent team access.

Exam trap

HashiCorp often tests the misconception that version control systems like Git can safely manage Terraform state, but they lack the locking and atomicity required for concurrent team workflows.

67
Multi-Selectmedium

Which TWO are benefits of using Terraform Cloud's remote operations with a CLI-driven run workflow?

Select 2 answers
A.Integration with version control systems for automatic plan and apply
B.Centralized state management with automatic locking
C.Support for multiple cloud providers in a single workspace
D.Reduced dependency on local environment variables for provider authentication
E.Ability to execute `terraform plan -refresh-only` without a run
AnswersB, D

Remote operations in Terraform Cloud inherently provide centralized state management, storing the `terraform.tfstate` file securely in a remote backend. This centralization is critical for team collaboration, ensuring all team members operate against the same, authoritative infrastructure state. Furthermore, automatic state locking prevents concurrent `terraform apply` operations from corrupting the state file, guaranteeing consistency and preventing race conditions during infrastructure updates.

Why this answer

Option B is correct because Terraform Cloud remote operations store the workspace state centrally on Terraform Cloud's servers rather than on the local machine, and the platform automatically locks state during runs to prevent concurrent modifications and state corruption. Option D is correct because with remote operations the run executes inside Terraform Cloud's disposable environment, where provider credentials and secrets are supplied via workspace variables (environment variables, Terraform variables, or dynamic provider credentials) rather than relying on the practitioner's local shell environment. The unmarked options do not belong: A describes VCS-driven workflows, not the CLI-driven run workflow, which triggers runs from the local CLI via `terraform plan`/`terraform apply`; C is not a benefit specific to remote operations, since a single workspace still maps to one provider configuration and multi-provider support exists regardless of execution mode; and E is false because `terraform plan -refresh-only` is a Terraform CLI command that still requires a run to be initiated and executed, whether locally or remotely.

Exam trap

HashiCorp often tests the distinction between general Terraform Cloud features and those specifically tied to different run workflows (CLI-driven vs. VCS-driven). Candidates may confuse broad benefits of Terraform Cloud (like multi-provider support) or benefits of the VCS-driven workflow (like automatic plan/apply from VCS pushes) with the unique advantages of the CLI-driven workflow, which include centralized state management and leveraging the remote execution environment for credential management.

68
MCQhard

A company uses Terraform Cloud with a remote state backend and runs infrastructure as code through a CI/CD pipeline (GitHub Actions). The pipeline executes 'terraform plan' and 'terraform apply' using a service account with appropriate permissions. Recently, the team introduced a Sentinel policy to enforce that all AWS resources have mandatory tags (Environment, Owner, Project). The policy passes when runs are triggered manually from the Terraform Cloud UI, but fails consistently when the CI/CD pipeline runs the plan. The infrastructure configuration files are identical in both cases. The team verifies that the service account used by CI/CD has the same workspace permissions as the UI user. What is the most likely cause of the failure?

A.The Sentinel policy is checking the wrong workspace.
B.The CI/CD pipeline is using a different set of variables that override the tags.
C.The Sentinel policy is configured to fail on all plans regardless of compliance.
D.The CI/CD pipeline is using an older version of Terraform that does not support Sentinel.
AnswerB

Terraform Cloud allows variables to be set at various levels, with a specific order of precedence. A CI/CD pipeline often initiates runs via the Terraform Cloud API, which can include `TF_VAR_` environment variables or `terraform.tfvars` content that overrides variables configured directly in the workspace UI. If the pipeline injects different tag values through these mechanisms, the resulting Terraform plan will differ, causing the Sentinel policy to detect a non-compliant resource configuration.

Why this answer

The Sentinel policy enforces mandatory tags on AWS resources. When the CI/CD pipeline runs, it may use different variable definitions (e.g., from environment variables or variable files) that override the Terraform variables for tags. If the pipeline sets missing or incorrect tag values, the policy fails.

Manual UI runs likely use the workspace's default variable values, which satisfy the policy. Since the configuration files are identical, the discrepancy is due to variable overrides from the pipeline, making Option B correct.

69
MCQhard

A team uses Terraform Cloud with a VCS-backed workflow. They notice that a recent commit triggered a run that failed because of an invalid configuration. The team fixed the configuration and wants to re-run the plan without committing again. Which action should they take?

A.Amend the previous commit and force push
B.Create a new commit with the fix
C.Use the 'Queue Plan' button in the Terraform Cloud UI
D.Run terraform plan locally and apply
AnswerB

Creating a new commit with the fix is the correct and standard procedure for a VCS-backed workflow in Terraform Cloud. This action pushes the updated configuration to the remote repository, which Terraform Cloud actively monitors for changes. Upon detecting the new commit, Terraform Cloud automatically initiates a new run (plan and potentially apply) using the corrected code, ensuring the infrastructure aligns with the intended state.

Why this answer

In a VCS-backed Terraform Cloud workspace, runs are triggered by commits to the linked repository. When a configuration error is found in the code, fixing it requires a new commit that includes the corrected code. The 'Queue Plan' button re-runs a plan using the same commit, so it cannot incorporate local fixes.

Creating a new commit (option B) triggers a new run with the fixed configuration.

Exam trap

Candidates may think that the 'Queue Plan' button can re-run a plan with any configuration fix, but it only uses the same commit and workspace settings. If the fix involves version-controlled files, a new commit is necessary.

How to eliminate wrong answers

Option A is wrong because amending the previous commit and force pushing rewrites Git history, which can disrupt team collaboration and is not a recommended practice for fixing a failed run in Terraform Cloud; it also does not leverage Terraform Cloud's built-in run management. Option B is wrong because creating a new commit with the fix would trigger a new run automatically, but the question specifically asks to re-run the plan without committing again, making this an unnecessary and incorrect approach. Option D is wrong because running terraform plan locally and applying bypasses Terraform Cloud's VCS-backed workflow, state management, and collaboration features, and the apply would not be tracked or approved through Terraform Cloud's run pipeline.

70
MCQhard

A team uses Terraform with multiple workspaces and wants to automatically trigger a plan when a pull request is opened in their Git repository. They use Terraform Cloud. Which feature enables this?

A.VCS-driven workflow
B.API-driven workflow
C.CLI-driven workflow
D.Registry-driven workflow
AnswerA

A VCS-driven workflow integrates Terraform with a Version Control System like Git, automatically triggering `terraform plan` operations in a remote execution environment (e.g., Terraform Cloud/Enterprise) whenever changes are pushed or a Pull Request (PR) is opened. This approach provides continuous validation of infrastructure changes, allowing teams to review and approve proposed modifications before they are applied, which is essential for managing multiple workspaces collaboratively and maintaining infrastructure consistency.

Why this answer

The VCS-driven workflow in Terraform Cloud automatically triggers a plan when a pull request is opened in a connected Git repository. This is configured by linking a VCS provider (e.g., GitHub, GitLab) to a workspace and enabling speculative plans on pull requests, which allows Terraform Cloud to run a plan without applying changes.

Exam trap

HashiCorp often tests the distinction between VCS-driven and API-driven workflows, where candidates mistakenly think any automated trigger must use the API, but the VCS-driven workflow is the native Git integration that handles PR events without custom API calls.

How to eliminate wrong answers

Option B is wrong because the API-driven workflow requires an external system to call the Terraform Cloud API to trigger runs, not automatically on pull requests. Option C is wrong because the CLI-driven workflow relies on local execution of Terraform commands, not on Git events. Option D is wrong because the Registry-driven workflow is used for consuming modules from the Terraform Registry, not for triggering plans from VCS events.

71
MCQeasy

Refer to the exhibit. A Terraform plan fails with the error shown. What is the most likely cause?

A.The S3 bucket does not have versioning enabled.
B.The DynamoDB table is not configured correctly.
C.The state file is corrupted.
D.Another Terraform run is currently in progress.
AnswerD

When a Terraform operation, such as `plan` or `apply`, is initiated, it first attempts to acquire a state lock to prevent concurrent modifications. If another Terraform process is already running against the same state, it will hold this lock, causing subsequent operations to fail with a 'lock acquisition failed' error. This mechanism ensures state consistency and prevents potential corruption from simultaneous updates.

Why this answer

The error message indicates that Terraform cannot acquire a state lock. This typically occurs when another Terraform run is already in progress and holds the lock on the state file. Terraform uses a locking mechanism (often via DynamoDB) to prevent concurrent modifications; if a lock is already held, subsequent runs will fail with this error until the lock is released or expires.

Exam trap

HashiCorp often tests the distinction between state file corruption and state locking errors; the trap here is that candidates may confuse a lock failure with a state file issue, especially when the error message includes DynamoDB references.

How to eliminate wrong answers

Option A is wrong because S3 bucket versioning is not related to state locking; versioning helps with state file history and recovery, but does not cause lock acquisition failures. Option B is wrong because while a misconfigured DynamoDB table could cause lock failures, the error message specifically points to an existing lock being held, not a configuration issue. Option C is wrong because a corrupted state file would typically cause parsing or validation errors, not a lock acquisition failure.

72
Drag & Dropmedium

Drag and drop the steps to use Terraform workspaces for environment separation in the correct order.

Drag or tap steps into the slots.

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

Why this order

The correct sequence for using Terraform workspaces is: first create the workspace (if it doesn't exist) to isolate state, then select it to switch to that workspace's state, then set environment-specific variables (e.g., via .tfvars files) to tailor configuration, and finally run terraform plan and apply to manage resources. Workspaces are essential for environment separation, ensuring state isolation and preventing cross-environment interference.

73
MCQeasy

A company wants to integrate Terraform with their CI/CD pipeline to automatically deploy infrastructure. Which Terraform feature should they use to ensure state files are stored securely and accessible by the pipeline?

A.Terraform import
B.Local state with .gitignore
C.Terraform Cloud remote state
D.terraform state push
AnswerC

Terraform Cloud provides a highly secure, reliable, and accessible remote backend for storing Terraform state files. It automatically handles state locking to prevent concurrent modifications, encrypts state at rest and in transit, and offers versioning for auditability. Its API-driven nature and direct integration with Terraform runs make it an ideal solution for CI/CD pipelines, ensuring consistent and collaborative infrastructure management across automated deployments.

Why this answer

Terraform Cloud remote state stores the state file in a managed, access-controlled backend that CI/CD pipelines can authenticate to via API tokens, providing secure storage, locking, and versioning. This satisfies the requirement that state be stored securely and be reliably accessible to the pipeline without committing it to source control.

Exam trap

TF-004 often tests the misconception that keeping state local and gitignoring it is 'secure enough,' when the real requirement is a shared, locked, access-controlled remote backend for CI/CD.

How to eliminate wrong answers

Option A is wrong because 'terraform import' brings existing infrastructure under Terraform management; it has nothing to do with where or how state is stored. Option B is wrong because local state with .gitignore keeps state off source control but leaves it on a single machine, making it inaccessible to CI/CD runners and prone to loss or concurrent-write corruption. Option D is wrong because 'terraform state push' is a manual command to overwrite remote state — it is an operation, not a secure storage feature, and misusing it can corrupt state.

74
MCQhard

A user receives the error shown in the exhibit when running `terraform init`. The user is behind a corporate proxy. Which environment variable should be set to resolve this issue?

A.TF_VAR_proxy=http://proxy:8080
B.AWS_ACCESS_KEY_ID
C.HTTP_PROXY=http://proxy:8080
D.TF_LOG=DEBUG
AnswerC

The `HTTP_PROXY` environment variable is a widely recognized standard that many applications, including Terraform and its providers, respect for configuring an HTTP proxy server. When set, Terraform will route its outgoing HTTP requests through the specified proxy server, enabling it to reach external endpoints that might otherwise be inaccessible due to network restrictions or firewalls. This is the correct and conventional method for configuring a network proxy for Terraform's HTTP communications, directly addressing connectivity errors in environments requiring proxy access.

Why this answer

Terraform uses the standard `HTTP_PROXY` environment variable to route HTTP/HTTPS requests through a corporate proxy when downloading providers and modules. Setting `HTTP_PROXY=http://proxy:8080` instructs Terraform's underlying HTTP client to connect via the specified proxy, resolving the connectivity error during `terraform init`.

Exam trap

HashiCorp often tests the distinction between Terraform-specific environment variables (like `TF_VAR_`) and standard system proxy variables, leading candidates to mistakenly choose `TF_VAR_proxy` as a Terraform-native proxy setting.

How to eliminate wrong answers

Option A is wrong because `TF_VAR_proxy` is not a recognized environment variable in Terraform; the `TF_VAR_` prefix is used to set input variables, not proxy configuration. Option B is wrong because `AWS_ACCESS_KEY_ID` is an AWS credential variable unrelated to proxy settings; it would not fix a network connectivity issue caused by a proxy. Option D is wrong because `TF_LOG=DEBUG` enables verbose logging for debugging but does not configure proxy routing; it only increases log output without addressing the underlying proxy requirement.

75
MCQhard

A team using a remote S3 backend with DynamoDB locking is experiencing frequent 'Error acquiring the state lock' messages in their CI/CD pipeline. The pipeline runs multiple concurrent jobs for different workspaces. What is the most likely cause and solution?

A.The DynamoDB table lacks sufficient read/write capacity; increase it.
B.The same workspace is being used for concurrent runs; use separate workspaces per environment.
C.The pipeline is running too many jobs; increase the lock wait time.
D.The S3 bucket is not versioned; enable versioning.
AnswerB

Terraform workspaces provide isolated state files and, crucially, independent state locks within the same backend configuration. When multiple concurrent `terraform apply` or `terraform plan` operations target the *same* workspace, only one can acquire the state lock at a time, leading to subsequent runs timing out while waiting for the lock to be released. Using distinct workspaces for different environments or concurrent operations ensures each run attempts to acquire a separate lock, preventing contention.

Why this answer

The error 'Error acquiring the state lock' occurs when Terraform cannot obtain a lock on the state file for a specific workspace. In this scenario, the pipeline runs multiple concurrent jobs for different workspaces, but if the same workspace is inadvertently used across concurrent runs, Terraform's DynamoDB-based locking mechanism will prevent simultaneous access to that workspace's state. The solution is to ensure each environment (e.g., dev, staging, prod) uses a separate workspace, avoiding lock contention.

Option B correctly identifies this as the most likely cause and solution.

Exam trap

HashiCorp often tests the misconception that DynamoDB capacity or S3 versioning are the root cause of lock errors, when the real issue is workspace-level contention in concurrent pipelines.

How to eliminate wrong answers

Option A is wrong because DynamoDB read/write capacity is not the issue; the lock error is about contention, not throughput limits, and increasing capacity would not resolve concurrent access to the same lock item. Option C is wrong because increasing the lock wait time (e.g., via the `-lock-timeout` flag) only delays the failure, it does not prevent the underlying conflict of multiple jobs trying to lock the same workspace state. Option D is wrong because S3 bucket versioning is unrelated to state locking; versioning protects against accidental deletion or corruption of state files, but does not affect DynamoDB lock acquisition.

Page 1 of 2 · 80 questions totalNext →

Ready to test yourself?

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