TExcelTAD
Home › Infrastructure as Code: Terraform & OpenTofu › count & Conditional Resources

count & Conditional Resources

count turns one resource block into N instances. Inside the block, count.index is the instance number (0, 1, …), and the instances are addressed local_file.worker[0], local_file.worker[1], and so on. It is the simplest way to make "three identical things" and, with 0 or 1, to make a resource optional.

N identical things

bash · try it yourself
mkdir c && cd c
cat > main.tf <<'HCL'
variable "workers" {
  type    = number
  default = 3
}

resource "local_file" "worker" {
  count    = var.workers
  filename = "worker-${count.index + 1}.conf"
  content  = "id=${count.index}\n"
}

output "files" {
  value = local_file.worker[*].filename
}
HCL
tofu init >/dev/null
tofu apply -auto-approve | grep -E 'Creation complete' | sort   # parallel: sort for a stable order
tofu state list
tofu output files
echo "--- scale down to 2"
tofu apply -auto-approve -var workers=2 | grep -E 'Destruction complete|^Apply'
ls worker-*
local_file.worker[0]: Creation complete after 0s [id=5996a0fab93e84f0f1dffd423209a817815676b6]
local_file.worker[1]: Creation complete after 0s [id=db535032f3d3dfea52852c5633452a8f948fbfba]
local_file.worker[2]: Creation complete after 0s [id=eae010df9c4e8d6ed22e103697c806f520433d70]
local_file.worker[0]
local_file.worker[1]
local_file.worker[2]
[
  "worker-1.conf",
  "worker-2.conf",
  "worker-3.conf",
]
--- scale down to 2
local_file.worker[2]: Destruction complete after 0s
Apply complete! Resources: 0 added, 0 changed, 1 destroyed.
worker-1.conf
worker-2.conf

The three instances are created in parallel (the CLI prints them in whatever order they finish). Scaling down removes the highest indexes. With identical instances that is fine.

Optional resources: count = condition ? 1 : 0

hcl
variable "enable_bastion" {
  type    = bool
  default = false
}

resource "aws_instance" "bastion" {
  count         = var.enable_bastion ? 1 : 0
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.nano"
}

output "bastion_ip" {
  # zero or one instance: one() returns the element or null
  value = one(aws_instance.bastion[*].public_ip)
}

This idiom is everywhere in modules: enable_nat_gateway, create_dns_record, enable_flow_logs. Reference the optional instance with one(x[*].attr) or try(x[0].attr, null) so the code also works when it doesn't exist.

The trap: count over a list of things that differ

When instances are not identical, for example one per name in a list, count ties each object to its position. Remove an element from the middle and everything after it shifts:

bash · try it yourself
mkdir trap && cd trap
cat > main.tf <<'HCL'
variable "teams" {
  type    = list(string)
  default = ["api", "billing", "search"]
}

resource "local_file" "team" {
  count    = length(var.teams)
  filename = "team-${var.teams[count.index]}.txt"
  content  = "${var.teams[count.index]}\n"
}
HCL
tofu init >/dev/null
tofu apply -auto-approve >/dev/null
echo "--- remove \"billing\" from the middle of the list"
tofu plan -var 'teams=["api", "search"]' | grep -E '^  #|^Plan:|filename'
--- remove "billing" from the middle of the list
  # local_file.team[1] must be replaced
      ~ filename             = "team-billing.txt" -> "team-search.txt" # forces replacement
  # local_file.team[2] will be destroyed
  # (because index [2] is out of range for count)
      - filename             = "team-search.txt" -> null
Plan: 1 to add, 0 to change, 2 to destroy.

You wanted to delete one thing; the plan replaces team[1] (billing becomes search) and destroys team[2]. For files that's harmless. For IAM users, databases or DNS records, it means deleting and recreating something that should have been left alone. The fix is for_each, next lesson, which keys instances by name instead of position.

Rule of thumb:

Use count for Use for_each for
N interchangeable copies one instance per distinct item (user, subnet, bucket, rule)
on/off: cond ? 1 : 0 anything built from a list or map that can change in the middle

Test yourself

How do you address the second instance of aws_instance.web created with count?

  1. aws_instance.web.2
  2. aws_instance.web[1]
  3. aws_instance.web["1"]
  4. aws_instance.web#2

With count = length(var.users) and users ["a", "b", "c"], what happens when you remove "a"?

  1. Only user a is destroyed
  2. Every instance shifts: b and c are replaced into positions 0 and 1, and index 2 is destroyed
  3. Nothing
  4. An error

Which idiom makes a resource optional?

  1. enabled = false
  2. count = var.enabled ? 1 : 0
  3. lifecycle { skip = true }
  4. depends_on = []