šŸ¶
Terraform

Terraform: Extract Single Element from List of Objects

By Ondřej DolanskĆ½ on 01/01/2025

Learn how to efficiently convert a Terraform list of objects into a list of single elements extracted from those objects, simplifying data manipulation in your infrastructure code.

Terraform: Extract Single Element from List of Objects

Table of Contents

Introduction

In Terraform, extracting a list of specific elements from a list of objects is a common task. This can be achieved efficiently using a combination of the for expression and the splat operator ([*]). This approach allows you to iterate through the original list, access desired attributes from each object, and create a new list containing only those specific values.

Step-by-Step Guide

To extract a list of single elements from a list of objects in Terraform, you can use the for expression with the splat operator ([*]).

Example:

Let's say you have a list of objects like this:

variable "people" {
  default = [
    {
      name = "bob"
      age  = 30
    },
    {
      name = "amy"
      age  = 25
    },
    {
      name = "jane"
      age  = 28
    }
  ]
}

To get a list of names, you can use the following code:

local {
  names = [for person in var.people : person.name]
}

This code iterates through the var.people list and extracts the name attribute from each object, creating a new list called names.

You can then use the local.names list in your AWS resource definitions. For example:

resource "aws_instance" "example" {
  # ... other configurations ...
  tags = {
    Name = local.names[0] # Access the first name in the list
  }
}

Code Example

This Terraform code defines a variable "people" containing a list of objects, each representing a person with name and age. It then extracts the names of all people into a local variable "names" and outputs it. Finally, it demonstrates using the extracted names by creating an AWS instance with the first name in the list as its tag.

# Define a variable with a list of objects
variable "people" {
  default = [
    {
      name = "bob"
      age  = 30
    },
    {
      name = "amy"
      age  = 25
    },
    {
      name = "jane"
      age  = 28
    }
  ]
}

# Extract a list of names from the objects
local {
  names = [for person in var.people : person.name]
}

# Print the list of names
output "extracted_names" {
  value = local.names
}

# Example usage: Accessing the first name in the list
resource "aws_instance" "example" {
  ami           = "ami-0c94855ba95c574c9" # Replace with your desired AMI ID
  instance_type = "t2.micro"

  tags = {
    Name = local.names[0]
  }
}

Explanation:

  1. Variable people: This variable defines a list of objects, each representing a person with "name" and "age" attributes.
  2. Local names: This local value uses a for expression to iterate over each element (person) in the var.people list. For each person, it extracts the value of the name attribute and creates a new list containing only the names.
  3. Output extracted_names: This output simply displays the content of the local.names list, which will be ["bob", "amy", "jane"].
  4. Resource aws_instance: This resource demonstrates how to use the extracted names list. It creates an AWS instance and sets the Name tag to the first element (local.names[0]) of the extracted names list, which is "bob".

This example shows how to extract a specific attribute from a list of objects in Terraform, making it easier to work with and manipulate data within your infrastructure code. You can adapt this pattern to extract other attributes or perform different operations based on your needs.

Additional Notes

  • Flexibility: This technique isn't limited to just extracting names. You can use it to extract any attribute from the objects within your list. Simply replace "person.name" with "person.age" to get a list of ages, for example.
  • Error Handling: If an object in the list doesn't have the attribute you're trying to access (e.g., if one person was missing a name), Terraform would throw an error. Consider using optional attributes or error handling mechanisms for more robust code.
  • Alternatives: While the for expression with splat is a common and readable way to achieve this, other options exist. You could explore using map or lookup functions depending on your specific needs and data structure.
  • Real-World Applications: This pattern is incredibly useful when working with complex data structures in Terraform. Imagine managing a list of servers, each with attributes like IP address, instance type, and environment. You can easily extract lists of IP addresses or filter servers based on their environment using this technique.
  • Keep it Organized: As your infrastructure code grows, consider using modules to encapsulate logic like this. This promotes code reusability and makes your Terraform configurations easier to manage.

Summary

Feature Description Example
Goal Create a list of single elements (e.g., names) from a list of objects (e.g., people with names and ages). Get a list of names from a list of people objects.
Method Use a for expression with the splat operator ([*]) to iterate through the object list and extract the desired attribute. [for person in var.people : person.name]
Input A variable containing a list of objects. var.people (a list of objects with name and age attributes)
Output A new list containing only the extracted elements. local.names (a list of names)
Usage The extracted list can be used in other Terraform resources. Accessing the first name: local.names[0]

Conclusion

This article explained how to extract a list of single elements from a list of objects in Terraform using the for expression and splat operator. This technique is valuable for manipulating and working with complex data structures in your infrastructure code. By understanding this pattern, you can write more efficient and readable Terraform configurations, especially when dealing with lists of objects and extracting specific attributes for use in your resources. Remember to explore additional features like error handling and consider organizing your code with modules as your projects grow.

References

Were You Able to Follow the Instructions?

šŸ˜Love it!
šŸ˜ŠYes
šŸ˜Meh-gical
šŸ˜žNo
šŸ¤®Clickbait