data "aws_caller_identity" "this" {} resource "random_id" "this" { byte_length = 2 } resource "aws_cloudwatch_event_rule" "this" { name = "${var.res-prefix}-ssl-cert-expiry-${random_id.this.dec}" description = "Reminder of SSL expiring certificates" event_pattern = jsonencode({ "source" : ["aws.acm"], "detail-type" : ["ACM Certificate Approaching Expiration"] }) } resource "aws_cloudwatch_event_target" "sns" { rule = aws_cloudwatch_event_rule.this.name target_id = "ssl-cert-expiry-sns-${random_id.this.dec}" arn = aws_sns_topic.ssl-cert-expiry-notice.arn input_transformer { input_paths = { "cert" : "$.resources[0]", "days" : "$.detail.DaysToExpiry", "cn" : "$.detail.CommonName" } input_template = <<-EOT "The following ACM certificate will expire soon" "ID: " "CommonName: " "Days to expiry: " EOT } } # Modify ACM DaysBeforeExpiry account setting if it should be set lower than the default 45 days module "awscli" { count = var.days-before-expiry < 45 ? 1 : 0 source = "../../util/terraform-aws-cli" role_session_name = "terraform-awscli" aws_cli_commands = ["acm", "put-account-configuration", "--idempotency-token", random_id.this.dec, "--expiry-events DaysBeforeExpiry=${var.days-before-expiry}"] } # SNS topic and subscription resource "aws_sns_topic" "ssl-cert-expiry-notice" { name = "${var.res-prefix}-ssl-cert-expiry-notice-${random_id.this.dec}" kms_master_key_id = var.sns-kms-key-arn } resource "aws_sns_topic_policy" "default" { arn = aws_sns_topic.ssl-cert-expiry-notice.arn policy = data.aws_iam_policy_document.sns_topic_policy.json } data "aws_iam_policy_document" "sns_topic_policy" { statement { sid = "AllowPublishingFromEvents" effect = "Allow" actions = [ "sns:Publish", "SNS:Publish" ] principals { type = "Service" identifiers = ["events.amazonaws.com"] } resources = [aws_sns_topic.ssl-cert-expiry-notice.arn] } statement { sid = "AllowPublishThroughSSLOnly" effect = "Deny" principals { identifiers = ["*"] type = "AWS" } actions = [ "sns:Publish", "SNS:Publish" ] condition { test = "Bool" values = ["false"] variable = "aws:SecureTransport" } resources = [aws_sns_topic.ssl-cert-expiry-notice.arn] } } resource "aws_sns_topic_subscription" "ssl-cert-expiry-notice-sub" { for_each = var.email-addresses topic_arn = aws_sns_topic.ssl-cert-expiry-notice.arn protocol = "email" endpoint = each.value }