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?
Think about what for_each expects to iterate over to create resources with keys.
The for_each argument expects a map or set of strings. Using var.servers directly (a map) allows Terraform to create one resource per key-value pair, using the map keys as resource instance keys.
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"
}
}Remember that for_each with a map gives each.key and each.value.
Option C correctly uses for_each = var.instances so each.key is the map key (app, db) and each.value is the AMI ID. This allows naming the instance with the key and setting the AMI from the value.
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?
Think about how to create unique keys for each instance when count > 1.
Option A correctly uses nested for expressions to create a flat map with unique keys like 'web-0', 'web-1', etc., allowing for_each to create multiple instances per role.
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?
Terraform has a way to mark sensitive values to avoid logging them.
Option A is correct because marking attributes as sensitive = true prevents Terraform from showing passwords in logs or UI, even when using for_each with maps containing secrets.
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?
Think about how Terraform tracks resource instances by keys in for_each maps.
Terraform tracks each resource instance by the map key. Removing 'alpha' from the map causes Terraform to destroy that instance. Adding 'gamma' creates a new instance. 'beta' remains unchanged because its key and value remain.