Home > Enterprise >  Get value out of a tolist([ data object in Terraform
Get value out of a tolist([ data object in Terraform

Time:07-12

I have this terraform output:

output "cloud_connection" {
    value =  data.cloud_connection.current.connection[0]
  }
$ terraform output
cloud_connection = tolist([
  {

    "id" = "123"
    "settings" = toset([
      {
        "vlan_id" = 100
      },
    ])
    "connection_type" = "cloud"
  },
])

I need to get the vlan_id to reuse it later on.

output "cloud_connection" {
    value =  data.cloud_connection.current.connection[0].settings[0].vlan_id
  }
$ terraform output
cloud_connection = tolist([
    tolist([
      100,
    ]),
  ])

The problem is I can't seem to be able to get the vlan id out of a list.

When I try:

output "cloud_connection" {
    value =  data.connection.current.connection[0].settings[0].vlan_id[0]
  }

I am getting this error:

│ Elements of a set are identified only by their value and don't have any separate index or key to select
│ with, so it's only possible to perform operations across all elements of the set.

How can I get the vlan_id alone?

Thanks

CodePudding user response:

Assuming that you know that you have at least 1 element in each of the nested collections, the idiomatic way would be to use splat expression with some flattening:

output "cloud_connection" {
  value = flatten(data.connection.current.connection[*].settings[*].vlan_id)[0]
}

CodePudding user response:

You can use the function join, assuming you´re getting the following output:

$ terraform output
cloud_connection = tolist([
    tolist([
      100,
    ]),
  ])

For example:

output "cloud_connection" {
    value =  join(",",data.cloud_connection.current.connection[0].settings[0].vlan_id)
  }

That returns:

cloud_connection = "100"
  • Related