I’m trying to create a CloudWatch dashboard and I’m having some difficulties with trying to loop through a variable and evaluate which objects should be created inside of a jsonencode() function.
https://registry.terraform.io/providers/hashicorp/aws/5.4.0/docs/resources/cloudwatch_dashboard
Main.tf
resource "aws_cloudwatch_dashboard" "cloudwatch_dashboard" {
dashboard_name = var.dashboard_name
dashboard_body = jsonencode(
{
"start" = var.dashboard_start_time
"end" = var.dashboard_end_time
"periodOverride" = var.dashboard_period_override
"widgets" = [for item in var.widgets : {
"type" = lookup(item, "type")
"x" = lookup(item, "x", null)
"y" = lookup(item, "y", null)
"width" = lookup(item, "width", null)
"height" = lookup(item, "height", null)
"properties" = {
"markdown" = lookup(item.widget_properties[0], "markdown"),
"background" = lookup(item.widget_properties[0], "background", "solid")
}
"properties" = {
"region" = lookup(item, "region", null)
"title" = lookup(item, "title", "Default Widget Title")
"query" = lookup(item, "query", null)
"view" = lookup(item, "view", null)
}
}]
}
)
}
Variables.tf
variable "widgets" {
default = [
{
type = "text"
x = "123"
y = "456"
width = "abc"
widget_properties = [{
markdown = "Hello"
}]
},
{
type = "text"
x = "789"
y = "987"
width = "def"
widget_properties = [{
markdown = "Hi"
}]
},
{
type = "log"
x = "123"
y = "456"
width = "ghi"
widget_properties = [{
region = "us-east-1"
title = "test"
query = ""
view = ""
}]
}
]
}
What I’m trying to achieve is something like this example below where there are two widget objects defined in the JSON body. One for type = metric and another for type = text.
What I haven’t been able to figure out yet is how to only evaluate the first properties block when type = text
and then only evaluate the second properties block if type = metric
.
I’ve tried a few things such as directives but that doesn’t seem to work within the jsonencode function. I’ve tried using a templatefile with an interpolated jsonencode call. I’ve also tried to use a for loop with an ending if statement inside the properties block but that didn’t work either.
Is there a good way to approach this? Would I want to create the properties inside of a local block then somehow add those to the JSON body?