0
0
Terraformcloud~30 mins

Splat expressions in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Splat Expressions in Terraform
📖 Scenario: You are managing cloud infrastructure using Terraform. You have multiple virtual machines (VMs) defined, and you want to collect their public IP addresses easily.
🎯 Goal: Create a Terraform configuration that defines three virtual machines with specific names and public IPs. Then, use a splat expression to extract all their public IP addresses into a list variable.
📋 What You'll Learn
Define a list variable vm_names with three VM names: "vm1", "vm2", "vm3"
Create three aws_instance resources using a for_each loop over vm_names
Each instance must have a public_ip attribute set to a unique IP string
Use a splat expression to create a list variable public_ips containing all public IPs from the instances
💡 Why This Matters
🌍 Real World
Splat expressions help you gather information from multiple cloud resources easily, such as collecting all IP addresses or IDs for further use.
💼 Career
Cloud engineers often need to manage many resources and extract their attributes efficiently; splat expressions simplify this process in Terraform.
Progress0 / 4 steps
1
Define the VM names list variable
Create a Terraform variable called vm_names as a list with these exact values: "vm1", "vm2", "vm3".
Terraform
Need a hint?

Use variable "vm_names" with type = list(string) and set default to the list of names.

2
Create aws_instance resources using for_each
Create aws_instance resources named example using for_each over var.vm_names. Set the public_ip attribute to "10.0.0.${index(toset(var.vm_names), each.key) + 1}" for each instance.
Terraform
Need a hint?

Use for_each = toset(var.vm_names) and set public_ip using the index of each key plus 1.

3
Use a splat expression to get all public IPs
Create a local variable called public_ips that uses a splat expression to collect all public_ip values from aws_instance.example resources.
Terraform
Need a hint?

Use locals block and assign public_ips = aws_instance.example[*].public_ip.

4
Output the list of public IPs
Add an output block named all_public_ips that outputs the local variable public_ips.
Terraform
Need a hint?

Use output "all_public_ips" block with value = local.public_ips.