Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an object from a list of objects in Terraform?

Tags:

I have the following list of objects variable:

variable "objects" {   type = "list"   description = "list of objects   default = [       {         id = "name1"         attribute = "a"       },       {         id = "name2"         attribute = "a,b"       },       {         id = "name3"         attribute = "d"       }   ] } 

How do I get element with id = "name2" ?

like image 842
votaroe Avatar asked Aug 31 '18 16:08

votaroe


People also ask

How do you use list variables in Terraform?

All files in your Terraform directory using the . tf file format will be automatically loaded during operations. Create a variables file, for example, variables.tf and open the file for edit. Add the below variable declarations to the variables file.

How do you use a loop in Terraform?

Using the count meta-argument The count meta-argument is the simplest of the looping constructs within Terraform. By either directly assigning a whole number or using the length function on a list or map variable, Terraform creates this number of resources based on the resource block it is assigned to.

What are two complex types in Terraform?

There are two categories of complex types: collection types (for grouping similar values), and structural types (for grouping potentially dissimilar values).


2 Answers

You get the map with id="name2" with the following expression:

var.objects[index(var.objects.*.id, "name2")] 

For a quick test, run the following one-liner in terraform console:

[{id = "name1", attribute = "a"}, {id = "name2", attribute = "a,b"}, {id = "name3", attribute = "d"}][index([{id = "name1", attribute = "a"}, {id = "name2", attribute = "a,b"}, {id = "name3", attribute = "d"}].*.id, "name2")] 
like image 106
JRoppert Avatar answered Sep 23 '22 21:09

JRoppert


You can't nested multiple levels of square brackets to get n levels inside a data structure. However you can use the interpolation functions to retrieve such values. In this case you'll want to use the lookup function to retrieve the value from the map which itself has been accessed with square brackets, that will look like this...

${lookup(var.objects[1], "id")} 

Rowan is correct, complex data structures are difficult to work with in current versions of Terraform. However it looks like it won't be too long before we can expect better support in this area. The upcoming version 0.12 will include rich types adding improvements to lists and maps.

like image 22
Ollie Petch Avatar answered Sep 23 '22 21:09

Ollie Petch