Terraform Advanced — Splat Expressions
Splat expressions extract attributes from lists and resource collections in a single expression.
The Splat Operator [*]
# Create 3 EC2 instances
resource "aws_instance" "web" {
count = 3
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
}
# Get all instance IDs
output "instance_ids" {
value = aws_instance.web[*].id
}
# Equivalent for expression:
output "instance_ids_alt" {
value = [for inst in aws_instance.web : inst.id]
}
Splat with for_each Resources
Splat [*] only works with count. For for_each, use values():
resource "aws_s3_bucket" "this" {
for_each = toset(["logs", "assets", "backups"])
bucket = "${var.project}-${each.key}"
}
# ❌ Won't work:
# aws_s3_bucket.this[*].arn
# ✅ Correct:
output "bucket_arns" {
value = values(aws_s3_bucket.this)[*].arn
}
# ✅ Also correct — for expression:
output "bucket_arns_alt" {
value = [for b in aws_s3_bucket.this : b.arn]
}
Nested Splat
# Get all private IPs from all network interfaces
output "all_private_ips" {
value = aws_instance.web[*].network_interface[*].private_ip
}
💡 Production Tip: Prefer
forexpressions over splat for complex transformations. Splat is a shorthand —forgives you filtering and restructuring.
What’s Next?
Learn try(), can(), and one() for safe attribute access.