Courseiva

HashiCorp Certified: Terraform Authoring and Operations Professional (AWS provider) (AWS provider) (AWS provider) — Questions 151–225

278 questions total · 4 pages · All types, answers revealed

Page 2

Page 3 of 4

Page 4
151
MCQmedium

You are using HCP Terraform agents. Why would you choose to use an agent instead of the public HCP Terraform execution environment?

A.To increase execution speed
B.To access resources in a private network
C.To bypass OPA policies
D.To avoid paying for HCP Terraform
AnswerB

HCP Terraform agents run inside your own infrastructure, so they can reach endpoints on private networks that the hosted execution environment cannot route to. This directly satisfies the stem's private-network access constraint, which the public runners cannot fulfil.

Why this answer

HCP Terraform agents run Terraform operations inside your own infrastructure, so they can reach private endpoints such as internal VPCs, on-prem databases, and private APIs that the hosted public execution environment cannot route to. The public runners only have internet-facing egress, so any resource behind a firewall or private DNS is unreachable. Choosing an agent is therefore about network reachability, not speed or cost.

Exam trap

The trap here is assuming agents exist for performance or cost reasons, when the exam is really testing that agents are the mechanism for reaching private-network resources.

How to eliminate wrong answers

Option A is wrong because agent-based execution is generally not faster than the public environment — it adds a network hop back to HCP Terraform and runs on your own hardware, so speed is not the driver. Option C is wrong because OPA/ Sentinel policy enforcement happens in HCP Terraform itself and applies to agent runs too; agents cannot bypass policy checks. Option D is wrong because HCP Terraform agents are a feature of paid plans and do not eliminate HCP Terraform billing — they exist for network access, not cost avoidance.

152
MCQeasy

Which of the following is a primary benefit of using a Private Module Registry?

A.It encrypts all Terraform state files.
B.It allows central management and version control of reusable modules.
C.It forces all workspaces to use the same module versions.
D.It automatically generates cost estimates for all modules.
AnswerB

A Private Module Registry stores modules within your own organisation, giving centralised publishing, semantic versioning and access control. This satisfies the need for central management and version control of reusable modules, unlike the public registry where you cannot govern or curate shared code.

Why this answer

A Private Module Registry (available in Terraform Cloud/Enterprise and as a self-hosted registry) provides a centralized, versioned catalog of reusable modules that teams can publish, discover, and consume. It enforces versioning and access control, so consumers pin module versions and get consistent, auditable infrastructure patterns across the organization. This is its primary benefit over ad-hoc Git-based module sourcing.

Exam trap

The trap is conflating the Private Module Registry with unrelated Terraform Cloud features like state encryption or cost estimation, or assuming it forces uniform versions across workspaces.

How to eliminate wrong answers

Option A is wrong because state file encryption is handled by the backend (e.g., S3 SSE, Terraform Cloud encryption), not by the module registry. Option C is wrong because the registry supports multiple module versions simultaneously — it does not force all workspaces onto the same version; consumers choose versions via constraints. Option D is wrong because cost estimation is a separate Terraform Cloud feature (cost estimation runs), not a function of the Private Module Registry.

153
MCQhard

A team's CI pipeline runs 'terraform init' on Linux amd64 runners, while developers run it on macOS arm64 laptops. After a developer commits .terraform.lock.hcl generated on their laptop, the CI pipeline fails with 'provider ... does not have a package available for your current platform'. What is the most appropriate fix?

A.Delete .terraform.lock.hcl from version control and let each environment regenerate it independently
B.Add a provider_installation block with direct = true so Terraform ignores the lock file on CI
C.Run 'terraform providers lock -platform=linux_amd64 -platform=darwin_arm64' and commit the updated lock file
D.Set the TF_PLUGIN_CACHE_DIR environment variable on the CI runner to reuse the developer's cached provider
AnswerC

The providers lock command with multiple -platform flags records package checksums for each specified platform in .terraform.lock.hcl. Including both linux_amd64 and darwin_arm64 ensures every environment finds a matching entry, so init succeeds on CI and developer machines while preserving checksum verification and version pinning.

Why this answer

The dependency lock file records checksums per platform. When it is generated on only one platform, other platforms cannot verify their provider packages and init fails. Regenerating the lock file with terraform providers lock using -platform for each target platform adds the required hashes while keeping the file committed for reproducibility.

Exam trap

The trap here is thinking the lock file is platform-agnostic and that any regenerated copy works everywhere, when in reality missing platform hashes cause init failures on other operating systems.

154
MCQmedium

You maintain a Terraform module that deploys AWS resources into several environments. Rather than declaring a separate variable per environment, you want a single input variable that accepts a map of environment names to configuration objects, where each object contains a region string and an instance count number, and your configuration should reject any input that does not match this shape at plan time. Which variable type constraint should you declare?

A.variable "environments" { type = list(object({ region = string, count = number })) }
B.variable "environments" { type = map(string) }
C.variable "environments" { type = map(object({ region = string, count = number })) }
D.variable "environments" { type = any }
AnswerC

A map(object({...})) constraint requires every value in the map to be an object whose attributes match the declared schema, so region must be a string and count a number. Terraform converts compatible values and raises a type error for mismatches during validation, which is exactly the plan-time rejection the scenario requires.

Why this answer

A map of objects is the only constraint that simultaneously enforces named environment keys and a fixed attribute schema with region as a string and count as a number. Terraform validates caller input against that schema during planning and converts compatible primitive values automatically, so malformed input fails early rather than producing broken resources later.

Exam trap

The trap here is assuming that any makes a variable flexible and safe, when in reality it disables the schema checking that would catch malformed environment objects.

155
MCQeasy

Where are lifecycle meta-arguments placed within a Terraform configuration?

A.At the root of the configuration file.
B.Inside the resource block, within a 'lifecycle' block.
C.Inside the module block.
D.Inside the provider block.
AnswerB

Lifecycle meta-arguments govern an individual resource's creation and destruction behaviour, so they nest inside the resource block as a lifecycle block. This satisfies the constraint that settings such as create_before_destroy apply only to that resource.

Why this answer

Lifecycle meta-arguments are used to customize the behavior of a specific resource, such as preventing its destruction or ignoring changes to certain attributes. They are defined within a nested 'lifecycle' block inside the resource block, as they directly modify that resource's lifecycle. This placement ensures the arguments apply only to that resource, not globally or to modules/providers.

Exam trap

The trap here is confusing where meta-arguments like 'lifecycle' can be placed, as some meta-arguments (e.g., 'count', 'for_each') can be used at both resource and module levels, but 'lifecycle' is exclusively a resource-level meta-argument.

How to eliminate wrong answers

Option A is wrong because placing lifecycle meta-arguments at the root of the configuration file is invalid; Terraform does not support lifecycle blocks at the root level, and such placement would cause a syntax error. Option C is wrong because while modules can have lifecycle-related settings, the 'lifecycle' meta-argument itself is not placed inside a module block; modules use other meta-arguments like 'count' or 'for_each', but lifecycle is resource-specific. Option D is wrong because provider blocks configure the provider plugin, not resource lifecycle behavior; lifecycle meta-arguments are not valid inside provider blocks.

156
MCQmedium

You are using a module from the public Terraform Registry in a production configuration. After running terraform init -upgrade, you notice that the module version changed unexpectedly and caused a breaking change in your infrastructure. You want to prevent this from happening again. Which approach should you take?

A.Run terraform init without the -upgrade flag after the initial installation.
B.Set the version argument to a range like ">= 1.0.0" to allow flexibility while avoiding major version changes.
C.Pin the module to a specific version using the version argument in the module block.
D.Use a local path to a copy of the module that you maintain manually.
AnswerC

Specifying an exact version constraint, such as version = "1.2.0", ensures that Terraform only uses that version. This prevents automatic upgrades from introducing breaking changes. The version argument is the standard mechanism for version pinning in Terraform modules, and it applies to modules from the Terraform Registry or other sources that support versioning.

Why this answer

Pinning the module to a specific version using the version argument ensures that Terraform always uses that exact version, preventing unexpected upgrades that could introduce breaking changes. While other methods like local copies or avoiding -upgrade might reduce risk, they do not provide the same level of control and are not enforced by Terraform. The version argument is the recommended and reliable way to lock a module version.

Exam trap

The trap here is assuming that running terraform init without -upgrade prevents future upgrades, but it only avoids upgrades during that specific command; it does not enforce a version constraint.

157
MCQmedium

Your team uses HCP Terraform to manage AWS infrastructure. You need to allow a specific team of developers to apply changes in a workspace, but you do not want them to be able to modify workspace settings or delete the workspace. Which team permission should you assign to the developers?

A.Write
B.Read
C.Plan
D.Admin
AnswerA

Write permission allows team members to read and write to the workspace, including queuing runs and applying changes, but does not permit modifying workspace settings or deleting the workspace. This exactly matches the requirement: developers can apply changes but cannot alter settings or delete.

Why this answer

Write permission in HCP Terraform allows users to perform runs, including apply, but restricts administrative actions like changing settings or deleting the workspace. This provides the necessary operational access while protecting the workspace configuration. Admin would give too much control, and Read would not allow applies.

Exam trap

The trap here is assuming that Write permission includes workspace deletion or settings modification, when in fact those actions require Admin permission.

158
MCQeasy

Your organization uses HCP Terraform with the AWS provider. You want to share a set of AWS region and tagging variables across all workspaces in a specific project without duplicating them in each workspace. Which HCP Terraform feature should you use?

A.Terraform input variables with default values in the root module.
B.Variable sets applied to the project.
C.Workspace-specific variables defined in each workspace's variables tab.
D.Environment variables set in the run's execution environment.
AnswerB

Variable sets allow you to define variables once and apply them to multiple workspaces, projects, or the entire organization. Applying a variable set to a project automatically makes those variables available to all workspaces within that project, satisfying the need for shared configuration.

Why this answer

Variable sets in HCP Terraform are designed to share variables across multiple workspaces. You can create a variable set containing the AWS region and tagging variables and apply it to the entire project, ensuring all current and future workspaces in that project inherit the variables. This centralizes management and reduces duplication.

Exam trap

The trap here is confusing variable sets with workspace-specific variables or Terraform input variables, which do not provide centralized sharing across a project.

159
MCQeasy

In HCP Terraform, you want to allow team members to see runs but prevent them from approving plans. Which team permission set should you assign?

A.Write
B.Admin
C.Read
D.Cost Estimation
AnswerC

Read permissions grant visibility into workspaces and runs without any write or approval capability, so members can inspect run status and logs while being blocked from approving plans. This satisfies both constraints in the stem: view runs, deny approvals. Approval rights require the Write permission set, which Read deliberately excludes.

Why this answer

The Read permission set in HCP Terraform grants team members the ability to view workspaces, runs, state, and variables, but it does not include the permission to apply runs or approve plans. Write permission is required to queue applies and approve plans, so Read is the correct choice to allow visibility without approval authority.

Exam trap

The trap is conflating 'see runs' with 'approve plans' — candidates may pick Write thinking it is needed to view runs, but Read already grants visibility while Write grants approval.

How to eliminate wrong answers

Option A is wrong because Write permission allows members to queue runs, apply plans, and approve plans — exactly what the question says to prevent. Option B is wrong because Admin grants full control including workspace deletion, variable management, and team access, which is far more than read-only visibility. Option D is wrong because Cost Estimation is not a team permission set in HCP Terraform; it is a feature that can be enabled on workspaces, not a permission level.

160
MCQeasy

You are writing a Terraform configuration that uses a `for` expression to transform a list of strings into a map where each string is both the key and the value. Which of the following expressions achieves this?

