Day-08: Meta Arguments in terraform
Source: Dev.to
Meta arguments
Terraform provides five meta‑arguments that control resource behavior:
depends_oncountfor_eachproviderlifecycle
count
count is used for iterating over a list of values.
// variables.tf
variable "bucket_count_list" {
type = list(string)
default = [
"bhaskaratejabulusu-bucket-day-08-list-1",
"bhaskaratejabulusu-bucket-day-08-list-2"
]
}
// main.tf
resource "aws_s3_bucket" "bucket1" {
count = length(var.bucket_count_list)
bucket = var.bucket_count_list[count.index] // iterates from 0 to count‑1
}
for_each
for_each iterates over values or key‑value pairs. It works with maps and sets; the variable’s type must be either map or set.
Set example
// variables.tf
variable "bucket_count_set" {
type = set(string)
default = [
"bhaskaratejabulusu-bucket-day-08-set-1",
"bhaskaratejabulusu-bucket-day-08-set-2"
]
}
// main.tf
resource "aws_s3_bucket" "bucket2" {
for_each = var.bucket_count_set
bucket = each.value // iterates over the set
}
Map example
// variables.tf
variable "bucket_count_map" {
type = map(string)
default = {
bucket1 = "bhaskaratejabulusu-bucket-day-08-map-1",
bucket2 = "bhaskaratejabulusu-bucket-day-08-map-2"
}
}
// main.tf
resource "aws_s3_bucket" "bucket3" {
for_each = var.bucket_count_map
bucket = each.value
}
depends_on
depends_on explicitly declares a dependency between resources, ensuring Terraform creates them in the correct order.
// main.tf
resource "aws_s3_bucket" "bucket1" {
count = length(var.bucket_count_list)
bucket = var.bucket_count_list[count.index]
}
resource "aws_s3_bucket" "bucket2" {
for_each = var.bucket_count_set
bucket = each.value
depends_on = [aws_s3_bucket.bucket1]
}
In this example, bucket2 depends on bucket1; Terraform will wait for bucket1 to be created before provisioning bucket2.