Courseiva

CCNA Terraform Advanced Workflow Questions

75 of 77 questions · Page 1/2 · Terraform Advanced Workflow topic · 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

The plan shows changes to attributes like AMI and instance type. Since the configuration hasn't changed, these differences indicate that the instance was modified manually, likely via the AWS console. This is a classic example of configuration drift, where the actual infrastructure state diverges from the desired state defined in Terraform configuration.

Option D correctly identifies this cause.

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 validate resource attributes.

Why this answer

Terraform Cloud's Sentinel policy framework allows you to define policy-as-code rules that can enforce mandatory tags on resources. By writing a Sentinel policy that checks for the presence of specific tags (e.g., 'Environment', 'Owner') during the plan phase, you can block or warn on any resource creation that lacks those tags, ensuring compliance with organizational tagging standards.

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

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.

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

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

11
Multi-Selectmedium

Which TWO of the following are valid ways to import existing infrastructure into Terraform management? (Choose TWO.)

Select 2 answers
A.Use 'terraform validate' to automatically import resources.
B.Use 'terraform state rm' to remove resources from state, then re-add them.
C.Use the 'terraform import' command with the resource address and ID.
D.Write the configuration manually and run 'terraform plan' to refresh state, then adjust.
E.Run 'terraform apply' with an empty configuration to detect resources.
AnswersC, D

This is the primary method for importing existing resources.

Why this answer

'terraform import' is the dedicated command to bring existing infrastructure under Terraform management by associating a real-world resource ID with a resource address in state. Option D is correct because you can manually write configuration that matches the existing resource, then run 'terraform plan' to refresh state and detect any drift, allowing you to adjust the configuration until the plan shows no changes.

Exam trap

HashiCorp often tests the misconception that 'terraform validate' or 'terraform apply' can import resources, when in fact only 'terraform import' (or manual configuration with plan refresh) accomplishes this, and candidates confuse validation or apply with the import workflow.

12
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 enforces policies on configurations before apply.

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.

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

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

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

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

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

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

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

20
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

S3 backend encryption encrypts state at rest.

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.

21
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

Provisioners are not re-run on updates unless triggers specify.

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.

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

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

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

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

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

27
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 is the policy-as-code framework for enforcing rules.

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.

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

29
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

Implementing a CI/CD pipeline that runs 'terraform init' with the correct backend configuration ensures that all developers use the same remote backend and prevents accidental local inits. This enforces consistency and avoids the scenario where a developer creates a local state file that diverges from the remote state. Option A is incorrect because state locking prevents concurrent modifications but does not prevent the use of a local backend.

Option C is incorrect because there is no 'terraform plan -check' flag; even if there were, it would not detect a local state at plan time if the state was already initialized locally. Option D is incorrect because 'terraform workspace' commands manage workspaces but do not enforce that the backend is remote; a local backend still works with workspaces.

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

31
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

Standard practice; avoids triggering runs on main until merge.

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.

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

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

34
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

Remote backends enable state locking and store state in a shared location, preventing conflicts and enabling team collaboration. The other options are incorrect: remote backends do not store state locally, can be used with Terraform Cloud, and migration can be automated.

35
MCQmedium

An organization wants to use Terraform to manage resources across multiple accounts and regions, with different team members responsible for different environments. Which Terraform feature helps separate state and configuration for each environment?

A.Providers
B.Modules
C.Workspaces
D.Backends
AnswerC

Create separate state files for each environment.

Why this answer

Workspaces in Terraform allow you to manage multiple distinct sets of infrastructure resources (state files) within the same configuration. By using separate workspaces for each environment (e.g., dev, staging, prod), you can isolate state and configuration without duplicating code, making it the correct feature for this multi-environment scenario.

Exam trap

Terraform certification exams often test the misconception that backends alone provide environment isolation, but backends only define the storage location; without workspaces or manual state file separation, all environments would share the same state, leading to conflicts.

How to eliminate wrong answers

Option A is wrong because providers are used to define and configure the cloud provider (e.g., AWS, Azure) and its authentication, not to separate state or configuration per environment. Option B is wrong because modules are reusable configuration packages that encapsulate resource definitions, but they do not inherently provide state isolation across environments; multiple modules still share the same state file unless combined with workspaces or separate backends. Option D is wrong because backends define where state is stored (e.g., S3, Terraform Cloud), but they do not inherently separate state per environment; you would need to configure separate backend instances or use workspaces to achieve that isolation.

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

