Terraform Tutorial β Meta-Arguments Overview
Meta-arguments are special arguments that work on ANY resource type. They change how Terraform handles the resource itself, not what the resource looks like.
count β Create N Identical Resources
resource "aws_instance" "web" {
count = 3
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
tags = {
Name = "web-server-${count.index}"
}
}
This creates three EC2 instances: web-server-0, web-server-1, web-server-2.
Reference by index: aws_instance.web[0].public_ip
for_each β Create Resources from a Collection
variable "buckets" {
default = {
logs = "private"
assets = "private"
backups = "private"
}
}
resource "aws_s3_bucket" "buckets" {
for_each = var.buckets
bucket = "myapp-${each.key}"
}
Creates three buckets, each identified by its key: aws_s3_bucket.buckets["logs"], aws_s3_bucket.buckets["assets"], etc.
count vs for_each
| Aspect | count |
for_each |
|---|---|---|
| Input | A number | A set or map |
| Identify instances | By index [0], [1] |
By key ["logs"], ["assets"] |
| Removing middle item | Shifts all subsequent indexes | Only removes that key |
| Best for | Identical copies | Distinct items with meaningful keys |
π‘ Tip: Prefer
for_eachovercount. If you remove item[1]from a count of 3, Terraform wants to destroy[2]and rename[1]β causing unnecessary changes. Withfor_each, removing"assets"only affects that one resource.
depends_on β Explicit Dependencies
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
depends_on = [aws_iam_role_policy_attachment.web_policy]
}
Use when Terraform canβt detect the dependency from references alone.
provider β Use a Specific Provider
resource "aws_s3_bucket" "eu_bucket" {
provider = aws.eu
bucket = "myapp-eu-data"
}
Selects which provider configuration to use (for aliased providers).
lifecycle β Control Create/Update/Destroy Behavior
resource "aws_db_instance" "main" {
# ... arguments ...
lifecycle {
prevent_destroy = true
create_before_destroy = true
ignore_changes = [password]
}
}
Summary Table
| Meta-Argument | Purpose |
|---|---|
count |
Create N copies of a resource |
for_each |
Create one resource per item in a set/map |
depends_on |
Declare explicit dependencies |
provider |
Choose which provider configuration to use |
lifecycle |
Control create/update/destroy behavior |
Whatβs Next?
You now have a complete picture of Terraform resources. Time to test your knowledge with the practice exercises.