A.`[ for s in var.list : s => s ]`
B.`{ for s in var.list : s => s }`
C.`{ for s in var.list : s = s }`
D.`{ for s in var.list : key => value }`
AnswerB

This expression uses a `for` expression with the syntax `{ for s in var.list : s => s }`. It iterates over each element `s` in `var.list` and creates a map entry with key `s` and value `s`. This is the correct syntax for a map comprehension where both key and value are derived from the same element.

Why this answer

The correct expression is `{ for s in var.list : s => s }`. It uses a map comprehension with the `=>` separator, creating a map where each string is both key and value. The other options either use incorrect brackets, wrong separator, or undefined variables.

Exam trap

The trap here is mixing up list and map comprehension syntax. List comprehensions use `[ ]` without `=>`, while map comprehensions use `{ }` with `=>`.

161
MCQhard

A platform team wants to prevent any workspace in their HCP Terraform organization from provisioning EC2 instances with public IP addresses. They need the policy to block a run before apply whenever a non-compliant plan is detected, and they want the failure reason surfaced to the developer. Which approach meets these requirements?

A.Attach a Sentinel or OPA policy set to the organization with a hard-mandatory policy that inspects the plan and denies non-compliant EC2 resources.
B.Configure an AWS Config rule that flags instances with public IPs and rely on it to stop the Terraform apply.
C.Use a `terraform_data` resource with a local-exec provisioner to scan the plan JSON and fail the apply.
D.Add a `precondition` block to each EC2 resource that checks the public IP attribute during apply.
AnswerA

Policy sets are applied at the organization or workspace level, and a hard-mandatory policy evaluates the plan and blocks the run when it fails. Sentinel or OPA policies can inspect planned resource attributes such as `associate_public_ip_address` and return a descriptive failure message. This satisfies both pre-apply blocking and developer-visible failure reasons.

Why this answer

Organization-level policy sets with hard-mandatory enforcement evaluate the plan before apply and deny non-compliant changes. Because policies are attached centrally, every workspace is covered without per-module changes, and the policy can return a clear message explaining which attribute violated the rule, giving developers actionable feedback.

Exam trap

The trap here is choosing a post-deployment detector like AWS Config or a provisioner that runs too late to prevent the change.

162
MCQmedium

Your organization uses HCP Terraform with several projects. A compliance officer must be able to read the results of every policy evaluation and run across all projects, but must not be able to modify workspaces or trigger runs. Which approach grants exactly these rights?

A.Assign the officer the organization-level read permission and rely on project visibility to expose run and policy results.
B.Create a team with the plan permission on each workspace and add the officer to that team.
C.Add the officer to each project's team with the write permission set on every workspace.
D.Give the officer the organization owner role and instruct them not to make changes.
AnswerA

Organization-level read grants visibility into workspaces, runs, and policy evaluations across all projects without conferring the ability to modify settings or trigger runs. It scales automatically to new projects and workspaces, giving the compliance officer exactly the read-only cross-project view required.

Why this answer

Organization-level read permission is designed for users who need to observe activity across all projects without changing anything. It reveals workspace runs, plans, and policy evaluation results while withholding the ability to modify configuration or queue runs. Because it applies at the organization scope, it automatically covers future projects and workspaces the compliance officer must review.

Exam trap

The trap here is assuming per-workspace permissions are required for cross-project visibility, when organization-level read already covers all projects.

163
MCQhard

A module author wants to conditionally create an AWS CloudWatch log group only when a variable named enable_logging is true. The log group resource is defined inside a child module. Which approach correctly implements this conditional creation within the module?

A.Add a lifecycle block with create_before_destroy = var.enable_logging.
B.Use a count meta-argument on the resource with count = var.enable_logging ? 1 : 0.
C.Use a null_resource with a trigger that runs a local-exec provisioner to create the log group via AWS CLI.
D.Wrap the resource in a dynamic block with for_each = var.enable_logging ? [1] : [].
AnswerB

The count meta-argument can be used on any resource to conditionally create instances. Setting count = var.enable_logging ? 1 : 0 creates one instance when enable_logging is true and zero when false. This is a standard and supported pattern inside modules. The resource is then referenced using index syntax, such as aws_cloudwatch_log_group.example[0], when needed.

Why this answer

Conditional resource creation in Terraform is achieved using the count or for_each meta-arguments. Applying count = var.enable_logging ? 1 : 0 directly on the resource allows it to be created only when the variable is true. This pattern works inside modules and is the idiomatic way to conditionally manage resources.

Other methods like dynamic blocks or lifecycle arguments do not control resource existence.

Exam trap

The trap here is confusing dynamic blocks, which generate nested blocks, with meta-arguments like count that control whether a resource is created at all.

164
MCQhard

An operations engineer needs to remove an aws_iam_role and its attached aws_iam_role_policy_attachment from Terraform management without deleting the role in AWS, because the role is shared with an external team. The configuration for both resources will also be deleted from the repository. Which command sequence accomplishes this?

A.Delete the resource blocks from the configuration and run terraform apply -refresh=false so Terraform forgets the resources.
B.terraform state mv aws_iam_role.example aws_iam_role.shared, then terraform apply to drop the old address
C.terraform destroy -target=aws_iam_role_policy_attachment.example, then remove the aws_iam_role block from state with terraform import
D.terraform state rm aws_iam_role_policy_attachment.example, then terraform state rm aws_iam_role.example
AnswerD

terraform state rm detaches resources from state without calling any AWS API, so the role and its attachment remain intact in the account. Removing the attachment entry first avoids a dangling reference to a resource that no longer exists in state. After both entries are gone and the configuration is deleted, future plans ignore them entirely, which is exactly what a shared-resource handoff requires.

Why this answer

Unmanaging resources without deleting them in the cloud requires removing their entries from state. terraform state rm performs exactly that, issuing no provider API calls, and ordering the attachment before the role keeps the state consistent. Destroying, moving, or merely editing configuration all either delete the real objects or leave them tracked.

Exam trap

The trap here is confusing terraform state rm, which only forgets resources in state, with terraform destroy, which actually deletes the live AWS objects.

165
MCQeasy

You have written a Terraform module that outputs the ARN of an AWS S3 bucket. A user of the module wants to reference this output in their root configuration. How should they access it?

A.data.terraform_remote_state.<MODULE_NAME>.bucket_arn
B.output.<MODULE_NAME>.bucket_arn
C.module.<MODULE_NAME>.outputs.bucket_arn
D.module.<MODULE_NAME>.bucket_arn
AnswerD

Module outputs are accessed directly as attributes on the module object. The syntax is module.<MODULE_NAME>.<OUTPUT_NAME>. This allows the root configuration to use the output value in other resources or outputs. It is the standard way to reference module outputs in Terraform.

Why this answer

Module outputs are exposed as attributes on the module object. The correct reference is module.<MODULE_NAME>.<OUTPUT_NAME>. This allows the root configuration to consume the output value seamlessly.

Other options represent incorrect syntax or refer to different mechanisms like remote state.

Exam trap

The trap here is assuming an 'outputs' intermediate attribute, which does not exist in Terraform's module output referencing syntax.

166
MCQeasy

Where can you view the historical state versions in HCP Terraform?

A.The Variables tab
B.The Runs tab
C.The States tab
D.The Settings tab
AnswerC

The States tab within a workspace lists every historical state version, showing serial numbers, timestamps and who created each one. This is the dedicated interface for reviewing past state, satisfying the requirement to view historical state versions rather than only the current state.

Why this answer

The States tab in an HCP Terraform workspace displays the historical list of state versions, including the serial number, the run that produced each version, timestamps, and options to download or roll back. This is the dedicated location for inspecting state history.

Exam trap

The trap is confusing the Runs tab with the States tab — runs show execution history, but state versions are specifically under the States tab, and candidates often pick Runs by association.

How to eliminate wrong answers

Option A is wrong because the Variables tab manages workspace and environment variables, not state versions. Option B is wrong because the Runs tab shows the history of plan and apply runs, but state versions are viewed under the States tab. Option D is wrong because the Settings tab contains workspace configuration such as VCS connection, execution mode, and destruction settings, not state history.

167
MCQmedium

Your team manages AWS infrastructure with Terraform. A module needs to accept a map of environment names to instance types, where each instance type must be one of a fixed set of allowed values. You want Terraform to reject invalid configurations during plan with a clear error message. Which approach best validates the variable input?

A.Define the variable with type = map(string) and use a lifecycle precondition on each AWS instance resource that checks the instance type.
B.Define the variable with type = map(string) and add a validation block with a condition that checks each value against the allowed list using the contains function and alltrue.
C.Define the variable with type = map(string) and add a custom validation using the file function to read a list of allowed values from an external file.
D.Define the variable with type = map(string) and rely on the AWS provider to reject invalid instance types when the plan is applied.
AnswerB

This is correct because a validation block in a variable definition can enforce constraints on the variable's value. Using alltrue over a for expression that checks each map value against the allowed list ensures every entry is valid, and Terraform will produce a custom error message when the condition fails, stopping the plan early.

Why this answer

Variable validation blocks allow you to enforce custom constraints on input variables. By using a condition that checks all values in the map against a list of allowed instance types, you ensure that invalid configurations are caught during plan with a helpful error message. This is the intended way to validate complex variable inputs in Terraform.

Exam trap

The trap here is assuming that provider-level validation is sufficient, when the exam expects you to use variable validation for early, clear feedback.

168
MCQmedium

You need to ensure that a resource is always recreated if an associated data source value changes. Which meta-argument supports this?

A.create_before_destroy
B.replace_triggered_by
C.lifecycle_hooks
D.prevent_destroy
AnswerB

`replace_triggered_by` forces Terraform to destroy and recreate the resource whenever a referenced attribute or resource changes, satisfying the requirement that the resource is always recreated when the associated data source value changes. It accepts resource references directly, unlike `lifecycle` triggers, which only react to arbitrary values.

Why this answer

The replace_triggered_by meta-argument forces Terraform to destroy and recreate the resource whenever any of the referenced attributes or resources change, including data source values. It is designed exactly for the scenario where a resource must be replaced based on an external or computed value rather than a direct attribute reference. When the referenced value changes between plans, Terraform marks the resource for replacement.

Exam trap

The trap here is confusing create_before_destroy with a replacement trigger — candidates often pick it because it sounds like it controls recreation, but it only controls ordering, not the decision to replace.

How to eliminate wrong answers

Option A is wrong because create_before_destroy only controls the ordering of replacement (create the new instance before destroying the old) — it does not trigger replacement on its own. Option C is wrong because 'lifecycle_hooks' is not a real Terraform meta-argument; the lifecycle block contains create_before_destroy, prevent_destroy, ignore_changes, and replace_triggered_by, but there is no lifecycle_hooks argument. Option D is wrong because prevent_destroy does the opposite — it blocks destruction and causes an error if a plan would destroy the resource, rather than triggering recreation.

169
MCQhard

You are writing a Terraform module that creates an AWS S3 bucket. You want to ensure that the bucket name is globally unique and follows a naming convention that includes the AWS account ID and region. How can you generate a unique name within the module?

A.Use the random_id resource to generate a unique suffix and append it to the bucket name.
B.Use the timestamp() function to generate a unique name based on the current time.
C.Use the format() function with the account ID and region, and rely on AWS to enforce uniqueness.
D.Use the uuid() function to generate a unique string and use it as the bucket name.
AnswerA

The random_id resource generates a unique identifier that can be used as a suffix. By combining it with the account ID and region, you can create a globally unique bucket name that follows the convention. This is a common pattern for ensuring uniqueness in AWS resource names.

Why this answer

