构建跨区域AWS资源自动修复流程:CloudWatch事件规则配置问询
Hey there, let's walk through building this auto-remediation workflow to clean up resources created outside the eu-central-1 region. First up, the CloudWatch Events rule you started configuring—let's refine it to target exactly the events you care about.
Auto-Remediation Workflow: Clean Up Non-eu-central-1 Resources
Step 1: Configure CloudWatch Events Rule for Resource Creation Detection
This rule will capture API calls that create your target resources only when they're deployed outside eu-central-1. Here's the polished configuration (I added the critical region filter and fixed the wildcard syntax for eventName):
{ "source": [ "aws.cloudtrail" ], "detail-type": [ "AWS API Call via CloudTrail" ], "detail": { "eventSource": [ "ec2.amazonaws.com", "cloudformation.amazonaws.com", "lambda.amazonaws.com" ], "eventName": [ "Create*" ], "region": [ "!=", "eu-central-1" ] } }
Key Notes on This Configuration:
eventName: "Create*": Uses CloudWatch Events wildcard syntax (*) to match all creation-related API calls (e.g.,CreateVpc,CreateStack,CreateFunction,CreateInternetGateway).region: "!=": "eu-central-1": Ensures we only trigger on resources created outside your allowed region—this is the critical filter you were missing to avoid false positives.- Target Services: Covers EC2 (for VPCs, Internet Gateways, EC2 instances), CloudFormation, and Lambda as you specified.
Step 2: Wire Up a Remediation Lambda Function
Once the event rule detects a non-compliant resource creation, it needs to trigger action:
- Set the rule's target to a Lambda function.
- In your Lambda code, parse the CloudTrail event to extract:
- Resource ARN/ID
- Region where the resource was created
- Call the appropriate AWS API to clean up the resource:
- EC2:
DeleteVpc,DeleteInternetGateway,TerminateInstances - CloudFormation:
DeleteStack - Lambda:
DeleteFunction
- EC2:
- Critical: Assign an IAM role to the Lambda with permissions to perform these deletion actions and read CloudTrail event details.
Pro Tips:
- Test the rule first with a Lambda that only logs events (instead of deleting) to validate it's capturing the right resources.
- Add error handling in your Lambda (e.g., retry logic for resources that can't be deleted immediately due to dependencies).
内容的提问来源于stack exchange,提问作者Adrien Merlier
相关产品推荐
相关产品推荐

