Skip to content
Latchkey

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".

Terraform
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

  1. Drive count from a variable or a statically known list length.
  2. Read computed attributes inside the resource body, not in count.
  3. Re-run plan so the count is a known number.
main.tf
# 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.

Terminal
terraform apply -target=data.aws_subnets.this

How 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.

Frequently asked questions

What causes ""Invalid count argument""?
Taking length() of a computed list (subnet ids, query results) yields an unknown count during planning.
How do I fix "Invalid count argument"?
Base count on a known input

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card