The random_id resource generates a unique, stable identifier that can be used as a suffix to ensure global uniqueness. When combined with account ID and region, it creates a name that follows the convention and is highly unlikely to collide. Other methods like uuid() or timestamp() either do not guarantee uniqueness or cause instability in the name across runs.

Exam trap

The trap here is assuming that account ID and region alone are sufficient for global uniqueness, but S3 bucket names must be unique across all AWS accounts, so additional randomness is required.

170
MCQhard

Your team maintains a Terraform module that provisions an AWS VPC. The module is used by multiple teams. You need to allow callers to customize the CIDR block but enforce a default if not provided. How should you define the variable in the module?

A.variable "vpc_cidr" { type = string }
B.variable "vpc_cidr" { type = string default = null }
C.variable "vpc_cidr" { type = string default = "10.0.0.0/16" }
D.variable "vpc_cidr" { type = string validation { condition = can(cidrhost(var.vpc_cidr, 0)) error_message = "Invalid CIDR" } }
AnswerC

This declaration defines a variable with a type and a default value. If the caller does not provide a value, Terraform uses the default. If the caller provides a value, it overrides the default. This meets the requirement to allow customization while enforcing a default when no value is given.

Why this answer

To allow callers to customize a value while providing a fallback, you define a variable with a default. The default is used only when the caller does not supply a value. This provides flexibility and ensures the module works even if the variable is omitted.

The other options either make the variable required or do not provide a valid default.

Exam trap

The trap here is confusing validation with defaulting; a validation block does not make a variable optional, and omitting a default still makes the variable required.

171
MCQhard

You are configuring a Sentinel policy for your HCP Terraform organization. The policy must prevent any Terraform run from creating an AWS S3 bucket without server-side encryption enabled. The policy should block the run if such a bucket is detected, but you want to allow administrators to override the policy in emergency situations. Which enforcement level should you set for the policy?

A.advisory
B.hard-mandatory
C.soft-mandatory
D.mandatory
AnswerC

Soft-mandatory policies block a run when the policy fails, but users with permission to manage policies can override the failure and allow the run to proceed. This matches the requirement to block non-compliant S3 buckets while allowing administrators to override in emergencies. It provides both enforcement and flexibility.

Why this answer

Soft-mandatory enforcement blocks a run when the policy fails but allows users with appropriate permissions to override the failure. This provides the necessary guardrail against unencrypted S3 buckets while still permitting emergency overrides. Hard-mandatory would block without override, and advisory would not block at all.

Exam trap

The trap here is assuming that hard-mandatory is the only way to block a run, overlooking that soft-mandatory also blocks but includes an override path, which is explicitly required.

172
MCQeasy

Which file is automatically generated to lock provider versions and their checksums?

A.terraform.tfstate
B.terraform.tfvars
C..terraform.lock.hcl
D.provider.tf
AnswerC

The `.terraform.lock.hcl` file is created automatically by `terraform init` to record the exact provider versions selected and their cryptographic checksums. This satisfies the stem's requirement for a generated file that locks versions and verifies integrity, ensuring consistent provider installations across runs and preventing tampering.

Why this answer

The .terraform.lock.hcl file is automatically generated by Terraform to lock provider versions and record their checksums. It ensures consistent provider versions across runs and verifies integrity.

Exam trap

The trap is confusing the lock file with state or variable files. Candidates might think terraform.tfstate locks providers, but it only stores resource state. The exam tests knowledge of the specific file for provider version locking.

How to eliminate wrong answers

Option A is wrong because terraform.tfstate stores the state of managed resources, not provider locks. Option B is wrong because terraform.tfvars is for variable values, not provider locking. Option D is wrong because provider.tf is a user-created configuration file for provider blocks, not an auto-generated lock file.

173
Multi-Selecteasy

Which of the following are valid ways to specify provider versions? (Select TWO)

Select 2 answers
A.In the required_providers block.
B.In the resource block.
C.In the backend block.
D.In the provider block using the 'version' argument (deprecated).
E.In the output block.
AnswersA, D

The `required_providers` block within a `terraform` block accepts a `version` argument, letting you pin or constrain a provider's version directly in configuration. This satisfies the stem's requirement for a valid specification method, as Terraform reads these constraints during initialisation to select a compatible provider release.

Why this answer

Option A is correct because Terraform's modern and recommended method for pinning provider versions is the required_providers block inside a terraform block, where each provider is listed with a source address and a version constraint (e.g., version = "~> 5.0"). Option D is correct because the legacy syntax allowed specifying a version argument directly inside a provider configuration block (e.g., provider "aws" { version = "~> 5.0" }), which still works but is deprecated in favor of required_providers. Option B is incorrect because resource blocks configure resource arguments and do not accept a provider version constraint.

Option C is incorrect because backend blocks configure state storage and locking, not provider versions. Option E is incorrect because output blocks only export values from the configuration and have no version attribute.

Exam trap

The trap is assuming version can be set anywhere provider-related — candidates pick resource or backend blocks, but only required_providers and the deprecated provider-block argument are valid.

174
MCQhard

You are using HCP Terraform with the AWS provider and have configured a policy set with Sentinel policies. A policy fails during a run, and the run is paused. You have the necessary permissions to override the policy. What is the effect of overriding a soft-mandatory policy failure?

A.The policy is automatically changed to advisory for all future runs.
B.The run continues, and the override is recorded in the audit log.
C.The policy is permanently disabled for the workspace.
D.The run is cancelled and must be restarted after the policy is fixed.
AnswerB

When a soft-mandatory policy fails and a user with override permissions chooses to override, the run proceeds, and the override action is logged in the audit trail. This ensures accountability while allowing flexibility. The policy remains in effect for future runs.

Why this answer

Overriding a soft-mandatory policy failure permits the current run to proceed, and the override is captured in the audit log for traceability. This mechanism balances enforcement with operational flexibility. The policy itself remains unchanged and will be enforced in subsequent runs.

Exam trap

The trap here is thinking that an override disables or alters the policy for future runs, when it only affects the current run and is logged.

175
MCQmedium

How can you debug the output of a complex 'for' expression in Terraform?

A.Check the state file
B.Use terraform plan
C.Use terraform console
D.Use terraform debug
AnswerC

terraform console evaluates expressions interactively against current state and variables, so you can inspect the intermediate result of a complex for expression without applying. This isolates whether the comprehension itself is malformed, satisfying the need to debug its output directly.

Why this answer

terraform console launches an interactive REPL where you can evaluate HCL expressions — including complex for expressions, functions, and variable references — against the current configuration and state, printing the result immediately. This makes it the fastest way to inspect what a for expression actually produces without running a full plan. It's the standard debugging tool for expression logic in Terraform.

Exam trap

The trap is assuming a general-purpose command like terraform plan or the state file can reveal expression output; candidates overlook that terraform console is the dedicated REPL for evaluating and debugging HCL expressions interactively.

How to eliminate wrong answers

Option A is wrong because the state file records resource attributes and metadata, not the evaluated output of arbitrary for expressions, so it cannot show you what an expression returns. Option B is wrong because terraform plan shows the resulting resource changes, not the intermediate value of a specific expression, making it impractical for isolating expression bugs. Option D is wrong because terraform debug is not a valid Terraform command — there is no such subcommand in the CLI.

176
Multi-Selectmedium

Which THREE of the following are consequences of drifting from the Terraform state?

Select 3 answers
A.The plan may show changes even if the config hasn't changed.
B.It can lead to 'Resource Not Found' errors if someone manually deletes an item.
C.It disables the use of lifecycle meta-arguments.
D.Terraform may attempt to revert changes during the next apply.
E.It automatically updates the configuration file.
AnswersA, B, D

Because the state file records the last-known real-world attributes, any out-of-band modification makes the stored values diverge from actual infrastructure. Terraform therefore reports a non-empty diff during plan even when the configuration itself is untouched, satisfying the drift-detection consequence.

Why this answer

Option A is correct because Terraform compares the configuration against the recorded state to build the plan; if real infrastructure has drifted from that state, the refresh will detect differences and the plan can show changes even though the .tf configuration itself was never modified. Option B is correct because if someone manually deletes a resource that still exists in the state file, the next refresh/plan will fail to find it and Terraform reports an error such as 'Resource Not Found' (or removes it from state depending on version), breaking the expected mapping between state and reality. Option D is correct because when drift is detected, Terraform's plan will propose actions to bring the real infrastructure back in line with the configuration, so the next apply may revert the out-of-band manual changes.

Option C is not correct because lifecycle meta-arguments (create_before_destroy, prevent_destroy, ignore_changes, replace_triggered_by) are configuration-level features and are not disabled by state drift. Option E is not correct because Terraform never rewrites your configuration files automatically; drift only affects the state and the plan, not the .tf source code.

Exam trap

The trap is believing drift disables lifecycle rules or auto-updates config — drift only affects state versus reality, not configuration semantics or lifecycle behavior.

177
Multi-Selectmedium

Which THREE pieces of information are displayed in the HCP Terraform Run UI?

Select 3 answers
A.The user who initiated the run
B.The raw state file in plain text
C.Policy check status
D.Plan output
E.Private cloud provider passwords
AnswersA, C, D

The Run UI records run metadata, and the initiating user is displayed so teams can trace who triggered the plan or apply. This satisfies the stem's requirement for information shown in the HCP Terraform Run UI, alongside status and timing details.

Why this answer

Option A is correct because the HCP Terraform Run UI shows run metadata including the identity of the user or team that triggered the run, which is essential for audit and collaboration. Option C is correct because Sentinel policy checks (and other policy evaluations) are surfaced in the run's UI with their pass/fail status, so users can see whether policies were enforced before apply. Option D is correct because the run's plan output, including the proposed resource changes and the diff, is displayed in the UI for review and approval.

Option B is not correct because the raw state file is not shown in plain text in the Run UI; state is stored securely and accessed via state versions or the API, not displayed as raw text. Option E is not correct because private cloud provider passwords are sensitive credentials and are never displayed in the Run UI; they are stored as sensitive variables and masked.

Exam trap

The trap here is confusing the Run UI with the States or Variables tabs — candidates assume raw state or credentials are visible in a run, but HCP Terraform deliberately hides both to preserve the security boundary.

178
Multi-Selectmedium

When debugging provider issues, which commands are most useful? (Select THREE)

Select 3 answers
A.terraform providers
B.TF_LOG=DEBUG
C.terraform fmt
D.terraform taint
E.terraform init
AnswersA, B, E

`terraform providers` lists every provider required by the current configuration and its child modules, showing the source address and version constraints each module declares. This directly exposes version conflicts or missing provider requirements during debugging, satisfying the need to inspect provider dependencies across the configuration.

Why this answer

Option A, `terraform providers`, is correct because it prints the provider requirements and the provider configuration tree for the current working directory, showing which providers each module uses and where they come from, which is essential when diagnosing provider source, version, or inheritance issues. Option B, `TF_LOG=DEBUG`, is correct because setting this environment variable enables detailed Terraform debug logging (including provider plugin communication and API calls), which is the primary way to trace provider errors and failures. Option E, `terraform init`, is correct because it initializes the working directory by downloading and installing the required provider plugins and modules, so it is the command used to resolve or reveal provider installation and version-constraint problems.

Option C, `terraform fmt`, is not correct because it only rewrites configuration files to canonical formatting and does not help diagnose provider behavior. Option D, `terraform taint`, is not correct because it merely marks a resource for destruction and recreation on the next apply, which is unrelated to debugging provider issues.

Exam trap

The trap is selecting formatting or taint commands as debugging tools — only providers, TF_LOG, and init actually expose provider installation, version, or runtime behavior.

179
MCQhard

