# CloudPeek alarms dashboard: one Alarm status widget listing the alarms you choose, with the ones
# that are firing at the top. The Terraform twin of cloudpeek-alarms.yaml.
# Guide: https://cloudpeek.app/docs/alarms.html
#
# If the alarms are defined in the same configuration, list them as
# aws_cloudwatch_metric_alarm.<name>.arn instead of the alarm_arns variable: see the guide.
#
# Save this file in an empty directory, set alarm_arns (for example in terraform.tfvars), then
# run: terraform init && terraform apply
# To add it to an existing configuration instead, leave out the terraform and provider blocks.

terraform {
  required_version = ">= 1.3"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0"
    }
  }
}

# Dashboards are global, and each alarm ARN names its own region; any region will do.
provider "aws" {
  region = "us-east-1"
}

variable "dashboard_name" {
  description = "Name of the CloudWatch dashboard to create."
  type        = string
  default     = "CloudPeek-Alarms"
}

variable "widget_title" {
  description = "The widget's title, as CloudPeek shows it."
  type        = string
  default     = "Production alarms"
}

variable "alarm_arns" {
  description = "The ARNs of the alarms to list. Each ARN names its own region, so one widget can list alarms from several regions."
  type        = list(string)

  validation {
    condition     = length(var.alarm_arns) > 0
    error_message = "List at least one alarm ARN."
  }
}

# sortBy puts the most recent change first within each state; CloudPeek always lists alarms in
# ALARM first.
resource "aws_cloudwatch_dashboard" "alarms" {
  dashboard_name = var.dashboard_name
  dashboard_body = jsonencode({
    widgets = [
      {
        type   = "alarm"
        x      = 0
        y      = 0
        width  = 12
        height = 6
        properties = {
          title  = var.widget_title
          sortBy = "stateUpdatedTimestamp"
          alarms = var.alarm_arns
        }
      },
    ]
  })
}

output "dashboard_url" {
  description = "The dashboard in the CloudWatch console."
  value       = "https://console.aws.amazon.com/cloudwatch/home#dashboards/dashboard/${aws_cloudwatch_dashboard.alarms.dashboard_name}"
}
