0
0
Terraformcloud~5 mins

For_each for map-based instances in Terraform - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThe index number of the item
BThe key of the current map item
CThe value of the current map item
DThe total number of items
If you want to create resources with names from a map, which Terraform feature helps you do this easily?
Afor_each
Bcount
Cvariable interpolation
Dlocals
What happens if you use a list instead of a map with for_each?
ATerraform will fail to apply
BTerraform will create only one resource
CTerraform will use list indexes as keys
DTerraform will ignore the list
Why should you avoid changing keys in a map used by for_each after deployment?
AIt automatically updates resources without changes
BIt improves performance
CIt makes Terraform ignore the resources
DIt causes Terraform to recreate resources
In the example for_each = { web1 = "t2.micro", web2 = "t2.small" }, what is each.value for the resource named web2?
A"t2.small"
Bnull
C"t2.micro"
D"web2"
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.