Your organization uses HCP Terraform with Sentinel policies. A policy set is configured with enforcement level 'hard-mandatory' and includes a policy that checks for the presence of a 'CostCenter' tag on all AWS resources. During a run, the policy fails because a newly added aws_s3_bucket lacks the tag. What happens to the run?

A.The policy failure is recorded as an advisory and the run continues automatically.
B.The run is queued for manual review by an organization owner before apply.
C.The run pauses and waits for a user with override permissions to approve continuation.
D.The run fails immediately and cannot proceed to apply.
AnswerD

Hard-mandatory policies enforce strict compliance; if the policy fails, the run is halted and cannot continue to apply. There is no override option. In this scenario, the missing tag causes the policy to fail, so the run fails immediately. The user must fix the configuration and start a new run to proceed.

Why this answer

Hard-mandatory Sentinel policies enforce strict compliance and cannot be overridden. If the policy fails, the run is immediately halted and cannot proceed to apply. The user must correct the configuration to include the required tag and trigger a new run.

This ensures no non-compliant infrastructure is deployed.

Exam trap

The trap here is mixing up hard-mandatory with soft-mandatory; hard-mandatory fails the run outright, while soft-mandatory pauses for possible override.

180
MCQhard

A module accepts a variable 'environment' used only to build a name prefix. The team wants to prevent callers from passing values outside a fixed set without duplicating validation in every caller. What is the correct approach?

A.Declare the variable with type = string and rely on callers to pass correct values
B.Add a validation block inside the variable definition in the module
C.Use a precondition block on each resource that consumes the variable
D.Add a null_resource with a local-exec provisioner that validates the value at apply time
AnswerB

A validation block in the variable definition enforces the rule where the variable is declared, so every caller is checked automatically. Using a condition with contains() against the allowed set produces a clear error before any resources are planned, centralizing enforcement in the module.

Why this answer

Validation blocks inside a variable definition enforce constraints at the point of declaration, so all callers are checked consistently and errors surface during plan. Preconditions, type constraints, and provisioners either require duplication, do not restrict values, or run too late to be reliable for this requirement.

Exam trap

The trap here is choosing a precondition on resources, which works but must be duplicated and evaluates later than variable validation.

181
MCQmedium

You want to automate the approval process for non-production environments in HCP Terraform. Which setting enables this?

A.Configure Run Triggers
B.Set Sentinel policy to advisory
C.Enable Auto-apply
D.Use API-driven workflows
AnswerC

Auto-apply removes the manual confirmation gate, so a successful plan in a non-production workspace is applied without human approval. This directly satisfies the automation requirement, whereas manual apply would still require someone to approve each run.

Why this answer

Enabling Auto-apply in a workspace's settings allows HCP Terraform to automatically apply a successful plan without manual approval. For non-production environments, this streamlines the deployment process by removing the need for human intervention after the plan phase.

Exam trap

The trap is mixing up Run Triggers with Auto-apply; Run Triggers are for cross-workspace orchestration, while Auto-apply is for automating the apply step within a workspace.

How to eliminate wrong answers

Option A is wrong because Run Triggers are used to trigger runs in a workspace based on upstream workspace applies, not to automate approval within a workspace. Option B is wrong because Sentinel policies set to advisory only provide warnings and do not block or auto-approve runs; they do not automate the approval process. Option D is wrong because API-driven workflows involve triggering runs via the API, but they do not inherently automate the approval step; approval still requires a manual action unless Auto-apply is enabled.

182
MCQmedium

If a resource is not specified with a provider meta-argument, which provider instance does it use?

A.The first one defined.
B.The provider configuration without an alias.
C.The one with the latest version.
D.It causes an error.
AnswerB

When a resource omits the provider meta-argument, Terraform binds it to the default provider configuration — the one declared without an alias in the required_providers block. Aliased configurations are only selected through an explicit provider argument, so the unaliased instance is the implicit default.

Why this answer

When a resource omits the provider meta-argument, Terraform associates it with the default provider configuration — the one declared without an alias. Aliased provider configurations (e.g., provider "aws" { alias = "west" }) are only used when a resource explicitly references them via provider = aws.west. This default-association rule is fundamental to how Terraform resolves provider instances.

Exam trap

The trap is assuming Terraform uses the first-declared or latest-version provider; candidates miss that the unaliased (default) configuration is the one automatically applied when provider is omitted.

How to eliminate wrong answers

Option A is wrong because Terraform does not pick 'the first one defined' — provider selection is based on the absence of an alias, not declaration order. Option C is wrong because provider version selection is handled separately via required_providers version constraints, not by which configuration a resource uses. Option D is wrong because omitting the provider argument is perfectly valid and does not cause an error as long as a default (unaliased) provider configuration exists for that provider type.

183
MCQmedium

You are developing a Terraform module that creates an AWS EC2 instance. You want to expose the instance's private IP address to the caller. How should you define this in the module?

A.Define a local value in the module and reference it in the root module.
B.Add an output block in the module that references the instance's private_ip attribute.
C.Use a variable in the module to pass the private IP address to the caller.
D.Use a data source in the root module to look up the EC2 instance by its tags.
AnswerB

Outputs are used to expose values from a module to the parent configuration. By defining an output that references the EC2 instance's private_ip attribute, the caller can access this value. This is the correct way to share resource attributes from a child module.

Why this answer

Outputs are the mechanism for a module to return values to its caller. By defining an output that references the EC2 instance's private_ip attribute, the parent module can access it using module.<module_name>.<output_name>. This is the intended and most efficient way to expose resource attributes from a child module.

Other options either do not work or are overly complicated.

Exam trap

The trap here is thinking that variables can be used bidirectionally; variables only pass data into a module, while outputs pass data out.

184
MCQeasy

When using 'for_each' on a list of strings, what must you do to ensure the configuration is stable?

A.Use count instead
B.Convert the list to a set
C.Use the index
D.Nothing, it's always stable
AnswerB

for_each requires a map or set of unique keys; a list of strings can contain duplicates, producing unstable addresses and plan errors. Converting the list to a set guarantees unique keys, keeping resource instance addresses stable across runs.

Why this answer

for_each requires a map or set of strings, not a list, because list indices are positional and unstable — inserting or removing an element shifts every subsequent index, causing Terraform to destroy and recreate resources. Converting the list to a set (e.g., toset(var.list)) gives each element a stable key based on its value, so resource addresses remain consistent across changes.

Exam trap

The trap is believing for_each works directly on lists — candidates forget that Terraform requires a map or set, and that converting with toset() is the canonical fix for list inputs.

How to eliminate wrong answers

Option A is wrong because count is the less stable alternative — it uses numeric indices that shift when list order changes, which is exactly the instability for_each is designed to avoid. Option C is wrong because using the index (via count.index) reintroduces positional instability; for_each deliberately avoids index-based addressing. Option D is wrong because a raw list is never stable with for_each — Terraform rejects lists outright for for_each and requires a map or set, so 'nothing' is technically impossible as well as incorrect.

185
Multi-Selectmedium

Which THREE of the following are true about 'lifecycle' blocks?

Select 3 answers
A.They are defined inside the resource configuration block.
B.Multiple lifecycle arguments can be used in one block.
C.They allow changing the provider version dynamically.
D.They are inherited from the provider block.
E.They are evaluated during the planning phase.
AnswersA, B, E

A lifecycle block is nested within the resource block it modifies, applying only to that specific resource. This positional placement is what makes it a valid statement about lifecycle blocks, distinct from provider or terraform-level configuration.

Why this answer

Option A is correct because lifecycle blocks are nested meta-arguments declared inside a resource block (e.g., resource "aws_instance" "example" { lifecycle { ... } }), not at the top level or in provider blocks. Option B is correct because a single lifecycle block can contain multiple arguments simultaneously, such as create_before_destroy, prevent_destroy, ignore_changes, and replace_triggered_by. Option E is correct because lifecycle settings are processed during the plan phase, where Terraform determines actions like replacement (create_before_destroy) and diffs to ignore (ignore_changes) before producing the execution plan.

Option C is not correct because provider versions are constrained via the required_providers block and version arguments, not lifecycle. Option D is not correct because lifecycle is a resource-level meta-argument and is not inherited from provider blocks.

Exam trap

The trap here is confusing lifecycle meta-arguments with provider configuration — candidates often assume lifecycle settings can control provider versions or are inherited from provider blocks, but they are strictly resource-scoped planning directives.

186
MCQeasy

Which function is most useful when you have a nested list of objects and want to create a single flat list to iterate over with for_each?

A.concat()
B.flatten()
C.lookup()
D.merge()
AnswerB

flatten() collapses nested lists into a single-level list, so a list of lists of objects becomes one flat list of objects. This satisfies the stem's requirement to iterate the result with for_each, which rejects nested collections.

Why this answer

The flatten() function takes a nested list (list of lists) and returns a single flat list containing all elements. When you have a nested list of objects and want to iterate with for_each, flatten() collapses the nesting so each object becomes a top-level element that for_each can key on. This is the idiomatic Terraform pattern for iterating over nested collections.

Exam trap

The trap is confusing concat() with flatten() — concat() merges lists at one level, while flatten() recursively collapses nested lists; candidates often pick concat() when the question mentions 'nested'.

How to eliminate wrong answers

Option A is wrong because concat() concatenates two or more lists into one list but does not recursively flatten nested lists — it only merges the top level, leaving inner lists intact. Option C is wrong because lookup() retrieves a value from a map by key; it has nothing to do with flattening nested structures. Option D is wrong because merge() combines multiple maps into a single map, which is useful for maps but not for flattening a list of lists of objects.

187
MCQhard

You are managing a production database instance. You want to ensure that if a developer accidentally removes the resource block from the Terraform configuration, Terraform will refuse to destroy the database. How do you implement this?

A.Set prevent_destroy = true in the lifecycle block.
B.Set create_before_destroy = false.
C.Use the ignore_changes meta-argument for the lifecycle block.
D.Configure a provider-level block to disable deletions.
AnswerA

Setting `prevent_destroy = true` in the resource's `lifecycle` block makes Terraform reject any plan that would destroy the database, including removal of its resource block. This directly satisfies the stem's requirement that Terraform refuse destruction after an accidental configuration deletion, failing the apply with an error rather than deleting the instance.

Why this answer

The 'prevent_destroy' lifecycle meta-argument, when set to true, causes Terraform to reject any plan that would destroy the resource. This includes accidental removal of the resource block from configuration, which would otherwise trigger a destroy. It acts as a safety net for critical resources like production databases.

Exam trap

The trap is confusing 'prevent_destroy' with other lifecycle arguments like 'ignore_changes' or 'create_before_destroy'. Candidates might think 'ignore_changes' prevents destruction, but it only ignores attribute updates.

How to eliminate wrong answers

Option B is wrong because 'create_before_destroy = false' is the default behavior and does not prevent destruction; it only controls the order of creation and destruction. Option C is wrong because 'ignore_changes' is used to ignore changes to specific attributes, not to prevent resource destruction. Option D is wrong because there is no provider-level block to disable deletions; such control is at the resource level via lifecycle.

188
MCQmedium

When using multiple provider instances with different regions, what must be defined in the provider configuration?

A.A unique alias identifier.
B.A unique project ID.
C.A credentials object.
D.A version constraint in each block.
AnswerA

Multiple provider blocks for the same provider need a unique alias so resources and modules can reference the intended region explicitly, for example aws.west versus aws.east. Without distinct aliases Terraform cannot tell the instances apart.

Why this answer

When you declare multiple instances of the same provider (e.g., two `aws` providers for different regions), each non-default instance must have a unique `alias` argument. Resources then select the desired instance using the `provider = aws.<alias>` meta-argument. Without an alias, Terraform cannot distinguish the instances and errors on duplicate provider configuration.

