Recall & Review
beginner
What does
for_each do in Terraform when used with a map?for_each lets you create multiple resources, one for each item in the map. Each resource gets a unique key from the map.
Click to reveal answer
beginner
How do you access the key and value inside a
for_each block for a map?Use each.key for the map key and each.value for the map value inside the resource block.
Click to reveal answer
intermediate
Why is using a map with
for_each better than a list for some cases?<p>Maps let you name each instance with a key, making it easier to identify and update specific resources.</p>Click to reveal answer
intermediate
What happens if you change the keys in the map used by
for_each?Terraform will see the old keys as removed and new keys as added, so it will destroy and create resources accordingly.
Click to reveal answer
beginner
Show a simple example of
for_each with a map to create multiple AWS EC2 instances.resource "aws_instance" "example" {
for_each = {
web1 = "t2.micro"
web2 = "t2.small"
}
ami = "ami-123456"
instance_type = each.value
tags = {
Name = each.key
}
}Click to reveal answer
What does
each.key represent in a for_each loop over a map?✗ Incorrect
each.key is the key from the map for the current resource instance.
If you want to create resources with names from a map, which Terraform feature helps you do this easily?
✗ Incorrect
for_each lets you create one resource per map entry, using keys as names.
What happens if you use a list instead of a map with
for_each?✗ Incorrect
Terraform uses list indexes as keys when for_each is given a list.
Why should you avoid changing keys in a map used by
for_each after deployment?✗ Incorrect
Changing keys makes Terraform think old resources are removed and new ones added, causing recreation.
In the example
for_each = { web1 = "t2.micro", web2 = "t2.small" }, what is each.value for the resource named web2?✗ Incorrect
each.value is the value from the map for the current key, so for web2 it is "t2.small".
Explain how
for_each works with maps in Terraform and why it is useful.Think about how maps have keys and values and how Terraform uses them.
You got /4 concepts.
Describe what happens if you rename a key in the map used by
for_each after resources are created.Consider how Terraform tracks resources by keys.
You got /4 concepts.