37
MCQmedium

An organization uses Terraform to provision infrastructure and then Ansible to configure it. They want to pass dynamic IP addresses from Terraform to Ansible. What is a recommended approach?

A.Use environment variables in the pipeline to pass IP addresses.
B.Use the terraform_remote_state data source in a dummy Terraform configuration.
C.Store outputs in Consul KV store and have Ansible read from there.
D.Use terraform output -json and parse it in Ansible as an inventory.
AnswerD

The terraform output -json command provides a structured, machine-readable JSON representation of all defined Terraform outputs. Ansible can natively consume dynamic inventories in JSON format, making this a highly efficient and idiomatic integration method. This approach directly leverages Terraform's output capabilities and Ansible's inventory system without requiring intermediate tools or complex parsing logic.

Why this answer

`terraform output -json` produces JSON output that can be parsed by Ansible to dynamically build an inventory. This approach is simple, directly uses Terraform's built-in output, and avoids additional infrastructure. Option A is incorrect: while environment variables can pass simple strings, they are less suitable for structured data like multiple IP addresses and are not the recommended pattern.

Option B is incorrect: `terraform_remote_state` is designed for fetching outputs from other Terraform configurations, not for exposing data to external tools like Ansible. Option C is incorrect: using Consul KV store introduces unnecessary complexity and external dependencies; the direct `terraform output` approach is simpler and more maintainable.

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

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

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

41
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

Idempotent; creates missing resources.

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.

42
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

'terraform plan -out=plan.tfplan' generates a plan file, and 'terraform show -json plan.tfplan' outputs it in JSON format, which can be parsed to detect destroy actions. If no destroy actions are present, the pipeline can proceed to apply. Option A is wrong because 'terraform apply -auto-approve' would apply any changes without checking for destroys.

Option B is wrong because 'terraform plan -destroy' always shows a destroy plan, not a way to detect destroys in a normal plan. Option C is wrong because 'terraform fmt' only formats code, not checks for destroys. Option D is wrong because 'terraform validate' only checks syntax, not planned changes.

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

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

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

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

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

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

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

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

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

52
MCQmedium

Refer to the exhibit. A Terraform Cloud plan includes an EC2 instance of type 't2.medium'. The team uses Sentinel policies. Which action should they take to proceed?

A.Modify the Sentinel policy to allow t2.medium.
B.Disable the policy check for this run.
C.Change the instance type in the configuration to t2.micro or t2.small.
D.Override the policy in the run using Terraform Cloud UI.
AnswerC

Comply with the policy.

Why this answer

Sentinel policies enforce compliance rules, and if the policy explicitly denies 't2.medium', the team must modify their configuration to use an allowed instance type (e.g., t2.micro or t2.small) to pass the policy check. This aligns with the principle of infrastructure-as-code where policies are immutable guardrails, and the configuration must be adapted to meet them rather than bypassing the policy.

Exam trap

HashiCorp often tests the misconception that Sentinel policies can always be overridden or disabled, but the trap here is that hard-mandatory policies require configuration changes, not workarounds, and candidates must recognize that modifying the policy or bypassing the check violates the governance model.

How to eliminate wrong answers

Option A is wrong because modifying the Sentinel policy to allow t2.medium undermines the purpose of policy-as-code; policies are typically managed by a separate team (e.g., security or compliance) and should not be changed by the team running the plan to accommodate a non-compliant resource. Option B is wrong because disabling the policy check for this run bypasses governance entirely, which defeats the purpose of using Sentinel for continuous compliance and is not a recommended practice in Terraform Cloud workflows. Option D is wrong because overriding the policy in the Terraform Cloud UI is only possible for 'soft-mandatory' policies, not for 'hard-mandatory' ones; if the policy is hard-mandatory, the override option is unavailable, and even if available, it should be used sparingly for exceptions, not as a routine workaround.

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

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

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

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

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

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

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

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

61
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

Remote state with locking ensures consistency and prevents corruption. Version control tracks changes. Storing state in source repo is not secure.

Auto-applying after plan is risky without approval. terraform import is for importing existing resources, not a CI/CD best practice.

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

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

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

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

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

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

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

