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" ?
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.
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.
There are two categories of complex types: collection types (for grouping similar values), and structural types (for grouping potentially dissimilar values).
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")]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With