Terraform "Invalid count argument" with an unknown value in CI
count must resolve to a known number when the plan is built. When it is derived from an attribute computed during apply (a length of a not-yet-created list, for example), Terraform cannot expand the resource and rejects the count.
What this error means
plan fails with "Error: Invalid count argument" and "The \"count\" value depends on resource attributes that cannot be determined until apply".
Error: Invalid count argument
on main.tf line 14, in resource "aws_instance" "web":
14: count = length(data.aws_subnets.this.ids)
The "count" value depends on resource attributes that cannot be determined until
apply, so Terraform cannot predict how many instances will be created.Common causes
count uses a length that is unknown at plan
Taking length() of a computed list (subnet ids, query results) yields an unknown count during planning.
count derives from a sibling resource attribute
The count expression reads an attribute of a resource created in the same run, which is not known until apply.
How to fix it
Base count on a known input
- Drive count from a variable or a statically known list length.
- Read computed attributes inside the resource body, not in count.
- Re-run plan so the count is a known number.
# count from a known variable, not a computed length
count = length(var.subnet_ids)Stage the dependency with -target if needed
If the count truly depends on another resource, apply that resource first so its values are known, then apply the rest.
terraform apply -target=data.aws_subnets.thisHow to prevent it
- Compute count from variables or locals known at plan time.
- Avoid length() over computed lists in count expressions.
- Use data sources resolved before the dependent resource plans.