TF-Associate-004 domain - 21% of the exam

Terraform configuration

Terraform configuration is 21% of the HashiCorp Certified: Terraform Associate (TF-Associate-004) exam. These are the objectives it covers, each with practice questions, with every answer explained.

Objectives in this domain

Sample question from this domain

Free sampleTerraform configurationmedium

A practitioner defines a variable to hold two Availability Zones and iterates over it with for_each to create one subnet per zone. When they run terraform plan, Terraform reports that for_each cannot be used with this value. What change to the variable makes for_each work directly?

variable "azs" {
  type    = list(string)
  default = ["eu-west-1a", "eu-west-1b"]
}
resource "aws_subnet" "this" {
  for_each          = var.azs
  availability_zone = each.value
}
  • AChange the variable type to tuple([string, string]), because a fixed-length tuple is the collection for_each expects.
  • BChange the variable type to set(string), because for_each accepts a map or a set of strings, not a list. Correct
  • CLeave the type as list(string) and add a lifecycle block with create_before_destroy set to true.
  • DLeave the type as list(string) and reference each.key instead of each.value in the resource.
Recognise that for_each accepts a map or a set of strings, so a list must be converted to a set before iterating over it. for_each keys each instance by a stable string, which a map or set of strings provides but a list does not; converting the list to set(string) supplies acceptable keys and lets the iteration proceed.

Why A is wrong: A tuple looks like an ordered pair that might suit two zones, but for_each rejects tuples just as it rejects lists; it needs a map or a set.

Why B is correct: for_each requires a map or a set of strings; converting the list to a set of strings gives it a collection it can key by value, so it works directly.

Why C is wrong: create_before_destroy governs replacement ordering and does nothing about the for_each input type, so the plan would fail with the same error.

Why D is wrong: Swapping each.key for each.value does not change that a raw list is an invalid for_each argument, so Terraform still refuses the list.

Other domains in this exam

See also the TF-Associate-004 cert hub, the study guide, and the cheat sheet.

Examworthy is not affiliated with or endorsed by HashiCorp. Original, blueprint-aligned practice material only.