Malar Kandasamy
Malar Kandasamy

Reputation: 868

How to fetch a value from list of maps in terraform 0.12 based on condition

I am using Terraform 0.12. I have a data source that is returning a list of maps. Here is an example:

[
  {
    "name": "abc"
    "id": "123"
  },
  {
    "name": "bcd"
    "id": "345"
  }
] 

How to iterate over this datasource of list of maps and find if a map with key "name" and value "bcd" exists ?

this is my data source:

data "ibm_is_images" "custom_images" {}

locals {
  isexists = "return true/false based on above condition"
}

If it exists, I want to create a resource of count 0 otherwise 1

resource "ibm_is_image" "my_image" {
  count = local.isexists == "true" ? 0 : 1
}

Upvotes: 4

Views: 5152

Answers (2)

Malar Kandasamy
Malar Kandasamy

Reputation: 868

If you want to validate, if the same map contains name "bcd" and id as "345", the above program may not work. The condition should be changed in this case as

 locals { 
isexists = contains([for x in foo: "true" if x.name == "bcd" && x.id == "345"], "true") 
}

output "abc" {
value="${local.isexists}"
}

Upvotes: 0

ydaetskcoR
ydaetskcoR

Reputation: 56997

You can use the contains function to check whether a value is found in a list.

So now you just need to be able to turn your list of maps into a list of values matching the name key. In Terraform 0.12 you can use the generalised splat operator like this:

variable "foo" {
  default = [
    {
      "name": "abc"
      "id": "123"
    },
    {
      "name": "bcd"
      "id": "345"
    }
  ]
}

output "names" {
  value = var.foo[*].name
}

Applying this gives the following output:

names = [
  "abc",
  "bcd",
]

So, combining this we can do:

variable "foo" {
  default = [
    {
      "name": "abc"
      "id": "123"
    },
    {
      "name": "bcd"
      "id": "345"
    }
  ]
}

output "names" {
  value = var.foo[*].name
}

output "bcd_found" {
  value = contains(var.foo[*].name, "bcd")
}

output "xyz_found" {
  value = contains(var.foo[*].name, "xyz")
}

When this is applied we get the following:

bcd_found = true
names = [
  "abc",
  "bcd",
]
xyz_found = false

Upvotes: 8

Related Questions