Skip to content
Latchkey

Terraform "Invalid count argument" - Unknown Value Until Apply in CI

A count whose value comes from something computed during apply (a list length built from other resources’ attributes) cannot be planned - Terraform needs the count to be known at plan time.

What this error means

plan fails with "Invalid count argument", saying the count depends on attributes that cannot be determined until apply. It often appears when count = length(some_computed_list).

terraform output
Error: Invalid count argument

  on sg.tf line 6, in resource "aws_security_group_rule" "ingress":
   6:   count = length(data.aws_instances.web.ids)

The "count" value depends on resource attributes that cannot be determined until
apply, so Terraform cannot predict how many instances will be created. To work
around this, use the -target argument to first apply only the resources that the
count depends on.

Common causes

count length from a computed source

count = length(...) where the list is built from a resource/data source whose result is unknown at plan time leaves the count unknown.

Conditional count on an apply-time boolean

A count = condition ? 1 : 0 where the condition itself depends on a computed value is also unknowable at plan time.

How to fix it

Drive count from plan-time-known values

Base count on variables/locals known up front, or switch to for_each over a known map so the instance set is determinable.

sg.tf
# known at plan time
resource "aws_security_group_rule" "ingress" {
  count = length(var.cidr_blocks)   # input-derived, known at plan
  cidr_blocks = [var.cidr_blocks[count.index]]
}

Stage the dependency first if unavoidable

  1. Restructure to a plan-time-known count or for_each where possible - that is the durable fix.
  2. If you must, apply the upstream resource with -target, then run a normal apply once its values are known.
  3. Treat -target as a one-off unblock, not a standing pattern.

How to prevent it

  • Base count/for_each on inputs known at plan time.
  • Avoid computing instance counts from other resources’ apply-time attributes.
  • Prefer for_each over count for stable, named instances.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →