DEV Community

drewmullen
drewmullen

Posted on • Edited 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

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more