I am trying to access the first key on a given tuple. The key's name is dynamic and may change so it cannot be accessed using a static value and has to be done either through a for loop or through the use of terraform fuctions.
I've created a small local resource that outputs the following section
skip_empty_mails = { for key, value in local.j.settings.tasks : key => value.email_notifications if value.email_notifications != {} }
The output sent back is
{
"3" = {
"on_start" = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]
}
"4" = {
"no_alert_for_skipped_runs" = false
"on_start" = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]
]
"on_start" = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]
"on_success" = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]
}
}
As seen above the key that holds all the values needs to be accessed in a way that will give me the ability to attach it to a string and use string.on_start
to pull its values.
The issue is that our key's name is dynamic and may vary.
I've tried following the terraform function documentation But haven't found anything that might be of use in this case.
You may be able to replicate using the following code
locals {
json = {
"3" = {
"on_start" = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]
},
"4" = {
"no_alert_for_skipped_runs" = false
"on_failure" = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]
"on_start" = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]
"on_success" = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]
}
}
}
CodePudding user response:
You can try with a combination of values
, element
or flatten
see the documentation:
- https://developer.hashicorp.com/terraform/language/functions/values
- https://developer.hashicorp.com/terraform/language/functions/element
- https://developer.hashicorp.com/terraform/language/functions/flatten
Below are samples:
First key extraction
locals {
json = {
"4" = {
"no_alert_for_skipped_runs" = false
"on_failure" = [
"[email protected]",
"[email protected]",
]
"on_start" = [
"[email protected]",
"[email protected]",
]
}
}
}
output "data" {
value = element(values(local.json), 1).on_start
}
the Terraform plan will be:
Changes to Outputs:
data = [
"[email protected]",
"[email protected]",
]
Extract and combine on_start item from all
locals {
json = {
"3" = {
"on_start" = [
"[email protected]",
"[email protected]",
]
},
"4" = {
"on_start" = [
"[email protected]",
"[email protected]",
]
}
}
}
output "data" {
value = flatten(values(local.json)[*].on_start)
}
the Terraform plan will be:
Changes to Outputs:
data = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]