69
Drag & Dropmedium

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

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

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

Why this order

The correct sequence 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.

70
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

Using a remote state backend (like Terraform Cloud) ensures state is stored securely and can be accessed by pipeline runs. Local state with .gitignore is not secure or accessible. Terraform import is for adding existing resources, not state storage. terraform state push is used to manually upload state.

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

72
MCQhard

An organization uses Terraform Cloud to manage infrastructure across multiple teams. They need to enforce that all workspaces use a specific version of Terraform and that no workspace can be deleted accidentally. Which approach meets these requirements without using Sentinel or Terraform Enterprise?

A.Include `required_version` in each workspace's root module and configure workspace locks in the UI.
B.Set `required_providers` with version constraints in a global Terraform file.
C.Use the Terraform Cloud API to write an OPA policy that enforces Terraform version and prevents workspace deletion.
D.Configure version constraints in the Terraform Cloud workspace settings and enable deletion protection.
AnswerD

Terraform Cloud workspaces offer explicit settings to define the exact Terraform CLI version used for all runs within that workspace, ensuring consistent execution environments regardless of the configuration's `required_version`. Additionally, a dedicated "Prevent deletion" safeguard can be enabled directly in the workspace settings. This critical feature protects against accidental or unauthorized removal of the workspace and its associated infrastructure state.

Why this answer

Terraform Cloud allows configuring the Terraform version at the workspace level, ensuring a specific version is used. The 'Prevent deletion' option in workspace settings protects against accidental deletion. While per-workspace, administrators can enforce these settings across workspaces via API or organization defaults.

Options A and B do not prevent deletion; Option C is incorrect because OPA is not natively integrated—Sentinel is the built-in policy engine but is excluded.

Exam trap

Candidates may think that built-in workspace settings are not enough to enforce global compliance, but administrators can enforce these settings via organization defaults or API scripts. OPA integration is often mistakenly assumed to be available natively.

How to eliminate wrong answers

Option A is wrong because `required_version` in a root module only enforces the Terraform version at plan/apply time, not across all workspaces globally, and workspace locks in the UI prevent concurrent operations but do not prevent accidental deletion. Option B is wrong because `required_providers` with version constraints controls provider versions, not the Terraform CLI version, and does not address workspace deletion prevention. Option D is wrong because Terraform Cloud workspace settings allow you to set a Terraform version per workspace, but there is no built-in 'deletion protection' toggle; deletion protection requires Sentinel or OPA policies via the API.

73
MCQhard

A large enterprise uses Terraform Cloud with remote execution mode to manage infrastructure across multiple AWS accounts. Each environment (dev, staging, prod) has a separate workspace. The security team requires that all changes to production must be approved by a senior engineer before applying. Additionally, developers should be able to plan changes in production to preview the impact, but not apply them. The current setup uses the same Terraform Cloud team membership for all workspaces. When a developer runs a plan in production, the plan succeeds but they are unable to apply. However, the security team notices that the developer can accidentally apply if they quickly approve their own plan via the UI because the workspace is configured with 'Auto Apply' enabled. The security team wants to enforce the approval process without removing the developer's ability to plan. Which combination of changes should be made? (Select only one option.)

A.Keep 'Auto Apply' enabled but restrict the production workspace to only the infrastructure lead's Terraform Cloud account.
B.Use run triggers to promote runs from dev to staging to production, and only the lead can promote to production.
C.Disable 'Auto Apply' on the production workspace and configure team permissions so that developers have 'plan' role and the infrastructure lead has 'write' role.
D.Use VCS branch restrictions to only allow applies from the 'main' branch, and have developers plan from feature branches.
AnswerC

This enforces manual approval and restricts apply permissions.

Why this answer

Disabling 'Auto Apply' on the production workspace ensures that no apply occurs without explicit approval. Configuring team permissions so that developers have the 'plan' role (which allows running plans but not applying) and the infrastructure lead has the 'write' role (which allows applying) enforces the required approval process while preserving the developer's ability to preview changes via plan.

Exam trap

HashiCorp often tests the distinction between run triggers (which automate promotion) and manual approval workflows, leading candidates to incorrectly choose run triggers as a solution for approval enforcement when they actually bypass manual approval.

How to eliminate wrong answers

