Bird
Raised Fist0
Terraformcloud~20 mins

For_each for map-based instances in Terraform - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Map Mastery in Terraform
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Understanding for_each with map variables

Given the following Terraform map variable:

variable "servers" {
  type = map(string)
  default = {
    web = "10.0.1.1"
    db  = "10.0.1.2"
  }
}

Which for_each expression correctly creates one resource per server with the key as the resource name?

Afor_each = toset(var.servers)
Bfor_each = values(var.servers)
Cfor_each = keys(var.servers)
Dfor_each = var.servers
Attempts:
2 left
💡 Hint

Think about what for_each expects to iterate over to create resources with keys.

❓ Configuration
intermediate
2:00remaining
Correct resource block using for_each with map

Which resource block correctly uses for_each to create AWS instances from the map below, assigning the instance name from the map key?

variable "instances" {
  default = {
    app = "ami-123456"
    db  = "ami-654321"
  }
}
A
resource "aws_instance" "example" {
  for_each = keys(var.instances)
  ami      = var.instances[each.key]
  tags = {
    Name = each.key
  }
}
B
resource "aws_instance" "example" {
  for_each = toset(var.instances)
  ami      = each.key
  tags = {
    Name = each.value
  }
}
C
resource "aws_instance" "example" {
  for_each = var.instances
  ami      = each.value
  tags = {
    Name = each.key
  }
}
D
resource "aws_instance" "example" {
  for_each = values(var.instances)
  ami      = each.value
  tags = {
    Name = each.key
  }
}
Attempts:
2 left
💡 Hint

Remember that for_each with a map gives each.key and each.value.

❓ Architecture
advanced
2:30remaining
Scaling infrastructure with map-based for_each

You have a map variable defining server roles and counts:

variable "server_roles" {
  default = {
    web = 3
    db  = 2
  }
}

Which approach correctly creates the specified number of instances per role using for_each with maps?

AUse <code>for_each = { for role, count in var.server_roles : for i in range(count) : "${role}-${i}" => role }</code> to flatten keys for each instance
BUse <code>for_each = { for role, count in var.server_roles : role => count }</code> and inside resource use <code>count.index</code> to create multiple instances
CUse <code>for_each = { for role, count in var.server_roles : "${role}-${count}" => count }</code> and create one resource per key
DUse <code>for_each = { for role, count in var.server_roles : role => range(count) }</code> and iterate over ranges
Attempts:
2 left
💡 Hint

Think about how to create unique keys for each instance when count > 1.

❓ security
advanced
2:00remaining
Avoiding sensitive data exposure in for_each maps

You have a map variable with server names and passwords:

variable "server_passwords" {
  type = map(string)
  default = {
    app = "pass123"
    db  = "secret456"
  }
}

Which Terraform practice prevents exposing passwords in resource logs when using for_each?

AUse <code>for_each = var.server_passwords</code> but mark the password attribute as <code>sensitive = true</code> in the resource
BUse <code>for_each = var.server_passwords</code> directly and output the passwords as resource attributes
CConvert the map to a list and use <code>count</code> instead of <code>for_each</code>
DStore passwords in plain text in Terraform state and avoid marking sensitive
Attempts:
2 left
💡 Hint

Terraform has a way to mark sensitive values to avoid logging them.

❓ service_behavior
expert
2:30remaining
Terraform state behavior with map-based for_each resource changes

Given a resource using for_each over a map:

resource "aws_instance" "example" {
  for_each = {
    alpha = "ami-111"
    beta  = "ami-222"
  }
  ami           = each.value
  instance_type = "t2.micro"
}

If you change the map to:

for_each = {
  beta  = "ami-222"
  gamma = "ami-333"
}

What happens to the Terraform state and resources after applying?

ATerraform updates the 'alpha' instance to use AMI 'ami-333' and keeps 'beta' unchanged
BTerraform destroys the 'alpha' instance and creates a new 'gamma' instance, keeping 'beta' unchanged
CTerraform creates a new instance for 'gamma' but leaves 'alpha' and 'beta' unchanged
DTerraform destroys all instances and recreates them with new keys
Attempts:
2 left
💡 Hint

Think about how Terraform tracks resource instances by keys in for_each maps.

Practice

(1/5)
1. What does for_each do when used with a map in Terraform?
easy
A. Creates resources only for the first key in the map
B. Deletes all resources in the map
C. Combines all map entries into a single resource
D. Creates one resource for each key-value pair in the map

Solution

  1. Step 1: Understand the role of for_each with maps

    for_each iterates over each key-value pair in a map to create multiple resources.
  2. Step 2: Recognize resource creation behavior

    Each key-value pair results in one resource instance, using each.key and each.value inside the resource block.
  3. Final Answer:

    Creates one resource for each key-value pair in the map -> Option D
  4. Quick Check:

    for_each with map = one resource per pair [OK]
