Search code examples
amazon-web-servicesterraformamazon-cloudwatch

Trying to create multiple widgets for an AWS cloudwatch dashboard using terraform, I don't want to keep copying an pasting?


variable "aws_instance_list" {
type = list 
default = ["i-07dd009cf6a72720b","i-047101ccb46330773"] 
}




resource "aws_cloudwatch_dashboard" "main" {
  dashboard_name = "my-dashboard"
  dashboard_body = jsonencode({
    widgets = [
      {
        type   = "metric"
        x      = 0
        y      = 0
        width  = 12
        height = 6
        properties = {
          metrics = [
            [
              "AWS/EC2",
              "CPUUtilization",
              "InstanceId",
              "i-07dd009cf6a72720b" #want this to change for each loop from the list
            ]
          ]
          period = 300
          stat   = "Average"
          region = "us-east-1"
          title  = "EC2 Instance CPU"
        }
      }
    ]
  })
}

I'm trying to iterate the widgets section, rather than copy and pasting the whole block again and again. was hoping to refer to a list. Any ideas on how I could implement this?


Solution

  • Here's the same demo using string templates and jsonencode. Hope this helps!

    # providers
    terraform {
      required_providers {
        local = {
          source = "hashicorp/local"
          version = "2.4.1"
        }
      }
    }
    
    variable "aws_instance_list" {
      type = list(string)
      default = ["i-07dd009cf6a72720b","i-047101ccb46330773"] 
    }
    
    
    # Output widgets JSON
    #    for s in var.aws_instance_list :
    output "all_widgets" {
      value = jsonencode(
         [ for i in var.aws_instance_list :
          {
            type   = "metric"
            x      = 0
            y      = 0
            width  = 12
            height = 6
            properties = {
              metrics = [
                [
                  "AWS/EC2",
                  "CPUUtilization",
                  "InstanceId",
                  "${i}" #want this to change for each loop from the list
                ]
              ]
              period = 300
              stat   = "Average"
              region = "us-east-1"
              title  = "EC2 Instance CPU"
            }
          }
         ]   
      )
    }
    

    Show output with: terraform output -raw all_widgets.

    See also: Terraform JSON generation and Resource: aws_cloudwatch_dashboard