Exam trap

The trap is thinking multiple provider blocks can coexist without aliases, or that credentials/version constraints are what differentiate them — the `alias` argument is the mandatory differentiator.

How to eliminate wrong answers

Option B is wrong because a 'project ID' is not a Terraform provider concept — it's a GCP-specific identifier and irrelevant to aliasing. Option C is wrong because a credentials object is not required to define multiple provider instances; credentials can be inherited from environment variables, shared config files, or IAM roles, and are orthogonal to aliasing. Option D is wrong because version constraints belong in `required_providers`, not in each aliased provider block, and are not what distinguishes multiple instances.

189
MCQmedium

Your team requires a custom module to be versioned strictly to prevent breaking changes during deployments. What is the recommended way to reference a module from a private Git repository?

A.Use the 'ref' parameter in the source URL string.
B.Set the 'version' block inside the module definition.
C.Copy the module code locally every time a new version is released.
D.Use the 'module_version' argument in the module block.
AnswerA

Using the `ref` parameter pins the module source to a specific Git tag, branch or commit, so deployments always fetch that immutable revision rather than the repository's moving default branch. This directly satisfies the strict versioning constraint, preventing upstream breaking changes from silently affecting your infrastructure during deployment.

Why this answer

For modules sourced from a private Git repository, Terraform does not support a separate 'version' argument; instead, you pin to a specific commit, tag, or branch using the 'ref' query parameter appended to the source URL (e.g., 'git::https://example.com/module.git?ref=v1.2.0'). This locks the module to an immutable Git reference, preventing unexpected breaking changes when the repository's default branch moves forward. The 'ref' parameter is the only supported mechanism for version pinning with Git-based module sources.

Exam trap

The trap here is confusing the registry-only 'version' argument with Git-based version pinning — candidates often assume 'version' works universally, but Terraform only supports 'ref' for Git sources, and the exam deliberately includes both to test that distinction.

How to eliminate wrong answers

Option B is wrong because the 'version' block is only valid for modules sourced from a Terraform Registry (public or private), not for arbitrary Git URLs — Terraform will error with 'Invalid version constraint' or simply ignore it for Git sources. Option C is wrong because manually copying module code into the local filesystem defeats the purpose of module reuse, introduces drift, and is not a versioning mechanism — it's an anti-pattern that breaks maintainability. Option D is wrong because 'module_version' is not a real Terraform argument; no such meta-argument exists in the module block, and candidates often confuse it with the registry-only 'version' argument.

190
MCQhard

How can you protect a module's inputs from receiving incorrect types of data?

A.Use the 'provider' block to enforce input types.
B.Use a 'validation' block with a condition inside the variable declaration.
C.Write a custom bash script to check the inputs.
D.Terraform automatically validates all inputs as strings.
AnswerB

A validation block inside the variable declaration evaluates a condition against the supplied value and returns an error message when it fails. This rejects malformed input at plan time, satisfying the requirement to guard against incorrect data types before resources are created.

Why this answer

Terraform's variable validation block, introduced in Terraform 0.13, allows you to define a condition expression that must evaluate to true for the variable value to be accepted. When placed inside a variable declaration, it can check the type, format, or range of the input and produce a custom error message if the condition fails. This is the native, declarative way to enforce input constraints at plan time, preventing invalid data from propagating into the module.

Exam trap

The trap here is confusing Terraform's automatic type checking with custom validation, leading candidates to think that simply declaring a type (e.g., string) is enough to protect against incorrect data, when in fact a validation block is needed for format or value constraints.

How to eliminate wrong answers

Option A is wrong because the 'provider' block configures the cloud provider (e.g., AWS region, credentials) and has no mechanism to validate module input types. Option C is wrong because a custom bash script is an external, imperative workaround that is not integrated with Terraform's validation lifecycle and would not run automatically during terraform plan or apply. Option D is wrong because Terraform does not automatically validate all inputs as strings; it performs type checking based on the declared type constraint, but it does not enforce custom validation rules unless a validation block is explicitly added.

191
MCQmedium

When using 'create_before_destroy', what is a common side effect that may cause the plan to fail?

A.Resource naming collisions.
B.Terraform will delete the state file.
C.Provider credentials will expire.
D.All other resources will be destroyed.
AnswerA

Creating the replacement before destroying the original means both exist simultaneously, so fixed names, unique DNS labels or static identifiers clash. The provider rejects the duplicate, causing the plan or apply to fail until the name is parameterised or the old resource is destroyed first.

Why this answer

With create_before_destroy, Terraform creates the new resource before destroying the old one. If the resource has a unique name or identifier (e.g., an AWS resource with a fixed name), the new resource may conflict with the existing one, causing the plan to fail due to naming collisions.

Exam trap

The trap is assuming create_before_destroy always works smoothly; candidates forget that resources with fixed names will collide. The exam tests whether you understand the side effect of creating a duplicate resource before destroying the original.

How to eliminate wrong answers

Option B is wrong because Terraform does not delete the state file during create_before_destroy; state is updated normally. Option C is wrong because provider credentials are not affected by lifecycle settings. Option D is wrong because create_before_destroy only affects the resource it's applied to, not all other resources.

192
MCQhard

Your team uses HCP Terraform with a VCS-driven workflow. You have a workspace that deploys to AWS. A developer wants to test a change that modifies an IAM policy without affecting the main branch. They create a feature branch and push changes, but the workspace is configured to track the `main` branch. What is the most appropriate way to allow the developer to test their change in isolation?

A.Change the existing workspace's VCS branch to the feature branch, run apply, then switch back to main.
B.Use the `-target` flag in a local `terraform apply` to apply only the IAM policy changes.
C.Create a new workspace that tracks the feature branch and uses the same Terraform configuration.
D.Create a run trigger from the main workspace to the feature branch workspace.
AnswerC

Creating a separate workspace that tracks the feature branch allows the developer to run plan and apply in isolation, using the same configuration but with its own state and variables. This prevents interference with the main workspace's state and infrastructure. It aligns with HCP Terraform's recommended pattern for branch-based development and testing, enabling safe experimentation before merging to main.

Why this answer

Isolating feature branch testing requires a separate workspace that tracks the feature branch, providing independent state and variables. Changing the existing workspace's branch or using local targeted applies introduces risk of state corruption or bypasses governance. Run triggers are for chaining workspaces, not for branch isolation.

Exam trap

The trap here is thinking that temporarily switching the workspace branch or using local CLI commands can safely test changes, when only a dedicated workspace provides proper isolation and state separation.

193
MCQeasy

Where are providers physically stored by default when running 'terraform init'?

A.The root module directory
B.~/.terraformrc
C..terraform/providers/
D./usr/local/bin/terraform
AnswerC

Terraform caches downloaded provider plugins in the .terraform/providers/ directory within the working directory, so subsequent runs reuse them without re-downloading. This satisfies the default storage location constraint, as init installs providers there unless a plugin cache directory is configured.

Why this answer

Terraform downloads providers into the .terraform/providers directory within your project working directory.

194
MCQeasy

Which function allows you to safely access a map value even if the key might not exist?

A.try()
B.element()
C.lookup()
D.coalesce()
AnswerC

lookup() retrieves a value from a map for a given key and returns null when the key is absent, rather than erroring. This makes it the safe accessor for potentially missing map keys in Terraform configurations.

Why this answer

The lookup() function is specifically designed to retrieve a value from a map by key while providing a fallback default if the key is absent, preventing errors. Its signature is lookup(map, key, default), so it safely handles missing keys without throwing an error. This makes it the idiomatic choice for optional map attributes in Terraform configurations.

Exam trap

The trap here is confusing lookup() with try() — both can handle missing data, but lookup() is the map-specific function with an explicit default argument, while try() is a general error-suppressing expression evaluator.

How to eliminate wrong answers

Option A is wrong because try() evaluates expressions and catches errors, but it is not the canonical map-key accessor and is typically used for nested attribute access on objects, not simple map lookups. Option B is wrong because element() retrieves an item from a list by index (wrapping around), not a value from a map by key. Option D is wrong because coalesce() returns the first non-null/non-empty argument from a list of values, not a map lookup by key.

195
MCQmedium

A CI pipeline runs Terraform against an AWS account and must assume a dedicated deployment role rather than use long-lived access keys. The role ARN differs between the staging and production pipelines. The team wants a single configuration that works in both environments without embedding credentials. Which approach correctly configures the AWS provider to assume the pipeline-specific role?

A.Define an input variable for the role ARN and reference it in the `assume_role` block of the AWS provider configuration.
B.Hardcode the production role ARN in the `provider "aws"` block and override it with a `-var` flag during staging runs.
C.Create two aliased AWS provider blocks, one per environment, and select the correct one using a `count` expression on the provider block.
D.Set the `AWS_ROLE_ARN` environment variable and rely on the AWS provider to assume that role automatically without any `assume_role` block.
AnswerA

The AWS provider's `assume_role` block accepts `role_arn`, `session_name`, and related arguments, and any of them can reference input variables. Feeding the role ARN from a variable lets the same configuration target staging or production based on the variable value supplied by the pipeline, without embedding credentials or duplicating provider blocks.

Why this answer

The AWS provider supports an `assume_role` block whose `role_arn` and related arguments can reference input variables. By parameterizing the role ARN, a single configuration serves both pipelines: each pipeline passes its own value through a `-var` flag, a `.tfvars` file, or workspace configuration. No credentials are embedded, and the provider assumes the correct role at plan and apply time.

Exam trap

The trap here is believing that an environment variable like `AWS_ROLE_ARN` alone makes the Terraform AWS provider assume a role, or that `-var` can override a hardcoded provider argument.

196
MCQmedium

You are configuring RBAC in HCP Terraform. A user needs to trigger runs and view plan logs but should not be allowed to modify workspace variables. Which permission set is appropriate?

A.Grant Admin access.
B.Grant 'Read' and 'Queue Plan' permissions.
C.Grant 'Manage Variables' permission.
D.Grant 'Write' permission to the workspace.
AnswerB

Granting Read plus Queue Plan satisfies the least-privilege requirement: Read exposes plan logs and workspace state, while Queue Plan permits triggering runs. Neither permission includes the variables:write capability, so the user cannot modify workspace variables. This precisely matches the stem's constraint of triggering runs and viewing logs without variable edit rights.

Why this answer

The 'Read' and 'Queue Plan' permissions allow a user to view workspaces and trigger runs, but not modify variables. This follows the principle of least privilege for the required actions.

Exam trap

The trap is granting 'Write' permission thinking it's needed to trigger runs. Candidates might confuse 'Write' with 'Queue Plan'. The exam tests understanding of the specific permission needed for triggering runs without variable modification.

How to eliminate wrong answers

Option A is wrong because Admin access grants full control, including modifying variables, which is excessive. Option C is wrong because 'Manage Variables' permission specifically allows modifying variables, which the user should not have. Option D is wrong because 'Write' permission allows modifying workspace settings and variables, which is more than needed.

197
MCQhard

A Sentinel policy is failing on a cost estimation result. What is the most likely cause if the cost estimation feature is enabled but the policy still fails?

A.The cost estimation provider is not configured for AWS.
B.The workspace does not have Sentinel enabled.
C.The API key for AWS is invalid.
D.The policy attempts to access cost data before the estimation has completed.
AnswerD

Cost estimation runs asynchronously after plan, so a policy evaluating cost data during the plan phase may execute before estimation finishes. The policy then reads an empty or incomplete result and fails, despite cost estimation being enabled.

Why this answer

