What are splat expressions, and how do they relate to `for` expressions?
Quick Answer
The splat operator [*] is shorthand for the most common for expression pattern: pulling one attribute out of every element of a list. aws_instance.web[*].id is equivalent to [for i in aws_instance.web : i.id], returning a list of every instance's ID when the resource uses count. It only handles this one shape (get one attribute from every item); anything requiring filtering, key transformation, or map output needs a full for expression instead. Splat is a readability shortcut for the simple case, not a replacement for for expressions generally.
Detailed Answer
The splat operator ([*]) shows up constantly in configurations using count, and it's easy to use without realizing it's really just a special case of the more general for expression.
Basic usage
resource "aws_instance" "web" {
count = 3
ami = var.ami_id
}
output "instance_ids" {
value = aws_instance.web[*].id
}
aws_instance.web[*].id returns a list of every instance's id attribute — ["i-aaa", "i-bbb", "i-ccc"] — one entry per count index.
The equivalent for expression
output "instance_ids" {
value = [for i in aws_instance.web : i.id]
}
These two produce identical results. Splat is purely a shorthand for "give me this one attribute from every element," nothing more.
What splat can't do
- Filtering:
aws_instance.web[*].idalways includes every instance; there's noifclause equivalent. To get only some instances' IDs, you need a realforexpression. - Key transformation / map output: splat only ever produces a list. If you need a map (e.g., keyed by instance name), you must use
{for ... : key => value}. - Nested attribute chains beyond simple property access: more complex per-element transformations (string formatting, combining multiple fields) generally read more clearly as an explicit
forexpression than a splat chain.
Legacy syntax note
Older Terraform configurations sometimes use the "legacy" splat form aws_instance.web.*.id (dot-based rather than bracket-based). It's functionally equivalent to [*], but the bracket form is the modern, recommended syntax.
Interview-ready summary
Splat is a convenience shorthand covering the single most common for-expression pattern (pluck one attribute from every element of a list). Reach for a full for expression the moment you need filtering, a map result, or any transformation beyond a plain attribute lookup.