Count
count is a meta-argument that makes many copies of one resource. It takes a number, and Terraform builds that many copies.
Three copies, one block
One block builds three files. count.index makes each copy different.
resource "local_file" "note" {
count = 3
content = "Note ${count.index}."
filename = "${path.module}/note-${count.index}.txt"
}Count from a list
length gives the count from the list. Each copy reads its own name by index.
variable "names" {
type = list(string)
default = ["alpha", "beta"]
}
resource "local_file" "note" {
count = length(var.names)
content = var.names[count.index]
filename = "${path.module}/${var.names[count.index]}.txt"
}Read one copy
A copy is read by its index in square brackets. The second copy is index 1.
output "second" {
value = local_file.note[1].filename
}Example
variable "names" {
type = list(string)
default = ["alpha", "beta", "gamma"]
}
resource "local_file" "note" {
count = length(var.names)
content = "Note ${count.index}: ${var.names[count.index]}."
filename = "${path.module}/note-${count.index}.txt"
}
output "files" {
value = [for f in local_file.note : f.filename]
}Key points
- count takes a whole number.
- count = 3 makes three copies of the resource.
- Each copy has an index, called count.index.
- The first copy is index 0, not index 1.
- The copies are identical except for the index.
- Removing an item from the middle shifts the later indexes.
count makes three copies, one for each name. count.index is 0, 1, then 2, so each copy gets its own name and file.
Note
A shifted index can force Terraform to destroy and rebuild later copies.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What breaks when you remove the first name from a count-based list?