Cost estimation in Terraform Cloud runs asynchronously after the plan. If a Sentinel policy references cost data (e.g., 'tfrun.cost_estimate') before the estimation has completed, the policy will fail because the data is not yet populated. This is the most likely cause when cost estimation is enabled but the policy still fails.

Exam trap

The trap is assuming that enabling cost estimation guarantees the data is available to Sentinel — candidates overlook the asynchronous timing and pick infrastructure-related causes (API key, provider config) instead of the race condition.

How to eliminate wrong answers

Option A is wrong because cost estimation is a Terraform Cloud feature that works with the AWS provider out of the box — there is no separate 'cost estimation provider' to configure for AWS. Option B is wrong because if Sentinel were not enabled, the policy would not run at all rather than fail on cost data. Option C is wrong because an invalid AWS API key would cause the plan itself to fail, not a Sentinel policy failure on cost estimation.

198
MCQhard

You need to output a complex object from a child module to be used by the root module. What is the best practice for defining the output?

A.Assign the output to a global variable in the root module.
B.Use a data source to read the child module's internal state.
C.Define an output block in the child module and reference it in the root module using the module prefix.
D.Write the output to a local file inside the module and read it in the root.
AnswerC

Outputs expose values across module boundaries; declaring an output block in the child module and referencing it as module.<name>.<output> in the root module is the standard mechanism. This satisfies the requirement to pass a complex object upward without duplicating logic.

Why this answer

Using explicit output blocks in the child module makes the data available for access via 'module.<module_name>.<output_name>'.

199
MCQhard

You are attempting to use a conditional expression to set a variable, but the types returned by the true and false results differ. What happens?

A.The result is coerced to a string
B.A type mismatch error is returned
C.It defaults to the true result type
D.Terraform automatically casts to the most flexible type
AnswerB

Terraform requires both conditional results to share a compatible type. When the true and false expressions return different types, evaluation fails with a type mismatch error rather than coercing one value, satisfying the stem's scenario.

Why this answer

In Terraform, a conditional expression requires both the true and false results to be of the same type. If they differ, Terraform returns a type mismatch error during evaluation. This is because Terraform's type system is strict and does not perform implicit type coercion in conditional expressions.

Exam trap

AWS provider exams often test the strictness of Terraform's type system in conditional expressions, tricking candidates into thinking Terraform will automatically coerce types when it actually errors out.

How to eliminate wrong answers

Option A is wrong because Terraform does not automatically coerce the result to a string; it raises an error. Option C is wrong because it does not default to the true result type; it requires both to be the same. Option D is wrong because Terraform does not automatically cast to the most flexible type; it enforces type consistency.

200
MCQhard

In a workspace, you define a variable named 'region'. How can you override this value for a specific run without changing the workspace configuration?

A.By editing the state file
B.By modifying the provider block
C.Using -var flag in terraform apply
D.By adding a new workspace
AnswerC

The -var flag passes an input variable value at the command line for that single terraform apply invocation, taking precedence over the workspace's stored value. The workspace configuration file remains untouched, satisfying the requirement to override without permanent change.

Why this answer

The '-var' flag allows you to override a variable's value for a specific Terraform run without modifying the workspace configuration. For example, 'terraform apply -var='region=us-west-2'' sets the value for that run only. Other options do not provide a way to override variables per run.

Exam trap

The trap is confusing workspace-level variable changes with per-run overrides, or thinking that editing the state file is a valid method.

How to eliminate wrong answers

Option A is wrong because editing the state file is not a supported or safe way to override variables; state files store resource attributes, not input variables. Option B is wrong because modifying the provider block changes the configuration itself, not a per-run override. Option D is wrong because adding a new workspace creates a separate environment with its own variables, but it does not override a variable for a specific run in the existing workspace.

201
MCQmedium

Your organization uses HCP Terraform with a VCS-driven workflow. A developer accidentally merges a change to the main branch that modifies a production workspace's Terraform code. The workspace is configured to auto-apply. Which mechanism can prevent the change from being applied immediately?

A.Use a Sentinel policy with 'soft-mandatory' enforcement.
B.Configure a run trigger to delay the apply.
C.Set the workspace's Terraform version to a specific version.
D.Enable 'Manual Apply' in the workspace settings.
AnswerD

Enabling 'Manual Apply' overrides the auto-apply setting and requires a user to manually confirm the apply after a successful plan. Even if auto-apply is enabled, manual apply forces an approval step. This directly prevents the change from being applied immediately without human intervention.

Why this answer

Manual Apply is the workspace setting that forces a user to explicitly confirm an apply after a successful plan, even if auto-apply is enabled. It acts as an approval gate. The other options do not prevent an immediate apply: run triggers are for cross-workspace runs, soft-mandatory policies allow overrides, and version pinning is unrelated.

Exam trap

The trap here is thinking that auto-apply cannot be overridden, or that a policy can block an apply without manual intervention.

202
MCQmedium

Your team uses HCP Terraform to manage AWS infrastructure. You need to ensure that all workspaces in a specific project automatically inherit a set of environment variables containing AWS credentials. These variables must be available to all runs in those workspaces without manual configuration. What is the most efficient way to achieve this?

A.Create a variable set with the environment variables and assign it to the project.
B.Define the variables in each workspace's Terraform configuration using a shared module.
C.Use the HCP Terraform API to create the variables in each workspace via a script.
D.Configure a run trigger that copies variables from a template workspace to the target workspaces.
AnswerA

Variable sets can be scoped to projects, and all workspaces within that project automatically inherit the variables. This eliminates the need to configure each workspace individually. It is the intended feature for sharing variables across multiple workspaces, and it supports environment variables, including sensitive ones.

Why this answer

Variable sets are designed to share variables across multiple workspaces. When assigned to a project, all workspaces in that project inherit the variables automatically, including new workspaces. This is the most efficient and maintainable solution.

Other options require manual intervention or do not provide automatic inheritance.

Exam trap

The trap here is overlooking the project-level scoping of variable sets and instead considering per-workspace configuration or API scripting, which are more labor-intensive and error-prone.

203
Multi-Selectmedium

A team is designing a reusable Terraform module that provisions an AWS VPC. They want to ensure the module is flexible and follows best practices for input variables. Which two practices should they implement? (Choose two.)

Select 2 answers
A.Provide default values for all input variables to simplify usage.
B.Avoid documenting variables in README to keep the module concise.
C.Mark variables that contain sensitive information with sensitive = true.
D.Define all variables as type = any to maximize flexibility.
E.Use validation blocks to enforce constraints on variable values.
AnswersC, E

Setting sensitive = true on a variable prevents its value from being displayed in Terraform plan and apply output. This is important for variables like passwords or API keys. It helps prevent accidental exposure of secrets in logs or console output. This practice is recommended for any variable that carries sensitive data, ensuring that the module adheres to security best practices.

Why this answer

Marking sensitive variables with sensitive = true and using validation blocks are both best practices for reusable modules. Sensitivity prevents secret leakage, while validation enforces input constraints and improves error handling. Avoiding defaults for critical variables, using explicit types, and documenting variables are also important.

These practices collectively make the module more secure, robust, and user-friendly.

Exam trap

The trap here is thinking that providing defaults for every variable or using type = any makes a module more flexible, when it actually reduces safety and clarity.

204
MCQhard

A module needs to render a JSON policy document where the list of allowed actions comes from a variable that may contain duplicates and mixed case, and the final output must be deterministic and free of duplicates. The engineer writes jsonencode({ Version = "2012-10-17", Statement = [{ Effect = "Allow", Action = local.actions, Resource = "*" }] }). Which local definition for local.actions best guarantees determinism and uniqueness?

A.actions = distinct(var.actions)
B.actions = sort(distinct(var.actions))
C.actions = toset(var.actions)
D.actions = sort(distinct([for a in var.actions : lower(a)]))
AnswerD

The for expression lowercases every action, distinct() removes duplicates including those that differed only by case, and sort() imposes a stable lexicographic order. The combination yields a deterministic, case-normalized, duplicate-free list regardless of input order, which is exactly what the policy document needs for reproducible JSON output across callers.

Why this answer

Wrapping the values in a for expression that applies lower() normalizes case, distinct() then collapses duplicates that previously differed only by capitalization, and sort() fixes a stable lexicographic order. The resulting list serializes identically for any caller passing the same logical set of actions, satisfying both determinism and uniqueness for the JSON policy.

Exam trap

The trap here is treating toset() as a deterministic container, when set ordering is undefined and jsonencode() may serialize its elements in an unstable sequence.

205
MCQhard

What is the result of a 'soft-mandatory' Sentinel policy failing during a run?

A.The run is immediately aborted.
B.The policy is skipped automatically.
C.The run pauses and waits for an override.
D.The run completes but triggers an alert.
AnswerC

Soft-mandatory sits between advisory and hard-mandatory on the enforcement scale: failure blocks the run but permits a privileged user to override, resuming it. Hard-mandatory cannot be overridden, and advisory only logs, so pausing for override matches the stem.

Why this answer

A soft-mandatory Sentinel policy, when it fails, causes the run to pause and wait for an override. This allows an authorized user to manually approve the run and continue, providing a balance between enforcement and flexibility. This is in contrast to hard-mandatory, which aborts the run immediately.

Exam trap

The trap is confusing soft-mandatory with hard-mandatory or advisory enforcement levels. Candidates might think soft-mandatory aborts the run or is skipped, but it actually pauses for override.

How to eliminate wrong answers

Option A is wrong because immediate abortion is the behavior of a hard-mandatory policy, not soft-mandatory. Option B is wrong because the policy is not skipped; it fails and requires intervention. Option D is wrong because the run does not complete; it pauses, and no alert is triggered by default.

206
MCQmedium

You need to share a module across your entire organization. Which registry type should you use?

A.The public Terraform Registry.
B.A shared network drive.
C.An S3 bucket with public read access.
D.A private module registry in Terraform Cloud or Enterprise.
AnswerD

A private module registry in Terraform Cloud or Enterprise publishes modules to a single organisation-wide namespace, so every team consumes the same versioned source. This satisfies the requirement to share one module across the entire organisation rather than per-workspace or public consumption.

Why this answer

A private module registry in Terraform Cloud or Enterprise is the correct answer because it is purpose-built for sharing Terraform modules within an organization. It provides versioned, discoverable modules with access control, integrates natively with Terraform CLI/Cloud workflows, and supports private module sourcing via the `terraform init` command. This ensures secure, consistent, and governed reuse across teams, which is exactly what the scenario requires.

Exam trap

The trap here is confusing general-purpose storage (like S3 or network drives) with a Terraform-native private registry, or assuming the public registry can be used for private sharing; candidates often overlook the need for access control, versioning, and integration with Terraform workflows.

How to eliminate wrong answers

Option A is wrong because the public Terraform Registry is open to everyone and is intended for publicly available modules, not for private organizational sharing; using it would expose proprietary code and lacks access controls. Option B is wrong because a shared network drive is not a Terraform-native module source; Terraform cannot directly reference modules from arbitrary file shares without custom setup, and it provides no versioning, access control, or integration with Terraform workflows. Option C is wrong because an S3 bucket with public read access is insecure and not a supported module registry; while Terraform can fetch modules from S3, public read access violates security best practices and lacks the governance, versioning, and discoverability features of a private registry.

207
MCQhard

Your team uses HCP Terraform with a workspace connected to a GitHub repository. You need to ensure that no changes can be applied to production unless a specific compliance policy passes. The policy should block the apply if it fails, but authorized users should be able to override the failure with a justification. Which Sentinel enforcement level should you use?

A.mandatory
B.soft-mandatory
C.advisory
D.hard-mandatory
AnswerB

Soft-mandatory enforcement blocks the apply if the policy fails, but allows users with the appropriate permissions to override the failure and proceed, typically after providing a reason. This matches the requirement to block non-compliant changes while permitting authorized overrides with justification.

Why this answer

Soft-mandatory enforcement blocks an apply when a policy fails but permits authorized users to override the failure with a justification. This balances compliance with operational flexibility. Advisory does not block, hard-mandatory does not allow overrides, and 'mandatory' is not a valid enforcement level.

Exam trap

The trap here is confusing soft-mandatory and hard-mandatory, or assuming that advisory provides blocking.

208
MCQmedium

You are managing state in a multi-region deployment. You need to ensure that simultaneous terraform apply operations do not corrupt the state file. Which backend configuration parameter primarily enables this functionality?

A.workspace_key_prefix
B.kms_key_id
C.acl
D.dynamodb_table
AnswerD

The `dynamodb_table` parameter enables state locking by writing a lock item to a DynamoDB table before any apply begins, so a second concurrent `terraform apply` fails rather than corrupting the shared state file. This directly satisfies the stem's requirement that simultaneous operations across regions cannot overwrite each other's state.

Why this answer

The dynamodb_table parameter in an S3 backend configuration enables state locking by having Terraform write a lock item to a DynamoDB table before any apply, preventing concurrent operations from corrupting the state file. Without it, two simultaneous applies could both read and write the same state object, causing lost updates or inconsistent resource tracking.

Exam trap

The trap here is confusing encryption or access-control parameters (kms_key_id, acl) with locking — candidates who skim often pick kms_key_id because 'security' sounds like it prevents corruption.

How to eliminate wrong answers

Option A is wrong because workspace_key_prefix only controls the S3 key path for non-default workspaces; it has no locking semantics. Option B is wrong because kms_key_id enables server-side encryption of the state object at rest, not concurrency control. Option C is wrong because acl sets the S3 object ACL (e.g., private, bucket-owner-full-control) and does not prevent simultaneous writes.

209
MCQmedium

You have a nested module structure. How can you pass a variable from the root module through an intermediate module to a leaf module?

A.Define the variable only in the leaf module and refer to root by index.
B.You must define the variable in the intermediate module and pass it to the leaf module.
C.You can use the 'global_vars' block in the root.
D.The intermediate module automatically inherits all root variables.
AnswerB

Terraform modules have no implicit variable inheritance, so the intermediate module must declare the variable in its own variables block and explicitly forward it via an argument in its module call to the leaf. This explicit pass-through satisfies the root-to-leaf requirement.

Why this answer

In Terraform, variables are not automatically inherited by child modules. To pass a variable from the root module to a leaf module through an intermediate module, you must explicitly define the variable in the intermediate module and pass it to the leaf module. This means declaring the variable in the intermediate module's variables.tf and then using it in the module block that calls the leaf module.

Exam trap

AWS provider exam often tests the misconception that variables are automatically inherited by child modules or that there is a global variable mechanism. The trap is assuming implicit inheritance.

How to eliminate wrong answers

Option A is wrong because you cannot refer to root module variables by index from the leaf module; modules do not have implicit access to parent variables. Option C is wrong because there is no 'global_vars' block in Terraform; variables must be explicitly passed. Option D is wrong because intermediate modules do not automatically inherit root variables; all variables must be explicitly declared and passed.

210
MCQhard

You are writing an OPA (Open Policy Agent) policy to restrict resource creation. You want to deny any EC2 instance that does not include the 'CostCenter' tag. How do you access the resource attributes in the policy?

A.terraform.tags
B.input.resource_changes
C.state.output
D.var.tags
AnswerB

OPA evaluates Terraform plan JSON, where every proposed change appears under input.resource_changes. Each entry carries the resource type, address and planned values, so the policy can inspect the EC2 instance's tags block and deny the run when 'CostCenter' is absent.

Why this answer

OPA policies for Terraform evaluate a JSON document that Terraform sends to the policy engine, and the resource attributes live under input.resource_changes. Each entry in that array contains the address, type, and the planned change with after values, so a policy checks input.resource_changes[_].change.after.tags for the CostCenter tag. This is the correct path to access resource attributes.

Exam trap

The trap is assuming OPA sees Terraform variables or state outputs directly, when the policy input is the plan JSON and resource attributes are nested under input.resource_changes.

How to eliminate wrong answers

Option A is wrong because 'terraform.tags' is not a valid OPA input path — OPA does not expose a terraform namespace. Option C is wrong because 'state.output' is not part of the policy input document; outputs are not the mechanism for inspecting resource changes. Option D is wrong because 'var.tags' refers to Terraform variables, which are not exposed to OPA in the resource_changes structure.

211
MCQeasy

What is the primary difference between 'count' and 'for_each' regarding state management?

A.for_each is only for maps
B.for_each does not support complex objects
C.count is faster than for_each
D.count uses index-based indexing, causing potential recreation when items are removed
AnswerD

count addresses instances by numeric index, so removing an item shifts subsequent indices and forces recreation of those resources. for_each keys instances by map or set value, so removing one item only affects that instance, avoiding unrelated recreation.

Why this answer

The primary difference is that `count` uses index-based indexing, so removing an item from the middle of a list causes all subsequent resources to be re-indexed, potentially leading to unnecessary recreation. `for_each` uses key-based indexing, so removing an item only affects that specific resource, avoiding recreation of others.

Exam trap

The trap is thinking that `count` and `for_each` are interchangeable, but the index-based nature of `count` can cause unintended resource recreation when items are removed from the middle of a list.

How to eliminate wrong answers

Option A is wrong because `for_each` can accept both maps and sets of strings, not only maps. Option B is wrong because `for_each` supports complex objects as values in the map. Option C is wrong because there is no inherent speed difference between `count` and `for_each`; performance depends on the provider and resource.

212
MCQhard

You want to pass a complex object type to a module, but you need to ensure specific attributes are present. How do you define this in the variable block?

A.type = map(any)
B.type = list(object)
C.type = object({...})
D.type = tuple([...])
AnswerC

An object type constraint declares named attributes with their individual types, so Terraform validates that every required attribute is present and correctly typed. This enforces the specific attributes the stem demands, unlike map or any, which permit arbitrary keys.

Why this answer

The object({...}) type constraint lets you define a schema with specific named attributes and their types, ensuring required attributes are present and correctly typed. This is the correct way to pass a complex object with enforced structure to a module. It validates at plan time and rejects missing or extra attributes as configured.

Exam trap

The trap is choosing map(any) for structured data — map(any) does not enforce specific attribute names, so required attributes can be missing without a plan-time error.

How to eliminate wrong answers

Option A is wrong because map(any) only enforces that all values are of the same type and does not define specific required attribute names. Option B is wrong because list(object) is not valid syntax — object requires a schema, and list(object) without attribute definitions is incomplete. Option D is wrong because tuple([...]) defines a fixed-length sequence of typed values by position, not a named-attribute object, so it cannot enforce specific attribute names.

213
MCQhard

Your organization uses HCP Terraform with projects to group workspaces by business unit. A compliance rule states that any workspace in the 'finance' project must have a cost estimation check that fails the run if the monthly cost increase exceeds $500. You have enabled cost estimation in the organization settings. What should you do next to enforce this rule?

A.Configure a run trigger from a cost monitoring workspace to the finance workspaces to automatically reject runs that exceed the threshold.
B.Create a Sentinel policy that uses the tfrun import to access the cost estimation data and enforce a hard-mandatory policy when the delta exceeds $500.
C.Enable the 'Cost Estimation' setting on each finance workspace and manually review the cost estimate before applying.
D.Set a workspace variable named COST_THRESHOLD to 500 and rely on Terraform's AWS provider to enforce it during plan.
AnswerB

Sentinel policies can access cost estimation results through the tfrun import, specifically the cost_estimate data. A hard-mandatory policy can evaluate the monthly cost delta and fail the run if it exceeds the threshold, providing the required enforcement for the finance project.

Why this answer

Cost estimation in HCP Terraform provides data that Sentinel policies can evaluate. By writing a hard-mandatory policy that checks the monthly cost delta from the cost estimate and fails if it exceeds $500, you enforce the compliance rule automatically for all runs in the finance project. This leverages the existing cost estimation feature and the policy-as-code framework.

Exam trap

The trap here is thinking that enabling cost estimation alone enforces a threshold, when it only provides data that must be acted upon by a policy or manual process.

214
Multi-Selecteasy

Which THREE components are part of the 'Workspace' object in HCP Terraform?

Select 3 answers
A.State file
B.Billing invoice history
C.Global provider plugins
D.Run history
E.Variables
AnswersA, D, E

Each HCP Terraform workspace stores its own state file, holding the recorded resource attributes and serial for the infrastructure it manages. State is a core component of the workspace object, distinct from configuration, which lives in the linked VCS repository.

Why this answer

In HCP Terraform, a Workspace is the fundamental unit that groups a Terraform configuration with its associated data, and the state file (A) is a core component because it stores the mapping between resources and real infrastructure, enabling plan and apply operations. Run history (D) is also part of the Workspace object, as each workspace records the sequence of runs (plan, apply, destroy) along with their status, logs, and outcomes. Variables (E) are included because workspaces hold both Terraform variables and environment variables that parameterize runs, with values that can be set per workspace and marked sensitive.

Billing invoice history (B) is not a workspace component; it belongs to the organization or account billing level. Global provider plugins (C) are not part of a workspace either, since provider plugins are installed and cached at the run environment or organization level, not stored within the workspace object itself.

Exam trap

The trap is including organization-level or runner-level concerns like billing or provider plugins as workspace components — candidates conflate 'things a workspace uses' with 'things a workspace IS'.

215
MCQeasy

Which command helps verify if the providers are properly initialized?

A.terraform validate
B.terraform show
C.terraform plan
D.terraform providers
AnswerD

`terraform providers` lists every provider required by the configuration alongside its source address and version constraints, reading the dependency lock file and module manifests. This directly satisfies the stem's requirement to verify proper initialisation, since missing or uninitialised providers appear as unresolved entries rather than confirmed installations.

Why this answer

'terraform providers' lists all providers required by the configuration, confirming they are initialized.

216
MCQmedium

When refactoring code, you rename a resource in your configuration. What happens if you run 'terraform plan' without updating the state?

A.Terraform will propose destroying the old resource and creating a new one.
B.Terraform will do nothing.
C.Terraform will automatically rename it in the state.
D.Terraform will throw an error and stop.
AnswerA

Terraform tracks resources by address in state. Renaming the block changes its address, so the plan shows the old address destroyed and the new one created, unless a moved block or state mv is used.

Why this answer

Renaming a resource in configuration changes its address, so Terraform sees the old address as removed and the new address as added, resulting in a plan to destroy the old resource and create a new one. State still maps the old address to the real resource, so Terraform cannot associate the new name with the existing object. This is why terraform state mv is used to rename without destruction.

Exam trap

The trap is assuming Terraform recognizes renamed resources as the same object — it does not, because state is keyed by address, not by resource identity.

How to eliminate wrong answers

Option B is wrong because Terraform does not ignore the rename; it detects the address change and plans replacement. Option C is wrong because Terraform never automatically renames resources in state — state changes only occur via apply, state mv, or import. Option D is wrong because Terraform does not error on a rename; it simply plans a destroy/create cycle, which is valid behavior.

217
MCQeasy

You are configuring a new HCP Terraform workspace that uses a VCS connection to a GitHub repository. You want runs to be automatically triggered when changes are pushed to the main branch. Which setting should you enable?

A.Automatic run triggering
B.Speculative plans
C.Run triggers
D.Auto-apply
AnswerA

