To dynamically create CloudWatch dashboards in Terraform, you can use the aws_cloudwatch_dashboard resource in Terraform. You can define a Terraform template that creates the dashboard and its widgets, and use Terraform variables to pass in different values for each deployment.
Here's an example of how you can create a simple dashboard with a single line graph widget:
provider "aws" {
region = "us-west-2"
}
variable "dashboard_name" {
type = string
}
variable "widget_metric_name" {
type = string
}
resource "aws_cloudwatch_dashboard" "example" {
dashboard_name = var.dashboard_name
dashboard_body = <<EOF
{
"widgets": [
{
"type": "metric",
"x": 0,
"y": 0,
"width": 12,
"height": 6,
"properties": {
"metrics": [
[ "AWS/EC2", "CPUUtilization", "InstanceId", "i-049df61146f277901" ],
[ ".", ".", ".", "i-0682af8ca95c71c99" ]
],
"period": 300,
"stat": "Average",
"region": "us-west-2",
"title": "${var.widget_metric_name}"
}
}
]
}
EOF
}
You can deploy this Terraform template by running terraform apply and passing in the desired values for the dashboard_name and widget_metric_name variables. For example:
javascriptCopy code
terraform apply -var 'dashboard_name=MyDashboard' -var 'widget_metric_name=EC2 CPU Utilization'
This will create a new CloudWatch dashboard with the specified name and a single line graph widget displaying the average CPU utilization for two EC2 instances. You can modify the Terraform template to include additional widgets and customize the dashboard as desired.