DEV Community

drewmullen
drewmullen

Posted on • Updated on

Terraform: Compare lists of maps for equality

Say you want to compare 2 lists with n maps in them. You're not sure, in fact you're certain, that the order cannot be relied upon. How can do do this?

The term is Symmetric Difference. I figured this out as part of my delve into terraform test. Here's how you can do it:

main.tf:

locals {
  tag_set_1 = [
    {
        "Key": "workspace",
        "Value": "default"
    },
    {
        "Key": "terraform",
        "Value": "true"
    },
    {
        "Key": "environment",
        "Value": "drew"
    }
]

tag_set_2 = [
    {
        "Key": "workspace",
        "Value": "default"
    },
    {
        "Key": "environment",
        "Value": "drew"
    },
    {
        "Key": "terraform",
        "Value": "true"
    }
]
}

output equality_check {
  value = length(setunion(setsubtract(local.tag_set_2, local.tag_set_1), setsubtract(local.tag_set_1, local.tag_set_2))) == 0
}

Enter fullscreen mode Exit fullscreen mode

Try it out!

$ terraform apply
Outputs:
equality_check = true
Enter fullscreen mode Exit fullscreen mode

Try it out locally using terraform console (instead of terraform apply:

$ echo 'length(setunion(setsubtract(local.tag_set_2, local.tag_set_1), setsubtract(local.tag_set_1, local.tag_set_2))) == 0' | terraform console

true
Enter fullscreen mode Exit fullscreen mode

Top comments (0)