Skip to content
The Chat Archive
gemini-2.5-pro-exp-03-25-grounding· Google LMArena Search Arena 24K

Acting as an Aws expert can you create a serverless yaml file that deploys a feature…

  1. User

    Acting as an Aws expert can you create a serverless yaml file that deploys a feature into Aws: deleting a kms custom key triggers an alarm and sends an sns Mail

  2. Assistant

    Okay, here is a serverless.yml file that defines the AWS resources needed to monitor a specific KMS key for deletion scheduling and trigger a CloudWatch alarm which then notifies an SNS topic (configured for email).

    This setup uses AWS EventBridge (formerly CloudWatch Events) to capture the specific KMS API call (ScheduleKeyDeletion) via CloudTrail, triggers a CloudWatch Alarm based on that event rule firing, and sends a notification to an SNS Topic.

    Assumptions:

    1. You have the Serverless Framework installed and configured with AWS credentials.
    2. You have an existing KMS Customer Managed Key (CMK) that you want to monitor. You'll need its ARN.
    3. CloudTrail is enabled in your account and region (this is usually the case by default, but ensure it's logging KMS API calls).
    # serverless.yml
    
    service: kms-deletion-monitor
    
    provider:
      name: aws
      runtime: nodejs18.x # Runtime isn't strictly needed as we don't have functions, but required by Serverless
      region: us-east-1 # Change to your desired region
      # Optional: Define IAM Role if more specific permissions are needed beyond what Serverless grants by default
      # iam:
      #   role:
      #     statements:
      #       - Effect: "Allow"
      #         Action:
      #           - "cloudwatch:PutMetricAlarm"
      #           - "cloudwatch:DescribeAlarms"
      #           - "cloudwatch:DeleteAlarms"
      #           - "events:PutRule"
      #           - "events:DescribeRule"
      #           - "events:DeleteRule"
      #           - "events:PutTargets"
      #           - "events:RemoveTargets"
      #           - "sns:CreateTopic"
      #           - "sns:Subscribe"
      #           - "sns:Unsubscribe"
      #           - "sns:DeleteTopic"
      #           - "sns:ListSubscriptionsByTopic"
      #           - "kms:DescribeKey" # Needed to validate Key ARN if needed
      #         Resource: "*" # Scope down if possible
    
    custom:
      kmsKeyArn: "arn:aws:kms:us-east-1:123456789012:key/your-kms-key-id" # <--- REPLACE with your KMS Key ARN
      notificationEmail: "[EMAIL_ADDRESS]" # <--- REPLACE with your email address
    
    resources:
      Resources:
    
        # 1. SNS Topic for Notifications
        KmsDeletionNotificationTopic:
          Type: AWS::SNS::Topic
          Properties:
            DisplayName: "KMS Key Deletion Scheduled Notification"
            TopicName: ${self:service}-${sls:stage}-kms-deletion-topic
    
        # 2. SNS Subscription (Email)
        # IMPORTANT: AWS will send a confirmation email to this address. You MUST click the link to activate the subscription.
        KmsDeletionEmailSubscription:
          Type: AWS::SNS::Subscription
          Properties:
            Protocol: email
            Endpoint: ${self:custom.notificationEmail}
            TopicArn:
              Ref: KmsDeletionNotificationTopic
    
        # 3. EventBridge Rule to detect KMS Key Deletion Scheduling
        KmsDeletionScheduledRule:
          Type: AWS::Events::Rule
          Properties:
            Name: ${self:service}-${sls:stage}-kms-deletion-scheduled-rule
            Description: "Rule to detect when the specified KMS key is scheduled for deletion"
            EventPattern:
              source: ["aws.kms"]
              detail-type: ["AWS API Call via CloudTrail"]
              detail:
                eventSource: ["kms.amazonaws.com"]
                eventName: ["ScheduleKeyDeletion"]
                resources:
                  - arn: ${self:custom.kmsKeyArn} # Filter for the specific key ARN
            State: ENABLED
            # Note: We don't set a target here directly. The CloudWatch Alarm will monitor this rule.
    
        # 4. CloudWatch Alarm triggered by the EventBridge Rule firing
        KmsDeletionAlarm:
          Type: AWS::CloudWatch::Alarm
          Properties:
            AlarmName: ${self:service}-${sls:stage}-KmsKeyDeletionScheduledAlarm
            AlarmDescription: "Alarm triggered when the specified KMS key is scheduled for deletion via EventBridge rule"
            Namespace: AWS/Events # Monitor the EventBridge rule itself
            MetricName: TriggeredRules # Metric indicating the rule fired
            Dimensions:
              - Name: RuleName
                Value:
                  Ref: KmsDeletionScheduledRule # Link alarm to the specific rule
            Statistic: Sum
            Period: 300 # Check over a 5-minute period (adjust as needed)
            EvaluationPeriods: 1 # Trigger after 1 period where the condition is met
            Threshold: 1 # Trigger if the rule fired at least once (Sum >= 1)
            ComparisonOperator: GreaterThanOrEqualToThreshold
            TreatMissingData: notBreaching # If the rule doesn't fire, don't treat it as an alarm state
            AlarmActions:
              - Ref: KmsDeletionNotificationTopic # Send notification to the SNS topic when in ALARM state
            # Optional: OKActions - actions when returning to OK state
            # OkActions:
            #   - Ref: KmsDeletionNotificationTopic
    
      Outputs:
        KmsDeletionNotificationTopicArn:
          Description: "ARN of the SNS Topic for KMS deletion notifications"
          Value:
            Ref: KmsDeletionNotificationTopic
        KmsDeletionAlarmName:
          Description: "Name of the CloudWatch Alarm monitoring KMS key deletion"
          Value:
            Ref: KmsDeletionAlarm
        MonitoredKmsKeyArn:
          Description: "ARN of the KMS Key being monitored"
          Value: ${self:custom.kmsKeyArn}
    
    

    Explanation:

    1. service: Defines the name of your Serverless service stack.
    2. provider: Specifies AWS as the provider, the runtime (needed by Serverless even without Lambda functions), and the target region.
    3. custom: A section to define variables.
      • kmsKeyArn: Crucially, replace the placeholder ARN with the actual ARN of the KMS key you want to monitor.
      • notificationEmail: Replace this with the email address where you want to receive notifications.
    4. resources.Resources: This is where standard AWS CloudFormation resources are defined.
      • KmsDeletionNotificationTopic (AWS::SNS::Topic): Creates the SNS topic that will receive alarm notifications.
      • KmsDeletionEmailSubscription (AWS::SNS::Subscription): Subscribes the specified email address to the SNS topic. Remember to confirm the subscription via the email AWS sends.
      • KmsDeletionScheduledRule (AWS::Events::Rule): Creates an EventBridge rule.
        • EventPattern: This is the core filter. It looks for events from the aws.kms source, specifically AWS API Call via CloudTrail type, where the eventName is ScheduleKeyDeletion, and importantly, it filters these events to only match those where the resources field contains the specific kmsKeyArn you provided.
        • State: ENABLED: Ensures the rule is active.
      • KmsDeletionAlarm (AWS::CloudWatch::Alarm): Creates the CloudWatch alarm.
        • Namespace: AWS/Events, MetricName: TriggeredRules: This tells CloudWatch to monitor the invocations of an EventBridge rule.
        • Dimensions: Links the alarm specifically to the KmsDeletionScheduledRule created earlier.
        • Statistic, Period, EvaluationPeriods, Threshold, ComparisonOperator: Defines the alarm condition: trigger if the Sum of TriggeredRules for our specific rule is >= 1 within a 300-second period.
        • TreatMissingData: notBreaching: If CloudTrail doesn't log the event (meaning the rule doesn't trigger) in a given period, the alarm doesn't go into the ALARM state.
        • AlarmActions: Specifies that when the alarm enters the ALARM state, it should publish a message to the KmsDeletionNotificationTopic.
    5. Outputs: Defines CloudFormation stack outputs, making it easier to find the ARNs/names of created resources after deployment.

    How to Deploy:

    1. Save the code above as serverless.yml.
    2. Replace the placeholder values in the custom section (kmsKeyArn and notificationEmail).
    3. Open your terminal in the same directory as the serverless.yml file.
    4. Run the deployment command: serverless deploy
    5. Wait for the deployment to complete. Check your email and click the confirmation link in the message from AWS SNS to activate the email subscription.

    How it Works Post-Deployment:

    1. If someone (or an automated process) calls the ScheduleKeyDeletion API action on the specific KMS key defined in kmsKeyArn.
    2. CloudTrail logs this API call.
    3. The EventBridge rule (KmsDeletionScheduledRule) detects this specific event based on its pattern.
    4. CloudWatch Logs a TriggeredRules metric for the KmsDeletionScheduledRule.
    5. The CloudWatch alarm (KmsDeletionAlarm) evaluates its metric. It sees that TriggeredRules has a sum >= 1 for the evaluation period.
    6. The alarm state changes to ALARM.
    7. Because the alarm is in the ALARM state, it triggers its AlarmActions, publishing a notification message to the KmsDeletionNotificationTopic.
    8. SNS sends the notification message to all confirmed subscribers (in this case, your email address).

    You will then receive an email indicating that the CloudWatch alarm

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.

Identical first prompt