I am trying to generate Terraform resources from a JSON file that has duplicate keys.
Is there any way to avoid the duplicate?
Here is an example JSON
{
"my-ptr-zone": {
"21-10": {
"zone" : "21.10.in-addr.arpa"
},
"21-10": {
"zone" : "21.10.in-addr.arpa"
}
}
}
Both the keys are the same here.
And here is the resource
resource "aws_route53_zone" "my-ptr-zone" {
for_each = var.my-ptr-zone
name = each.value.zone
}
Is there any way to skip the duplicates when looping?
I have tried to avoid generating duplicate values in the JSON file from the source, but that is another challenge.
3
Answers
If you want to generate only one resource per unique key in a map, ask Terraform to generate a set of the keys, then loop over those.
Consider the following example using the hashicorp/random provider.
Planning that with
terraform plan
, you’ll see that terraform only wants to generate one resource.Change one of the keys to something different, and terraform will want to create two resources.
If you instead are interested in some other uniqueness (e.g. only the unique values of
zone
), the same approach could be applied … generate a set of the things you want to be unique, then iterate over that set.A simple way to approach this would be to run a
merge
on the map twice.JSON File:
TF Code:
Output:
Terraform’s
jsondecode
function reacts to duplicate property names in a single object by discarding all but the last definition of a particular name.In the example shown in your question,
jsondecode
of the JSON document shown would produce the following Terraform value: