You want to create multiple identical virtual machines in Terraform. You have a list of VM names. Which approach is best to create one resource per VM name?
Think about how Terraform uniquely identifies each resource instance.
Using for_each with a map of VM names as keys allows Terraform to track each resource by its key, making management easier and more stable. Count uses numeric indexes which can cause issues if the list changes.
Given the following Terraform snippet, what will be the number of resources created?
variable "servers" {
default = ["app1", "app2", "app3"]
}
resource "aws_instance" "example" {
count = length(var.servers)
ami = "ami-123456"
instance_type = "t2.micro"
tags = {
Name = var.servers[count.index]
}
}Count creates multiple instances based on the number provided.
Count uses the length of the servers list (3), so Terraform creates 3 aws_instance resources, each tagged with the corresponding server name.
You have a Terraform configuration using count to create resources from a list. You remove one item from the list and apply changes. What happens to the resources?
Think about how count indexes resources and what happens when list length changes.
Count uses numeric indexes. Removing an item shifts indexes, so Terraform destroys the resource at the end of the list, which may not correspond to the removed item, causing unintended destruction.
You use for_each to create multiple resources with sensitive variables as keys. What is a potential security risk?
Consider how Terraform stores resource identifiers in state files.
When sensitive data is used as keys in for_each, those keys appear in plaintext in the state file, potentially exposing secrets. It's best to avoid using sensitive data as keys.
You have a Terraform module using count to create resources. You switch to for_each with a map of resource names. After applying, what is the expected behavior regarding resource replacement?
Think about how Terraform tracks resources by keys and indexes.
Switching from count (numeric indexes) to for_each (named keys) changes resource identifiers, so Terraform treats them as new resources and replaces all existing ones.