Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

terraform

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
}
like image 715
Malar Kandasamy Avatar asked Mar 03 '23 01:03

Malar Kandasamy


1 Answers

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
like image 107
ydaetskcoR Avatar answered Apr 09 '23 07:04

ydaetskcoR