You can trigger an AWS Lambda function in response to AWS CloudTrail events using AWS CLI and CloudWatch Alarms. Here’s a step-by-step guide on how to do it:
- Create an AWS Lambda Function:
If you haven’t already, create the AWS Lambda function that you want to trigger in response to CloudTrail events. - Create a CloudWatch Log Group for CloudTrail Events:
You need to create a CloudWatch Log Group that will receive CloudTrail events. ReplaceYOUR_LOG_GROUP_NAME
with your desired log group name.
aws logs create-log-group --log-group-name YOUR_LOG_GROUP_NAME
- Set Up a CloudWatch Logs Subscription Filter:
Configure a subscription filter to forward CloudTrail events to the CloudWatch Log Group. ReplaceYOUR_TRAIL_NAME
with the name of your CloudTrail trail.
aws logs put-subscription-filter \
--log-group-name YOUR_LOG_GROUP_NAME \
--filter-name CloudTrailFilter \
--filter-pattern '' \
--destination-arn arn:aws:lambda:YOUR_REGION:YOUR_ACCOUNT_ID:function/YOUR_LAMBDA_FUNCTION_NAME \
--role-arn arn:aws:iam::YOUR_ACCOUNT_ID:role/service-role/YOUR_LAMBDA_EXECUTION_ROLE
YOUR_REGION
: Replace with your AWS region.YOUR_ACCOUNT_ID
: Replace with your AWS account ID.YOUR_LAMBDA_FUNCTION_NAME
: Replace with the name of your Lambda function.YOUR_LAMBDA_EXECUTION_ROLE
: Replace with the ARN of the role that grants CloudWatch Logs permission to invoke the Lambda function.
- Create a CloudWatch Alarm:
Create a CloudWatch Alarm based on the Log Group’s metric filter. This alarm will trigger the Lambda function when CloudTrail events match the specified pattern.
aws cloudwatch put-metric-alarm \
--alarm-name CloudTrailEventAlarm \
--alarm-description "CloudTrail Event Alarm" \
--actions-enabled \
--alarm-actions arn:aws:automate:YOUR_REGION:ec2:stop \
--metric-name EventCount \
--namespace AWS/Logs \
--statistic Sum \
--period 300 \
--threshold 1 \
--comparison-operator GreaterThanOrEqualToThreshold \
--evaluation-periods 1 \
--alarm-description "Trigger Lambda on CloudTrail Event" \
--dimensions Name=LogGroupName,Value=YOUR_LOG_GROUP_NAME
- Replace
YOUR_REGION
andYOUR_LOG_GROUP_NAME
with the appropriate values. - In this example, the alarm is set to trigger the Lambda function when at least one CloudTrail event is logged. Adjust the
threshold
andcomparison-operator
as needed based on your specific requirements.
Now, your AWS Lambda function should be triggered when a CloudTrail event matches the pattern specified in the CloudWatch Alarm. Make sure to replace the placeholders with your actual values.