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).
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.
# 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
- Restructure to a plan-time-known count or
for_eachwhere possible - that is the durable fix. - If you must, apply the upstream resource with
-target, then run a normal apply once its values are known. - Treat
-targetas a one-off unblock, not a standing pattern.
How to prevent it
- Base
count/for_eachon inputs known at plan time. - Avoid computing instance counts from other resources’ apply-time attributes.
- Prefer
for_eachovercountfor stable, named instances.