In HCP Terraform, the 'Automatic run triggering' setting, when enabled, causes a run to be queued whenever a change is pushed to the tracked branch in the VCS repository. This is exactly what is needed to trigger runs on pushes to the main branch. It is a standard feature for VCS-driven workflows.

Why this answer

HCP Terraform's VCS integration includes an 'Automatic run triggering' setting. When enabled, any commit to the tracked branch (e.g., main) queues a new run. This is the correct setting to achieve automatic runs on code pushes.

Other options like run triggers, auto-apply, and speculative plans serve different purposes and do not initiate runs on VCS changes.

Exam trap

The trap here is confusing 'run triggers' with automatic run triggering; run triggers are for workspace dependencies, not VCS events.

218
MCQmedium

You need to ensure that all workspaces use a specific set of tags. How can this be enforced?

A.Using an HCP Terraform Sentinel policy.
B.Using a VCS branch protection rule.
C.Using a variable validation block.
D.Enabling 'Strict Mode' in the organization settings.
AnswerA

Sentinel is HCP Terraform's policy-as-code engine, evaluating plans against rules before apply. A policy can require specific tag keys on every workspace resource, blocking non-compliant runs, which directly enforces the mandated tag set across all workspaces.

Why this answer

HCP Terraform Sentinel policies are policy-as-code rules that are evaluated during the plan phase of a run. Sentinel policies can inspect the planned state of resources and enforce constraints such as requiring specific tags on all taggable resources. Because Sentinel operates at the organization level and can be applied to all workspaces, it is the correct way to enforce a consistent tagging standard across every workspace.

Exam trap

The trap is confusing Terraform-native validation (variable validation blocks) with organization-level policy enforcement — candidates often pick variable validation because it sounds like a validation mechanism, but it cannot inspect resource tags.

How to eliminate wrong answers

Option B is wrong because VCS branch protection rules control who can merge code into branches — they have no visibility into Terraform resource attributes like tags and cannot enforce tagging at plan time. Option C is wrong because a variable validation block only validates the value of a single input variable within a module; it cannot inspect resource-level tags or enforce them across all workspaces. Option D is wrong because HCP Terraform does not have a 'Strict Mode' organization setting for enforcing tags — this is a fabricated feature.

219
MCQhard

When migrating from local state to HCP Terraform, which command is used to initialize the migration?

A.terraform login
B.terraform push
C.terraform init
D.terraform migrate
AnswerC

`terraform init` detects the existing local backend configuration and prompts to migrate state to HCP Terraform's remote backend, copying `terraform.tfstate` to the workspace. This satisfies the migration constraint directly, since no separate import or push command exists for backend transitions.

Why this answer

The 'terraform init' command is used to initialize a Terraform working directory, and when migrating from local state to HCP Terraform, it detects the backend configuration change and prompts to migrate the state. This is the standard command to set up the backend and perform the migration. Other commands are not used for this purpose.

Exam trap

The trap is thinking that a dedicated 'terraform migrate' command exists, or confusing 'terraform init' with 'terraform login' for authentication.

How to eliminate wrong answers

Option A is wrong because 'terraform login' is used to authenticate to HCP Terraform, not to initialize or migrate state. Option B is wrong because 'terraform push' is a deprecated command from older Terraform versions and is not used for migration. Option D is wrong because 'terraform migrate' is not a valid Terraform command.

220
Multi-Selecteasy

Which TWO of the following are standard stages of an HCP Terraform run pipeline?

Select 2 answers
A.Policy Check.
B.Code linting.
C.Plan.
D.Automatic refactoring.
E.State migration.
AnswersA, C

Policy Check is a distinct pipeline stage where Sentinel policies evaluate the plan before apply, enforcing governance. It runs after Plan and before Apply, so it satisfies the requirement for a standard HCP Terraform run stage.

Why this answer

Option A (Policy Check) is correct because HCP Terraform's run pipeline includes a Policy Check stage where Sentinel or OPA policies are evaluated against the plan before it can be applied, enforcing governance and compliance. Option C (Plan) is correct because the Plan stage is a core phase of every run, where Terraform generates an execution plan comparing the current state to the desired configuration. The pipeline stages are typically Plan, Policy Check, and Apply, so these two fit the standard sequence.

Option B (Code linting) is not a pipeline stage; linting is done externally by tools like tflint or pre-commit hooks, not by HCP Terraform's run workflow. Option D (Automatic refactoring) is not a feature of the run pipeline; Terraform does not automatically rewrite configurations. Option E (State migration) is not a pipeline stage; state migration occurs when changing backends or workspaces, not as a standard run phase.

Exam trap

HCP Terraform exams often test whether candidates confuse real pipeline stages (Plan, Policy Check, Apply) with generic software practices like linting or refactoring.

221
MCQmedium

If a user wants to ensure that a resource's lifecycle is managed by Terraform but wants to bypass the 'prevent_destroy' protection, what is the best approach?

A.Add 'ignore_changes = [prevent_destroy]' to the block.
B.Use 'terraform state rm' to remove the constraint.
C.Use 'terraform destroy -force-remove-prevent-destroy'.
D.Remove the prevent_destroy block from the configuration and apply.
AnswerD

Removing the prevent_destroy argument eliminates the protection at its source, so the subsequent apply can destroy and recreate the resource. Terraform still manages the lifecycle, satisfying the stem's requirement to retain management while bypassing the guard.

Why this answer

The prevent_destroy lifecycle meta-argument is a configuration-level protection, not a state-level one. To bypass it, you must edit the configuration to remove (or comment out) the prevent_destroy argument from the lifecycle block, then run terraform apply so the plan reflects the new configuration. Only after the argument is gone from the config can terraform destroy proceed against that resource.

Exam trap

The trap here is assuming prevent_destroy can be overridden at runtime via a CLI flag or state manipulation, when in reality it can only be removed by editing the configuration itself.

How to eliminate wrong answers

Option A is wrong because ignore_changes only accepts resource attribute names to ignore during diff calculation — prevent_destroy is a lifecycle meta-argument, not an attribute, so it cannot be listed there. Option B is wrong because terraform state rm removes the resource from state entirely, which would cause Terraform to lose track of the real infrastructure rather than simply bypassing the protection. Option C is wrong because terraform destroy has no such flag as -force-remove-prevent-destroy; the CLI does not provide a command-line override for prevent_destroy.

222
MCQmedium

You manage an Amazon RDS instance with Terraform. During an unrelated deployment, a junior engineer runs `terraform apply` and the instance is unexpectedly destroyed and recreated, causing a brief outage. You need to ensure that future `terraform apply` runs fail before any destructive change can be planned for this database. Which configuration should you add to the `aws_db_instance` resource?

A.Add `lifecycle { prevent_destroy = true }` to the `aws_db_instance` resource.
B.Add `lifecycle { create_before_destroy = true }` to the `aws_db_instance` resource.
C.Run `terraform state rm aws_db_instance.main` to detach the instance from state.
D.Add `lifecycle { ignore_changes = [engine] }` to the `aws_db_instance` resource.
AnswerA

Adding a lifecycle block with prevent_destroy set to true causes Terraform to reject any plan that would destroy the RDS instance, failing the apply before the destructive action occurs. This protects the database from accidental replacement caused by configuration drift or an unintended change to a force-new attribute, which is exactly the outage scenario described.

Why this answer

The prevent_destroy lifecycle argument is the only mechanism that makes Terraform refuse to execute a plan containing the destruction of that specific resource. It acts as a guardrail during the plan phase, so the apply fails before any destructive API call is made. ignore_changes, create_before_destroy, and state rm all address different concerns and none of them block a replacement.

Exam trap

The trap here is assuming that any lifecycle meta-argument protects a resource from deletion, when only prevent_destroy actually blocks a destroy plan.

223
MCQeasy

Which block is used to configure provider-level settings like region or profile?

A.module {}
B.provider "aws" {}
C.terraform {}
D.resource "aws_instance" {}
AnswerB

The provider block, such as provider "aws" {}, declares and configures the provider plugin, accepting arguments like region and profile. This directly satisfies the requirement to set provider-level settings, since these values are passed to every resource managed by that provider.

Why this answer

The 'provider' block is used to configure the provider itself.

224
Multi-Selecthard

Your organization runs HCP Terraform with the AWS provider and wants to enforce a policy that blocks any `aws_s3_bucket` resource lacking a `lifecycle_rule` block. You are authoring a Sentinel policy that uses the `tfplan/v2` import. Which two statements correctly describe how the policy is evaluated and enforced? (Choose two.)

Select 2 answers
A.The Sentinel policy is evaluated against the plan JSON produced by a plan run, and a hard-mandatory failure prevents the apply from proceeding.
B.The `tfplan/v2` import exposes only the final resource attributes, so `lifecycle_rule` blocks cannot be detected in the plan.
C.Sentinel policies can only be attached at the workspace level and cannot be applied across an entire organization.
D.Sentinel policies are evaluated only after the apply completes, so violations are reported but infrastructure is already modified.
E.A soft-mandatory policy failure allows an authorized user to override the failure and continue the apply, whereas hard-mandatory blocks it entirely.
AnswersA, E

Sentinel policies using the tfplan/v2 import inspect the structured plan representation before any infrastructure changes occur. When a policy has hard-mandatory enforcement, a failing rule halts the run and the apply cannot proceed, which is precisely how you block a bucket without a lifecycle_rule. This is the intended mechanism for preventive governance in HCP Terraform.

Why this answer

Sentinel evaluates the plan before apply, so a hard-mandatory failure blocks a non-compliant S3 bucket from ever being created, while soft-mandatory allows an authorized override. Both facts reflect how policy sets are enforced in HCP Terraform. Post-apply-only evaluation, workspace-only scoping, and an inability to inspect nested blocks are all incorrect characterizations of the Sentinel workflow.

Exam trap

The trap here is conflating Sentinel's pre-apply plan evaluation with post-apply compliance scanning, and confusing soft-mandatory override behavior with hard-mandatory blocking.

225
MCQeasy

A team wants to pass a variable "allowed_ports" to a module and guarantee at apply time that every value is an integer between 1024 and 65535, rejecting invalid plans with a clear message. They prefer the validation to live in the variable block so callers get immediate feedback. Which declaration accomplishes this?

A.variable "allowed_ports" { type = list(number) validation { condition = alltrue([for p in var.allowed_ports : p >= 1024 && p <= 65535]) error_message = "Ports must be between 1024 and 65535." } }
B.variable "allowed_ports" { type = list(number) validation { condition = can(regex("^[0-9]+$", join(",", var.allowed_ports))) error_message = "Ports must be between 1024 and 65535." } }
C.variable "allowed_ports" { type = list(number) validation { condition = length(var.allowed_ports) > 0 error_message = "Ports must be between 1024 and 65535." } }
D.variable "allowed_ports" { type = list(number) validation { condition = contains(var.allowed_ports, 1024) && contains(var.allowed_ports, 65535) error_message = "Ports must be between 1024 and 65535." } }
AnswerA

The condition applies alltrue() over a for expression that evaluates the range check for every element, so any out-of-range port makes the condition false and produces the custom error message during plan. Because validation lives in the variable block, callers receive the failure immediately, and list(number) enforces the element type before the range logic runs.

Why this answer

A variable validation block with alltrue() over a per-element for expression evaluates the range predicate for every port and fails the plan when any element falls outside 1024–65535. Placing it in the variable block gives callers immediate, clearly worded feedback, and the list(number) type constraint handles element typing before the range check executes.

Exam trap

The trap here is using contains() to test list membership against boundary values, which checks for presence of specific ports rather than validating every element's range.

Page 2

Page 3 of 4

Page 4

All pages