0
0
TerraformHow-ToBeginner · 3 min read

How to Use Splat Expression in Terraform: Syntax and Examples

In Terraform, the splat expression uses * to extract a list of attributes from multiple resources or modules at once. It simplifies accessing repeated values by returning a list of those values instead of referencing each resource individually.
📐

Syntax

The splat expression syntax is resource_type.resource_name[*].attribute. Here, * means 'for all instances' of the resource, and attribute is the property you want to get from each instance.

This returns a list of values, one for each resource instance.

terraform
resource_type.resource_name[*].attribute
💻

Example

This example shows how to use the splat expression to get the public IP addresses of multiple AWS EC2 instances created by a resource block with count.

terraform
resource "aws_instance" "example" {
  count         = 3
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

output "instance_ips" {
  value = aws_instance.example[*].public_ip
}
Output
instance_ips = ["54.210.1.2", "54.210.1.3", "54.210.1.4"]
⚠️

Common Pitfalls

Common mistakes include:

  • Using the splat expression on a single resource without count or for_each, which returns a list with one element instead of a single value.
  • Forgetting to use [*] and trying to access attributes directly, which causes errors when multiple instances exist.
  • Using splat on resources without the attribute you want, leading to null or errors.
terraform
/* Wrong: accessing attribute directly on multiple instances */
output "wrong_ips" {
  value = aws_instance.example.public_ip
}

/* Right: use splat to get list of IPs */
output "correct_ips" {
  value = aws_instance.example[*].public_ip
}
📊

Quick Reference

Use splat expressions to simplify access to repeated resource attributes. Remember:

  • resource_name[*].attribute returns a list of attribute values.
  • Works with resources using count or for_each.
  • Use when you want to pass multiple values to outputs or other resources.

Key Takeaways

Use resource_name[*].attribute to get a list of attributes from multiple resource instances.
Splat expressions work only on resources with multiple instances created by count or for_each.
Without splat, accessing attributes on multiple instances causes errors or unexpected results.
Splat expressions simplify outputs and references by avoiding manual indexing.
Always verify the attribute exists on the resource to avoid null or errors.