Acting as an Aws expert can you create a serverless yaml file that deploys a feature…
- 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
- Assistant
Okay, here is a
serverless.ymlfile 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:
- You have the Serverless Framework installed and configured with AWS credentials.
- You have an existing KMS Customer Managed Key (CMK) that you want to monitor. You'll need its ARN.
- 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:
service: Defines the name of your Serverless service stack.provider: Specifies AWS as the provider, the runtime (needed by Serverless even without Lambda functions), and the target region.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.
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 theaws.kmssource, specificallyAWS API Call via CloudTrailtype, where theeventNameisScheduleKeyDeletion, and importantly, it filters these events to only match those where theresourcesfield contains the specifickmsKeyArnyou 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 theKmsDeletionScheduledRulecreated earlier.Statistic,Period,EvaluationPeriods,Threshold,ComparisonOperator: Defines the alarm condition: trigger if theSumofTriggeredRulesfor our specific rule is>= 1within a300-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 theALARMstate, it should publish a message to theKmsDeletionNotificationTopic.
Outputs: Defines CloudFormation stack outputs, making it easier to find the ARNs/names of created resources after deployment.
How to Deploy:
- Save the code above as
serverless.yml. - Replace the placeholder values in the
customsection (kmsKeyArnandnotificationEmail). - Open your terminal in the same directory as the
serverless.ymlfile. - Run the deployment command:
serverless deploy - 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:
- If someone (or an automated process) calls the
ScheduleKeyDeletionAPI action on the specific KMS key defined inkmsKeyArn. - CloudTrail logs this API call.
- The EventBridge rule (
KmsDeletionScheduledRule) detects this specific event based on its pattern. - CloudWatch Logs a
TriggeredRulesmetric for theKmsDeletionScheduledRule. - The CloudWatch alarm (
KmsDeletionAlarm) evaluates its metric. It sees thatTriggeredRuleshas a sum >= 1 for the evaluation period. - The alarm state changes to
ALARM. - Because the alarm is in the
ALARMstate, it triggers itsAlarmActions, publishing a notification message to theKmsDeletionNotificationTopic. - 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
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.