Using Terraform's Splat expression

Introduction

Splat expressions are a syntactic sugar variant of the for expression in Terraform. They produce the same result with the same input but are easier to declare.

Syntax

The syntax for a splat expression is:

var.list[*].attribute

In this syntax, var.list is a list of values, and attribute is the name of an attribute of each value in the list. The splat expression will iterate over the var.list list and extract the value of the attribute attribute for each value.

Whereas if you used a for expression, the syntax would be:

[for value in var.list : value.attribute]

More examples

Here are some examples of using splat expressions in Terraform:

  • To create an output of the list of the names of all the users in the users list:
variable "users" {
  type = list(string)
}

output "users_names" {
  value = var.users[*].name
}
  • To create a map of users to their ages:
variable "users" {
  type = list(map(string, number))
}

output "users_map" {
  value = { for user in var.users : user.name => user.age }
}
  • To create a list of resources:
resource "aws_instance" "vm" {
  count = 3
}

output "vms" {
  value = aws_instance.vm[*]
}
  • To create a map of resources to their names:
resource "aws_instance" "vm" {
  count = 3
}

output "vms_map" {
  value = { for i in range(count.value) : aws_instance.vm[i].name }
}

I hope this helps!

Here are a few more examples of splat expressions in Terraform:

  • To create a list of the IP addresses of all the VMs in the vms list:
variable "vms" {
  type = list(resource_ref("aws_instance"))
}

output "vm_ips" {
  value = [for vm in var.vms : vm.*.public_ip]
}
  • To create a map of VMs to their CPU cores:
variable "vms" {
  type = list(resource_ref("aws_instance"))
}

output "vm_cpu_cores" {
  value = { for vm in var.vms : vm.*.cpu_cores }
}
  • To create a list of the tags for all the resources in the resources list:
variable "resources" {
type = list(resource_ref)
}

output "resource_tags" {
value = [for resource in var.resources : resource.*.tags]
}

I hope these examples help you understand how to use splat expressions in Terraform.

Using Terraform's Splat expression
Older post

Managing Terraform state

Learn how you can view Terraform state and manage the resources in it.

Newer post

Using depends_on in Terraform

Using depends_on in Terraform

Using Terraform's Splat expression