Hint: Remember: for_each maps keys to separate resources [OK]
Common Mistakes:
  • Thinking for_each merges all map entries into one resource
  • Assuming for_each deletes resources
  • Believing for_each only uses the first map key
2. Which of the following is the correct syntax to use for_each with a map in a Terraform resource?
easy
A. resource "aws_instance" "example" { for_each = { key1 = "val1", key2 = "val2" } }
B. resource "aws_instance" "example" { for_each = ("key1", "key2") }
C. resource "aws_instance" "example" { for_each = "key1" }
D. resource "aws_instance" "example" { for_each = ["one", "two"] }

Solution

  1. Step 1: Identify valid for_each types

    for_each accepts a map or set of strings, but here we focus on map usage.
  2. Step 2: Check syntax correctness

    resource "aws_instance" "example" { for_each = { key1 = "val1", key2 = "val2" } } uses a map with key-value pairs correctly inside curly braces, which is valid Terraform syntax.
  3. Final Answer:

    resource "aws_instance" "example" { for_each = { key1 = "val1", key2 = "val2" } } -> Option A
  4. Quick Check:

    Map syntax with curly braces = correct for_each [OK]
Hint: Use curly braces for maps in for_each [OK]
Common Mistakes:
  • Using square brackets for maps instead of curly braces
  • Passing a single string instead of a map
  • Using parentheses which are invalid here
3. Given the Terraform snippet:
variable "servers" {
  default = {
    web = "10.0.0.1"
    db  = "10.0.0.2"
  }
}

resource "aws_instance" "example" {
  for_each = var.servers
  ami           = "ami-123456"
  instance_type = "t2.micro"
  tags = {
    Name = each.key
    IP   = each.value
  }
}

What will be the value of the tag Name for the instance with IP 10.0.0.2?
medium
A. web
B. 10.0.0.2
C. db
D. example

Solution

  1. Step 1: Map keys to IP addresses

    The map has keys 'web' and 'db' with values '10.0.0.1' and '10.0.0.2' respectively.
  2. Step 2: Match IP to key

    The IP '10.0.0.2' corresponds to the key 'db', so the tag Name will be 'db'.
  3. Final Answer:

    db -> Option C
  4. Quick Check:

    each.key for IP 10.0.0.2 = db [OK]
Hint: Match IP value to map key for Name tag [OK]
Common Mistakes:
  • Confusing key and value in the map
  • Using IP as the Name tag instead of the key
  • Assuming static tag values
4. What is wrong with this Terraform resource using for_each on a map?
resource "aws_instance" "example" {
  for_each = { "one" = "10.0.0.1", "two" = "10.0.0.2" }
  ami           = "ami-123456"
  instance_type = "t2.micro"
  tags = {
    Name = each.value
  }
  count = 2
}
medium
A. Using both for_each and count together causes an error
B. The map syntax is invalid
C. Missing each.key in tags
D. AMI ID is incorrect

Solution

  1. Step 1: Check resource meta-arguments

    Terraform does not allow using both for_each and count in the same resource block.
  2. Step 2: Identify the error cause

    The presence of count = 2 alongside for_each causes a configuration error.
  3. Final Answer:

    Using both for_each and count together causes an error -> Option A
  4. Quick Check:

    for_each and count cannot coexist [OK]
Hint: Never mix for_each and count in one resource [OK]
Common Mistakes:
  • Thinking map syntax is wrong
  • Believing missing each.key causes error
  • Assuming AMI ID is the problem
5. You have a map of server roles and IPs:
servers = {
  app1 = "10.0.1.1"
  app2 = ""
  app3 = "10.0.1.3"
  app4 = null
}

You want to create AWS instances only for servers with valid IPs using for_each. Which expression correctly filters the map to exclude empty or null IPs?
hard
A. for_each = var.servers
B. for_each = { for k, v in var.servers : k => v if v != "" && v != null }
C. for_each = { for k, v in var.servers : k => v if v == "" || v == null }
D. for_each = [ for v in var.servers : v if v != "" ]

Solution

  1. Step 1: Understand filtering with for expressions

    Use a for expression with an if condition to filter out empty strings and null values from the map.
  2. Step 2: Check each option

    for_each = { for k, v in var.servers : k => v if v != "" && v != null } correctly filters keys where value is neither empty string nor null, producing a valid filtered map for for_each.
  3. Final Answer:

    for_each = { for k, v in var.servers : k => v if v != "" && v != null } -> Option B
  4. Quick Check:

    Filter map with if condition to exclude empty/null [OK]
Hint: Filter map with for and if to exclude empty/null [OK]
Common Mistakes:
  • Not filtering out empty or null values
  • Using list comprehension instead of map
  • Filtering for empty/null instead of excluding them
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard