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.
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.
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
}
}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:
people: This variable defines a list of objects, each representing a person with "name" and "age" attributes.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.extracted_names: This output simply displays the content of the local.names list, which will be ["bob", "amy", "jane"].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.
"person.name" with "person.age" to get a list of ages, for example.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.| 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]
|
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.
For_each objects to list - Terraform - HashiCorp Discuss | I need to get the results of the following objects from the for_each loop into an array to use as an attribute within another resource. client_vpce_ids= [ { account_id= "123456789101", vpc_id= "vpce-xxxxxxxxxxxxxxx" }, { account_id= "123456789102", vpc_id= "vpce-yyyyyyyyyyyyyyy" } ] resource "first_resource" "first_example" { for_each = { for vpce in var.CLIENT_VPCE_IDS : vpce.account_id => vpce } name = "${each.value.account_id}-access-v...
Loop with conditional using object known only after apply - Terraform | Hello friends, I am trying to consolidate some variables to make a module easier to use, and found myself in a pickle. I have something like: variable "stateful_config" { type = object({ per_instance_config = map(object({ #name is the key stateful_disks = map(object({ #device_name is the key mode = string })) })) mig_config = object({ stateful_disks = map(object({ #device_name is the key mode = string })) ...
Terraform Map Variable - What It is & How to Use | What is a map variable in Terraform? See examples. The difference between map(string) and map(object).
Type Constraints - Configuration Language | Terraform | HashiCorp ... | Any additional attributes are discarded during conversion, which means map -> object map conversions can be lossy. Tuples and lists are similar. A list can only ...
Accessing values from a tuple for use in terraform as a list ... | I’m sure I’m being stupid here and that this is a 101 question but… I have a VPC that has been set up and there is a bunch of information I need to access via the terraform state file. In this case I need to return a list of subnet ids. My problem is that I can’t seem to access them from the tuple. e.g. Setting up a Redis ElasticCache service is AWS using the module-cache.git//modules/redis requires subnet_ids to be set as a list(string). At the moment this looks like this… module "redis"...
Terraform Types: Use of Boolean, Map,List, Data types | Use of Boolean, Map,List, Data types