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.
for_each block for a map?Use each.key for the map key and each.value for the map value inside the resource block.
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>for_each?Terraform will see the old keys as removed and new keys as added, so it will destroy and create resources accordingly.
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
}
}each.key represent in a for_each loop over a map?each.key is the key from the map for the current resource instance.
for_each lets you create one resource per map entry, using keys as names.
for_each?Terraform uses list indexes as keys when for_each is given a list.
for_each after deployment?Changing keys makes Terraform think old resources are removed and new ones added, causing recreation.
for_each = { web1 = "t2.micro", web2 = "t2.small" }, what is each.value for the resource named web2?each.value is the value from the map for the current key, so for web2 it is "t2.small".
for_each works with maps in Terraform and why it is useful.for_each after resources are created.