Home > OS >  Terraform, get 1st (or any) element of an object
Terraform, get 1st (or any) element of an object

Time:01-12

I need to get 1st element (or at least any root level element) of an object in Terraform.

An object has the following structure:

myObject = {
  "unknownRandomKey" : {"id": "123", "data": "data123"},
  "anotherRandomKey" : {"id": "456", "data": "data456"},
  "oneMoreRandomKey" : {"id": "789", "data": "data789"}
}

I don't know in advance what would be the names of top level keys, the rest of the structure has fixed format.

So it is a list by structure, but an object by presence. And Terraform does not allow list functions on a generic object. Neither myObject[0], nor element() or tolist() is supported on an object.

Any solution?

CodePudding user response:

Answering myself.

Instead of tolist(myObject), I should use values(myObject).

CodePudding user response:

This should be what you want:

myObject = {
  "unknownRandomKey" : {"id": "123", "data": "data123"},
  "anotherRandomKey" : {"id": "456", "data": "data456"},
  "oneMoreRandomKey" : {"id": "789", "data": "data789"}
}

myObject[keys(myObject)[0]]
# => {"id": "123", "data": "data123"}
  •  Tags:  
  • Related