How to Get an Object from a List of Objects in Terraform?
TLDR
To retrieve an object from a list of objects in Terraform, use the for expression with filtering or the lookup function for direct access. This approach allows you to dynamically extract specific objects based on conditions.
Terraform provides powerful tools for working with lists and objects. Retrieving a specific object from a list of objects is a common task in dynamic configurations. This guide explains how to achieve this with practical examples.
Step 1: Define a List of Objects
Start by defining a list of objects in your Terraform configuration.
Example
variable "instances" {
default = [
{
name = "app-server"
type = "t2.micro"
},
{
name = "db-server"
type = "t2.large"
}
]
}
Explanation
variable "instances": Declares a variable containing a list of objects.- Each object has
nameandtypeattributes.
Step 2: Use a for Expression with Filtering
Use a for expression to filter the list and retrieve the desired object.
Example
locals {
db_server = [for instance in var.instances : instance if instance.name == "db-server"]
}
Explanation
for instance in var.instances: Iterates over the list of objects.if instance.name == "db-server": Filters objects based on thenameattribute.db_server: Contains the filtered object(s).
Step 3: Extract a Single Object
If you expect only one object, use the tolist function to extract it.
Example
locals {
db_server = tolist([for instance in var.instances : instance if instance.name == "db-server"])[0]
}
Explanation
tolist: Converts the filtered result to a list.[0]: Extracts the first (and only) object from the list.
Step 4: Use the lookup Function
For direct access, use the lookup function if the list is indexed by a key.
Example
locals {
instance_map = { for instance in var.instances : instance.name => instance }
db_server = lookup(local.instance_map, "db-server")
}
Explanation
{ for instance in var.instances : instance.name => instance }: Converts the list to a map indexed byname.lookup: Retrieves the object with the keydb-server.
Best Practices
- Validate Inputs: Ensure the list contains the expected objects.
- Handle Missing Keys: Use the
defaultargument inlookupto handle missing keys. - Document Attributes: Clearly document the attributes of objects in the list.
By following these steps, you can efficiently retrieve objects from a list in Terraform, enabling dynamic and flexible configurations.
We earn commissions when you shop through the links below.
DigitalOcean
Cloud infrastructure for developers
Simple, reliable cloud computing designed for developers
DevDojo
Developer community & tools
Join a community of developers sharing knowledge and tools
SMTPfast
Developer-first email API
Send transactional and marketing email through a clean REST API. Detailed logs, webhooks, and embeddable signup forms in one dashboard.
QuizAPI
Developer-first quiz platform
Build, generate, and embed quizzes with a powerful REST API. AI-powered question generation and live multiplayer.
Want to support DevOps Daily and reach thousands of developers?
Become a SponsorFound an issue?
Related Posts
Also worth your time on this topic
How to Append to a List in Terraform?
Learn how to append elements to a list in Terraform using functions like `concat` and dynamic blocks.
AWS VPC with Terraform
Build a complete AWS VPC infrastructure using Terraform with public/private subnets, NAT gateway, and security groups.
120 minutes
Infrastructure as Code Patterns
What are the key principles and patterns of Infrastructure as Code? How do you structure IaC for multiple environments?
mid