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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With