DEV Community

Cover image for Terraform Meta-Arguments
Sainath Patil
Sainath Patil

Posted on

Terraform Meta-Arguments

What Are Meta-Arguments?
Meta-arguments are special arguments available to all Terraform resources. They modify how Terraform creates, destroys, or manages resources.

The key meta-arguments are:

  • count
  • for_each
  • depends_on

COUNT
The count meta-argument lets you create multiple instances of the same resource using a simple integer.
Example:

resource "aws_s3_bucket" "example" {
count = 3
bucket = "my-bucket-${count.index}"
}
Enter fullscreen mode Exit fullscreen mode

when to use:

  • Creating N identical resources
  • Feature flags (count = var.enabled ? 1 : 0)

Limitations:

  • Index positions shift when items are removed leads to resource recreation risk.
  • No stable index

FOR_EACH
for_each is more powerful and stable. It works with maps and sets, providing predictable resource identifiers.
Example:

resource "aws_s3_bucket" "example" {
for_each = toset(["bucket1", "bucket2", "bucket3"])
bucket = each.value
}
Enter fullscreen mode Exit fullscreen mode

when to use:

  • Creating resources using map or set data
  • Complex configurations
  • You want to update/add/remove resources without index shifting.

DEPENDS_ON
Sometimes Terraform can't detect relationships automatically. Use depends_on to control creation order.

Example:

resource "aws_s3_bucket" "dependent" {
bucket = "my-dependent-bucket"
depends_on = [aws_s3_bucket.primary]
}
Enter fullscreen mode Exit fullscreen mode

when to use:

  • Handling hidden dependencies
  • Enforcing order in resource creation
  • Working with modules

Use commands to test how meta arguments behave:

  • terraform init
  • terraform plan
  • terraform apply
  • terraform destroy

Video: https://youtu.be/XMMsnkovNX4?si=rncEENlnhlbe13BP

Top comments (0)