HashiCorp Certified: Terraform Authoring and Operations Professional Exam-style mock test
HashiCorp Terraform Authoring and Operations Professional Practice Exams|Practice test
Full explanations
Exam format
Pass line 70%
33 USD One-time · lifetime access
Enroll →
Sample questions
Example1 · HCL Authoring, Variables, Expressions, and Functions
At the B2B SaaS firm Larkfield, a module must accept a list of tenant subdomains and reject any configuration that passes a single bare string. Which variable declaration enforces that the value is a list of strings?
✓variable "subdomains" { type = list(string) }
Correct. The list(string) constraint requires an ordered collection of strings and causes Terraform to reject a bare string value.
・variable "subdomains" { type = string nullable = false }
Incorrect. A type of string accepts exactly a single string, which is the opposite of the requirement.
・variable "subdomains" { type = set(any) default = [] }
Incorrect. set(any) permits mixed element types and does not guarantee the strings-only, list semantics requested.
・variable "subdomains" { type = any description = "tenant subdomains" }
Incorrect. type = any disables type checking entirely, so a bare string would be accepted without error.
Explanation
A list(string) type constraint enforces both the collection shape and the element type, rejecting a scalar string input.
Example2 · Modules, Composition, and Reusability
A B2B SaaS platform team is building a reusable "tenant-network" module that other squads will consume. The networking squad wants consumers to pass a CIDR block but wants to reject any value outside the RFC1918 private ranges before Terraform plans anything. Which approach best enforces this constraint inside the module?
✓Add a variable validation block with a condition and error message
Correct. A variable validation block evaluates the condition at plan time and raises the error message when a consumer passes a non-private CIDR, rejecting invalid input early.
・Document the private-range requirement in the module README and rely on reviewers to catch violations
Incorrect. A README note is advisory only and does not programmatically reject invalid values, so bad CIDRs still reach plan and apply.
・Use a precondition in a check block that runs during the apply phase only
Incorrect. Preconditions run during plan/apply of a resource and are not the idiomatic mechanism for validating raw input variables; validation blocks are purpose-built for this.
・Create a wrapper module whose only job is to filter the CIDR argument before passing it onward
Incorrect. Building a whole extra wrapper module to filter one argument adds needless indirection when a single validation block on the variable achieves the same guard.
Explanation
Input validation belongs in a variable validation block, which evaluates at plan time and surfaces a custom error for out-of-range values.
Example3 · State Management, Backends, and Workspaces
A B2B SaaS platform team currently keeps Terraform state on each engineer's laptop, causing drift and overwrites. They need shared state with locking and encryption at rest, managed outside of CI runners. Which change best meets these needs?
・Commit the local terraform.tfstate file into Git so every engineer pulls the latest version before applying
Incorrect. Committing state to Git provides no locking, exposes secrets in plaintext history, and still allows concurrent conflicting edits.
✓Configure an S3 backend with DynamoDB-based state locking and server-side encryption enabled
Correct. A remote S3 backend with DynamoDB locking and server-side encryption gives shared, locked, encrypted-at-rest state independent of any single machine.
・Keep local state but email the tfstate file to teammates after each successful apply operation
Incorrect. Emailing the state file is error-prone, insecure, and offers no locking or concurrency protection whatsoever.
・Run terraform apply only from a single bastion host so one copy of the local state is used
Incorrect. A single bastion with local state creates a single point of failure and still lacks locking if two sessions run at once.
Explanation
A remote backend such as S3 with DynamoDB locking centralizes state, prevents concurrent writes, and encrypts data at rest, solving drift and overwrite problems.
Example4 · Provisioning Workflow, Providers, and Resource Lifecycle
A healthcare services firm must run a one-time bootstrap script on a newly created clinical-records VM, but only after the VM resource itself succeeds. The platform team wants the bootstrap tied to the resource lifecycle without replacing the VM. Which approach best fits HashiCorp's guidance for this scenario?
✓Use a remote-exec provisioner inside the VM resource with the default creation-time behavior
Correct. A creation-time remote-exec provisioner runs once after the resource is successfully created, which matches the one-time bootstrap requirement and keeps provisioners as a last resort tied to the lifecycle.
・Add a destroy-time provisioner so the script runs whenever the VM is torn down and rebuilt
Incorrect. A destroy-time provisioner runs during teardown, not after creation, so the bootstrap would not execute when the VM is first provisioned.
・Define the bootstrap as a separate null_resource with no triggers
Incorrect. A null_resource with no triggers never re-evaluates and is decoupled from the VM's creation success, so it does not guarantee running after the VM succeeds.
・Replace the VM resource with a data source referencing the existing host
Incorrect. A data source only reads existing infrastructure and cannot create the VM or run a bootstrap script at all.
Explanation
Provisioners are a last resort, but when used, a creation-time provisioner runs once after the resource is successfully created, satisfying a one-time post-create bootstrap.
Example5 · HCP Terraform, Operations, Testing, and Troubleshooting
A healthcare services firm manages its patient-portal infrastructure in an HCP Terraform workspace connected to a GitHub repository. The platform team wants every merge to the main branch to automatically trigger a plan, but they also require that a human reviewer approve before any apply changes production resources. Which workspace configuration meets this requirement?
・Set the workspace to Local execution mode so engineers run terraform apply from their laptops after the pull request is merged into the main branch
Incorrect. Local execution removes HCP Terraform's run orchestration, so merges would not trigger remote plans and the approval gate would not be enforced centrally.
✓Enable the VCS integration and keep the apply method set to manual apply so merges queue a plan awaiting confirmation
Correct. VCS-driven runs trigger a plan on each merge, and manual apply (auto-apply off) requires a reviewer to confirm before changes are applied.
・Configure the workspace with the API-driven workflow and disable VCS so that runs are started only through the Terraform CLI with saved credentials
Incorrect. The API-driven workflow with VCS disabled would not react to merges automatically; runs would have to be started externally.
・Turn on workspace auto-apply and rely on GitHub branch protection rules to gate the merge beforehand
Incorrect. Auto-apply would immediately apply the plan after a merge, bypassing the required human approval of the apply step.
Explanation
A VCS-connected workspace with manual apply plans on every merge but pauses for confirmation, giving the needed human approval gate before production changes.
Example6 · HCL Authoring, Variables, Expressions, and Functions
A healthcare services firm defines a variable to hold allowed ingress CIDR blocks for its patient-portal network module. Operators sometimes pass a single string by mistake, and Terraform must reject that at plan time instead of silently coercing it. Which type constraint should the variable use?
・type = string, then split on commas inside the module later
Incorrect. A plain string accepts the mistaken input and forces manual splitting, defeating the goal of rejecting it.
✓Set type = list(string) on the CIDR variable
Correct. Declaring list(string) makes Terraform reject a bare string during validation, enforcing the collection shape.
・type = any, relying on downstream resources to validate shape
Incorrect. The any type disables checking entirely, so the wrong single-string input passes straight through.
・type = map(string) keyed by each environment such as dev
Incorrect. A map keyed by environment changes the data model and still would not enforce a simple ordered list of CIDRs.
Explanation
A list(string) type constraint causes Terraform to error when a scalar string is supplied, catching the operator mistake at plan time.
Example7 · HCL Authoring, Variables, Expressions, and Functions
The platform team at retailer NorthPeak Outfitters wants a variable named store_tier to accept only the strings "flagship", "standard", or "popup", and to fail the plan with a clear message otherwise. Which construct inside the variable block enforces this?
✓A validation block using contains() plus an error_message
Correct. A validation block with a contains() condition against the allowed list and an error_message is the supported way to restrict a variable to a fixed set of values.
・A default block that lists the three permitted store tier strings, so Terraform rejects any value falling outside that default set during the plan phase
Incorrect. default only provides a fallback value when none is supplied; it does not constrain the set of acceptable inputs.
・A nullable = false setting combined with a plain string type constraint, which supposedly restricts the input down to just the three allowed tier names
Incorrect. nullable = false merely forbids null, and a string type permits any string, so neither restricts the value to three specific tiers.
・A precondition block that references each of the three allowed store tier strings in turn
Incorrect. precondition blocks belong to resources, data sources, or outputs, not to input variable definitions.
Explanation
Input validation of allowed values is done with a validation block containing a boolean condition (here contains()) plus an error_message.
Example8 · HCL Authoring, Variables, Expressions, and Functions
NorthPeak Outfitters needs an instance count that is 3 when var.environment equals "prod" and 1 otherwise. Which expression assigned to the count argument produces this behavior?
✓count = var.environment == "prod" ? 3 : 1, the ternary conditional returning 3 for prod and 1 in every other case
Correct. Terraform uses the ternary conditional syntax condition ? true_val : false_val, so this returns 3 for prod and 1 otherwise.
・count = if var.environment == "prod" then 3 else 1 end, as a block statement
Incorrect. HCL has no if/then/else/end statement form; conditional values use the ternary operator instead.
・count = var.environment ? 3 : 1, which returns 1 otherwise
Incorrect. The condition must be a boolean, and a bare string like var.environment is not a boolean, so this is invalid.
・count = coalesce(var.environment, 3, 1)
Incorrect. coalesce returns the first non-null argument and does not perform the prod-versus-other comparison required here.
Explanation
Conditional values in HCL use the ternary operator condition ? true : false, and the condition must evaluate to a boolean.
Example9 · HCL Authoring, Variables, Expressions, and Functions
NorthPeak Outfitters has local.region_stores = { "us-east": ["a", "b"], "us-west": ["c"] } and wants a single flat list of all store codes across regions. Which function call yields ["a", "b", "c"]?
✓flatten(values(local.region_stores)) to collapse the per-region lists
Correct. values() returns the list of value lists, and flatten() collapses that list of lists into a single flat list of store codes.
・merge([for region, stores in local.region_stores : stores]) applied to concatenate each per-region list into one combined ordered list of store codes
Incorrect. merge combines maps into a map, not lists into a flat list, so it does not produce the requested list output.
・concat(local.region_stores) because concat automatically walks the map values
Incorrect. concat requires multiple list arguments; passing a single map does not flatten its nested value lists.
・setunion(local.region_stores)
Incorrect. setunion operates on separate set arguments and cannot take a single map to flatten its values.
Explanation
Extract the map's value lists with values() and collapse the nested lists with flatten() to get one flat list.
Example10 · HCL Authoring, Variables, Expressions, and Functions
A financial services platform team wants a variable account_tier that only accepts the strings "standard", "premium", or "enterprise", and the plan must fail with a clear message otherwise. Which approach meets this requirement using native Terraform configuration?
✓Add a validation block using contains() against the allowed list with a custom error_message
Correct. A validation block using contains() against the allowed list with a custom error_message is the native mechanism for restricting a variable to a fixed set of values before apply.
・Set the variable type to a constrained enum keyword so only the three tier strings are syntactically accepted by the parser
Incorrect. Terraform has no enum type keyword; type constraints are limited to primitives, collections, and structural types.
・Reference the variable inside a precondition on each resource and raise an error when the value is unexpected
Incorrect. Preconditions validate resource/data context, not input variables, and scattering the check per resource is not the intended mechanism.
・Define the variable type as string and let the provider reject any disallowed tier value during the apply phase
Incorrect. Deferring rejection to the provider at apply time defeats early validation and gives no custom, variable-scoped error message.
Explanation
Variable validation blocks evaluate a condition (commonly contains() over an allowed list) and surface a custom error_message during plan, enforcing allowed values natively.
Example11 · HCL Authoring, Variables, Expressions, and Functions
A banking module must accept a list of accounts, where each account has a string id, a number balance, and a bool is_frozen. Which type constraint best expresses this input precisely?
✓list(object({ id = string, balance = number, is_frozen = bool })) to model an ordered collection of uniformly typed account records
Correct. list(object({...})) models an ordered collection of accounts where every element shares the same typed attributes id, balance, and is_frozen.
・list(map(any)) so that each account entry can carry an arbitrary mix of string, number, and boolean attributes
Incorrect. list(map(any)) loses per-attribute type enforcement and permits inconsistent, untyped account entries.
・map(object({ id = string, balance = number, is_frozen = bool })) keyed by an arbitrary string per account
Incorrect. map(object({...})) requires string keys per account rather than an ordered list of accounts as described.
・tuple([string, number, bool]) describing a single fixed three-element value rather than any variable-length list
Incorrect. A single tuple describes one fixed three-element value, not a variable-length list of accounts.
Explanation
A collection of uniform structured records is expressed as list(object({...})), giving both ordering and strict per-attribute typing.
Example12 · HCL Authoring, Variables, Expressions, and Functions
A platform engineer at NorthForge Manufacturing Distributors defines a variable for warehouse rack counts that must be a whole number between 10 and 500 inclusive, rejecting any value outside that window at plan time with a clear message. Which variable declaration correctly enforces this?
✓Use type number with a validation block whose boolean condition checks the inclusive range and returns an error_message
Correct. A validation block with a boolean condition on the range plus error_message is the supported pattern for constraining an input variable.
・Set type = number and rely on a default of 10 so that Terraform automatically clamps any larger supplied value down into the permitted range during the plan phase
Incorrect. Defaults do not clamp supplied values; a default only applies when no value is passed and never rejects out-of-range input.
・Use a precondition block referencing var.rack_count inside the variable so the bound check is evaluated before any resource in the configuration is created or updated
Incorrect. precondition blocks belong to resources, data sources, or outputs via lifecycle, not inside variable declarations for input validation.
・Apply type = string and a regex validation so that only digits are accepted, then convert and compare the numeric bounds later inside the resource arguments
Incorrect. Treating a numeric bound as a string regex is fragile and bypasses number typing; validation should operate on the number type directly.
Explanation
Input validation uses a validation block with a condition and error_message inside the variable declaration; defaults never clamp and preconditions apply to resources/outputs.
Example13 · HCL Authoring, Variables, Expressions, and Functions
NorthForge needs a single input variable describing each distribution center: a string region, a number capacity, and a bool refrigerated flag, with all three keys required for every center. Which type constraint best models one center entry?
・map(any), because it can hold mixed value types keyed by name and Terraform infers each center's structure from the supplied values
Incorrect. map(any) permits mixed types but does not enforce required keys or per-attribute types, so missing or mistyped fields slip through.
✓object({ region = string, capacity = number, refrigerated = bool }), which enforces the three exact required keys and pins the type of each attribute for every distribution center entry at plan time
Correct. An object type pins down the exact attribute names and each attribute's type, enforcing all three required keys.
・tuple([string, number, bool]), so the three positional elements correspond to the region, the capacity, and the refrigerated flag in that fixed declared order
Incorrect. A tuple relies on positional order with no named keys, which is error-prone and does not express required named fields like region or refrigerated.
・list(string), converting the capacity and the refrigerated flag into strings so a single homogeneous element type can represent all of the center fields together
Incorrect. list(string) forces a single element type and loses the number and bool typing, conflating distinct fields into strings.
Explanation
An object type is the right choice when you need named, required attributes each with its own type; maps and lists cannot enforce that structure.
Example14 · HCL Authoring, Variables, Expressions, and Functions
A telecom operator declares a variable for cell-site capacity that must accept only positive integers no greater than 500. Which approach enforces this at plan time using only native Terraform features?
✓Use a number variable with a validation block whose condition bounds it to 0-500
Correct. A validation block with a condition comparing the number against the 0-500 bounds and a custom error_message enforces the constraint during plan.
・Set the variable type to number and rely on the cloud provider to reject any values that fall outside the supported capacity range during the apply phase
Incorrect. Relying on the provider defers the check to apply and is not guaranteed for an arbitrary business bound like 500.
・Define the variable as a string and parse it inside a local value using a regex that only permits the digits 1 through 500 before passing it to resources
Incorrect. A regex on a string cannot cleanly express the numeric range 1-500 and is fragile and unnecessary.
・Mark the variable as sensitive so Terraform masks out-of-range values and halts the plan automatically whenever the configured limit is exceeded
Incorrect. The sensitive flag only masks values in output; it performs no range validation at all.
Explanation
Type constraints plus a validation block are the native mechanism for enforcing value rules at plan time.
Example15 · HCL Authoring, Variables, Expressions, and Functions
The operator has a list of base station names and needs a map keyed by name whose value is the uppercased name. Which expression produces that map?
✓{ for n in var.stations : n => upper(n) }
Correct. Using curly braces with the key => value form yields a map keyed by each name with its uppercased value.
・[ for n in var.stations : upper(n) ]
Incorrect. Square brackets produce a list of uppercased names, not a map keyed by name.
・{ for n in var.stations : upper(n) }
Incorrect. A curly-brace for expression still requires the key => value syntax; a single result expression is invalid here.
・{ for i, n in var.stations : i => n }
Incorrect. This keys the map by numeric index and keeps the original name, which does not match the requested name-keyed, uppercased map.
Explanation
A curly-brace for expression with key => value builds a map; square brackets build a list.
▶ Try 10 free questions (graded)