Option A is wrong because keeping 'Auto Apply' enabled would still allow applies to happen automatically after a plan, bypassing the approval process; restricting to the lead's account does not prevent a developer from triggering a plan that auto-applies. Option B is wrong because run triggers are designed to chain runs between workspaces (e.g., promoting from dev to staging to prod) but do not enforce a manual approval step before applying in production; they automate the promotion, not the approval. Option D is wrong because VCS branch restrictions control which branches can trigger runs, but they do not prevent a developer from applying a plan if they have apply permissions; the developer could still apply from the 'main' branch if they have the appropriate role, and the scenario requires that developers cannot apply at all.

74
MCQeasy

A DevOps team is using Terraform Cloud to manage infrastructure. They want to integrate Terraform into their CI/CD pipeline by triggering runs programmatically. Which approach should they use to invoke a Terraform run from an external system?

A.Use the Terraform Cloud API to trigger a run.
B.Set up a webhook from the VCS provider to trigger runs.
C.Configure a remote backend to automatically run apply.
D.Execute 'terraform apply -auto-approve' in the CI pipeline.
AnswerA

This is the correct method for programmatic interaction with Terraform Cloud. The Terraform Cloud API provides specific endpoints to create, manage, and trigger runs for designated workspaces, enabling seamless integration with external systems like CI/CD pipelines, custom scripts, or other automation tools. This approach allows for precise control over the run lifecycle, including dynamic variable overrides and explicit plan/apply actions, without requiring direct VCS commits.

Why this answer

The Terraform Cloud API provides a programmatic endpoint to trigger runs, allowing external CI/CD systems to initiate Terraform operations without manual intervention. This is the correct approach because it directly invokes a run with full control over variables, configuration versions, and apply strategies, aligning with the requirement to integrate Terraform into a CI/CD pipeline programmatically.

Exam trap

HashiCorp often tests the distinction between event-driven triggers (VCS webhooks) and programmatic API calls, where candidates mistakenly choose webhooks because they seem 'automated,' but the question explicitly requires programmatic invocation from an external system, not a VCS event.

How to eliminate wrong answers

Option B is wrong because setting up a webhook from the VCS provider triggers runs automatically on code changes, not programmatically from an external CI/CD system; it is event-driven, not API-driven. Option C is wrong because configuring a remote backend does not trigger runs—it only stores state remotely and enables remote execution, but the run must be initiated separately. Option D is wrong because executing 'terraform apply -auto-approve' in the CI pipeline is a local CLI command that bypasses Terraform Cloud's run management, state locking, and policy checks, and it does not integrate with Terraform Cloud's API or remote execution capabilities.

75
MCQhard

An organization uses Terraform with remote state stored in S3 and DynamoDB for state locking. During a plan, they receive the error: 'Error acquiring the state lock: ConditionalCheckFailedException: The conditional request failed'. What is the most likely cause?

A.The state file in S3 is corrupted.
B.The DynamoDB table is not configured with a primary key named LockID.
C.The S3 bucket does not have versioning enabled.
D.Another Terraform process is currently running and holds the state lock.
AnswerD

Lock acquisition fails because another process holds the lock.

Why this answer

The error 'ConditionalCheckFailedException' occurs when DynamoDB's conditional put operation fails, which happens when a lock item already exists in the DynamoDB table. This indicates another Terraform process currently holds the state lock, preventing concurrent operations. Terraform uses DynamoDB's conditional writes to ensure only one process can acquire the lock at a time.

Exam trap

A common pitfall in Terraform exams is confusing S3 state file corruption with DynamoDB state lock contention. The ConditionalCheckFailedException specifically indicates that another process holds the lock, not that the state file is damaged.

How to eliminate wrong answers

Option A is wrong because a corrupted state file in S3 would cause a different error, such as 'Error loading state: JSON syntax error' or 'Failed to read state file', not a DynamoDB conditional check failure. Option B is wrong because if the DynamoDB table lacked a primary key named LockID, Terraform would fail during initialization with an error like 'Error configuring the backend' or 'DynamoDB table does not have a primary key attribute named LockID', not during a plan. Option C is wrong because S3 bucket versioning is not required for state locking; it is used for state file versioning and recovery, and its absence would not cause a DynamoDB conditional check failure.

Page 1 of 2 · 77 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Terraform Advanced Workflow questions.