Distinct on values in object list

Hi,

I can see that Terraform includes the following distinct Function.
In the example, I can see that they are targeting a list of strings to remove any duplicate.

I would like to achieve somewhat the same, on a list of objects, in the following way:

Type: list(object)

Input:

{
    "Property1" = "A"
    "Property2" = "B"
},
{
    "Property1" = "C"
    "Property2" = "D"
},
{
    "Property1" = "F"
    "Property2" = "B"
},
{
    "Property1" = "G"
    "Property2" = "E"
}

In the input above, there are two objects containing the same value (B), of the Property2 property.

I’d like to “distinct” all of the values of the Property2 property, and retrieve those as a list that I could iterate. Expecting the following output:

[
  "B",
  "D",
  "E"
]

Is there a good way of achieving this, with any combination of native Terraform functions? Or how would one do, to achieve the above desired output?

Greatly appreciate your input.

You can do this using a for expression to convert your list(object(…)) into a list(string), then call distinct on the result. Like so:

variable "xs" {
  type = list(object({ Property1 = string, Property2 = string }))
  default = [
    { "Property1" = "A", "Property2" = "B" },
    { "Property1" = "C", "Property2" = "D" },
    { "Property1" = "F", "Property2" = "B" },
    { "Property1" = "G", "Property2" = "E" }
  ]
}

output "y" {
  value = distinct([
    for x in var.xs : x.Property2
  ])
}

Result:

$ terraform apply -auto-approve

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

y = [
  "B",
  "D",
  "E",
]
1 Like

Thank you alot for the swift and accurate reply @alisdair, this worked as desired. :slight_smile: