diff --git a/terraform/main.tf b/terraform/main.tf index 51ba01a1..7b599787 100644 --- a/terraform/main.tf +++ b/terraform/main.tf @@ -181,6 +181,26 @@ module "db-sns" { alert_pagerduty_integration_url = var.alert_pagerduty_integration_url } +module "backoffice-restart-alerts" { + source = "./modules/ecs-restart-alerts" + count = var.enable_restart_alerts ? 1 : 0 + service_name = "backoffice" + cluster_arn = module.droits-ecs-cluster.ecs_cluster_arn + alerts_topic_arn = module.backoffice-sns.alerts-topic-arn + + depends_on = [module.droits-ecs-cluster, module.backoffice-sns] +} + +module "webapp-restart-alerts" { + source = "./modules/ecs-restart-alerts" + count = var.enable_restart_alerts ? 1 : 0 + service_name = "webapp" + cluster_arn = module.droits-ecs-cluster.ecs_cluster_arn + alerts_topic_arn = module.webapp-sns.alerts-topic-arn + + depends_on = [module.droits-ecs-cluster, module.webapp-sns] +} + module "elasticache" { source = "./modules/elasticache" vpc_id = module.vpc.vpc_id diff --git a/terraform/modules/ecs-cluster/outputs.tf b/terraform/modules/ecs-cluster/outputs.tf index 4ffee331..f0e2e344 100644 --- a/terraform/modules/ecs-cluster/outputs.tf +++ b/terraform/modules/ecs-cluster/outputs.tf @@ -1,3 +1,7 @@ output "ecs_cluster_id" { value = aws_ecs_cluster.droits-ecs-cluster.id -} \ No newline at end of file +} + +output "ecs_cluster_arn" { + value = aws_ecs_cluster.droits-ecs-cluster.arn +} diff --git a/terraform/modules/ecs-restart-alerts/main.tf b/terraform/modules/ecs-restart-alerts/main.tf new file mode 100644 index 00000000..aec6d7ed --- /dev/null +++ b/terraform/modules/ecs-restart-alerts/main.tf @@ -0,0 +1,90 @@ +locals { + alarm_name = "ecs-${terraform.workspace}-droits-${var.service_name}-container-restarted" +} + +resource "aws_cloudwatch_event_rule" "task_stopped" { + name = "ecs-${terraform.workspace}-droits-${var.service_name}-task-stopped" + description = "ECS container stopped" + + event_pattern = jsonencode({ + source = ["aws.ecs"] + "detail-type" = ["ECS Task State Change"] + detail = { + clusterArn = [var.cluster_arn] + group = ["service:${var.service_name}"] + lastStatus = ["STOPPED"] + } + }) +} + +resource "aws_cloudwatch_event_target" "task_stopped" { + rule = aws_cloudwatch_event_rule.task_stopped.name + target_id = "${var.service_name}-task-stopped-alerts" + arn = var.alerts_topic_arn + + input_transformer { + input_paths = { + time = "$.time" + account = "$.account" + region = "$.region" + taskArn = "$.detail.taskArn" + stopCode = "$.detail.stopCode" + reason = "$.detail.stoppedReason" + } + + input_template = <<-EOT + { + "AlarmName": "${local.alarm_name}", + "AlarmDescription": "Container has restarted", + "NewStateValue": "ALARM", + "NewStateReason": "Task stopped with code : ", + "StateChangeTime": "