Automate AWS Trusted Advisor Remediation with Amazon EventBridge and Lambda
This article provides a step-by-step guide to automatically remediate AWS Trusted Advisor findings using Amazon EventBridge rules and AWS Lambda functions. It covers building event-driven automation that detects Trusted Advisor status changes, takes corrective action automatically, and includes a working code example for restricting open security groups.
How do I automate remediation of AWS Trusted Advisor findings using Amazon EventBridge and AWS Lambda?
This article explains how to use Amazon EventBridge and AWS Lambda to automatically remediate common AWS Trusted Advisor findings, such as unrestricted security groups and missing logging configurations.
Introduction
AWS Trusted Advisor continuously evaluates your AWS environment and recommends best practices across cost, performance, security, and fault tolerance. However, many teams address these recommendations manually, which creates delays between detection and resolution.
By connecting Trusted Advisor to Amazon EventBridge, you can trigger automated remediation the moment a check status changes. This article walks through the full setup: creating an EventBridge rule that matches Trusted Advisor events, building a Lambda function that fixes the issue, and notifying your team of the change.
Architecture overview
The architecture follows a simple event-driven pattern:
Trusted Advisor check refresh
→ EventBridge rule (filter by check name + status)
→ Lambda function (remediate the resource)
→ SNS topic (notify the team)
When Trusted Advisor refreshes a check and detects a new issue (status changes to WARN or ERROR), it emits an event to EventBridge. Your rule matches the event and invokes a Lambda function that performs the fix. The Lambda also publishes a notification to SNS so your team knows what was changed.
Prerequisites
Before you begin, ensure you have:
- An AWS account with Business Support+ or Enterprise Support plan (required for Trusted Advisor EventBridge integration)
- An Amazon SNS topic for notifications
- Familiarity with the AWS Lambda console
Important: Trusted Advisor emits all events to EventBridge in the US East (N. Virginia) us-east-1 Region only. Your EventBridge rule and Lambda function must be deployed in us-east-1, even if your resources are in other regions.
Step 1: Create an SNS topic for notifications
Always notify your team when auto-remediation occurs. Create an SNS topic first.
- Open the Amazon SNS console in us-east-1.
- Choose Topics, then Create topic.
- Select Standard, enter a name (for example,
TrustedAdvisorRemediation). - Choose Create topic.
- Create a subscription with your preferred notification channel (email, Slack via AWS Chatbot, etc.).
Step 2: Create the Lambda function
This example creates a function that removes unrestricted SSH (port 22) access from security groups when Trusted Advisor flags them.
- Open the Lambda console in us-east-1.
- Choose Create function > Author from scratch.
- Enter function name:
TA-RemediateOpenSSH - Runtime: Python 3.12
- Under Permissions, create a new role with the following IAM policy:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:DescribeSecurityGroups", "ec2:RevokeSecurityGroupIngress" ], "Resource": "*" }, { "Effect": "Allow", "Action": "sns:Publish", "Resource": "arn:aws:sns:us-east-1:ACCOUNT_ID:TrustedAdvisorRemediation" }, { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:us-east-1:ACCOUNT_ID:*" } ] }
- Paste the following function code:
import boto3 import json import os ec2 = boto3.client('ec2') sns = boto3.client('sns') SNS_TOPIC_ARN = os.environ['SNS_TOPIC_ARN'] def lambda_handler(event, context): """ Receives a Trusted Advisor event for unrestricted security groups and revokes 0.0.0.0/0 ingress on port 22 (SSH). """ detail = event.get('detail', {}) status = detail.get('status') # Only act on WARN or ERROR status if status not in ('WARN', 'ERROR'): return {'statusCode': 200, 'body': 'No action needed'} # Extract security group info from the event check_item_detail = detail.get('check-item-detail', {}) sg_id = check_item_detail.get('Security Group ID', '') region = check_item_detail.get('Region', 'us-east-1') if not sg_id: print(f"No Security Group ID found in event: {json.dumps(event)}") return {'statusCode': 400, 'body': 'Missing SG ID'} # Create a regional EC2 client (resources may be in any region) regional_ec2 = boto3.client('ec2', region_name=region) try: # Revoke SSH (port 22) from 0.0.0.0/0 regional_ec2.revoke_security_group_ingress( GroupId=sg_id, IpPermissions=[{ 'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}] }] ) message = f"REMEDIATED: Revoked SSH (port 22) from 0.0.0.0/0 on {sg_id} in {region}" print(message) except Exception as e: message = f"FAILED to remediate {sg_id} in {region}: {str(e)}" print(message) # Notify team sns.publish( TopicArn=SNS_TOPIC_ARN, Subject='Trusted Advisor Auto-Remediation', Message=message ) return {'statusCode': 200, 'body': message}
- Add environment variable:
SNS_TOPIC_ARN= your SNS topic ARN. - Set timeout to 30 seconds.
- Choose Deploy.
Step 3: Create the EventBridge rule
- Open the Amazon EventBridge console in us-east-1.
- Choose Rules, then Create rule.
- Name:
TA-UnrestrictedSG-Remediation - Keep default event bus. Choose Next.
- For Event source, choose AWS events or EventBridge partner events.
- For AWS service, choose Trusted Advisor.
- For Event type, choose Check Item Refresh Status.
- For status, choose Specific status(es) > select WARN and ERROR.
- For checks, choose Specific check(s) > select Security Groups – Specific Ports Unrestricted.
- Choose Next.
- For target, select Lambda function > choose
TA-RemediateOpenSSH. - Complete the wizard and choose Create rule.
Understanding the event payload
When Trusted Advisor emits an event, it follows this structure:
{ "version": "0", "id": "example-event-id", "detail-type": "Trusted Advisor Check Item Refresh Notification", "source": "aws.trustedadvisor", "account": "111222333444", "time": "2026-06-01T12:00:00Z", "region": "us-east-1", "resources": [], "detail": { "check-name": "Security Groups - Specific Ports Unrestricted", "check-item-detail": { "Status": "Red", "Region": "us-west-2", "Security Group Name": "my-sg", "Security Group ID": "sg-0123456789abcdef0", "Protocol": "tcp", "From Port": "22", "To Port": "22" }, "status": "ERROR", "resource_id": "sg-0123456789abcdef0", "uuid": "example-uuid" } }
The check-item-detail fields correspond to the check's report columns documented in the Trusted Advisor check reference. Use these fields to target the exact resource for remediation.
Step 4: Test the remediation
- Create a test security group with an inbound rule allowing SSH (port 22) from
0.0.0.0/0. - Trigger a Trusted Advisor refresh:
aws support refresh-trusted-advisor-check --check-id HCP4007jGY --region us-east-1 - Wait for the refresh to complete (typically a few minutes).
- Verify:
- EventBridge rule invocation count in CloudWatch Metrics
- Lambda execution in CloudWatch Logs
- SSH rule removed from the security group
- SNS notification received
Additional remediation examples
The official aws/Trusted-Advisor-Tools GitHub repository provides production-ready examples:
| Check | Remediation | Folder |
|---|---|---|
| Low utilization EC2 instances | Stop instances | LowUtilizationEC2Instances |
| EBS volumes without backup | Create snapshots | AmazonEBSSnapshots |
| Exposed IAM access keys | Delete keys + notify | ExposedAccessKeys |
| S3 buckets without versioning | Enable versioning | S3BucketVersioning |
| Idle RDS instances | Snapshot + stop | AmazonRDSIdleDBInstances |
| Unassociated Elastic IPs | Release EIPs | UnassociatedElasticIPs |
Best practices
- Always notify. Send alerts alongside every auto-remediation. Never fix silently.
- Start with low-risk checks. Enable logging and versioning before automating destructive actions like stopping instances.
- Deploy a dry-run mode first. Log what WOULD be fixed for a week, then enable actual remediation after confirming accuracy.
- Scope IAM tightly. Each Lambda gets permissions only for its specific remediation action.
- Track remediations. Use a DynamoDB table to log every action (timestamp, resource, region, result) for audit trail.
- Complement with AWS Config. Trusted Advisor events are best-effort and fire on refresh (not real-time). For critical controls needing immediate detection, use AWS Config rules with Systems Manager Automation.
Important notes
- Events are delivered on a best-effort basis and are not guaranteed. Do not rely solely on this for critical security controls.
- All events emit to us-east-1 only. Your Lambda must handle cross-region resources using regional API clients.
- This requires Business Support+ or Enterprise Support plan.
- Not all checks provide detailed resource information in the event payload. Test each check's event structure before building automation.
Conclusion
By connecting Trusted Advisor to EventBridge and Lambda, you can shift from reactive manual remediation to proactive automated fixes. Start with one or two low-risk checks, validate the behavior in dry-run mode, and expand as you gain confidence in the automation.
Related information
Related information
- Monitoring AWS Trusted Advisor check results with Amazon EventBridge (https://docs.aws.amazon.com/awssupport/latest/user/cloudwatch-events-ta.html)
- Trusted Advisor Tools (GitHub) (https://github.com/aws/Trusted-Advisor-Tools)
- Trusted Advisor check reference (https://docs.aws.amazon.com/awssupport/latest/user/trusted-advisor-check-reference.html)
- Create an EventBridge rule (https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule.html)
- How to Prioritize AWS Trusted Advisor Findings Using a Risk and Effort Matrix (https://repost.aws/articles/ARJS3dihmxRw6opo3uOzPKwQ)
- How to Schedule Automatic AWS Trusted Advisor Check Refreshes Using EventBridge Scheduler (https://repost.aws/articles/ARWBH1coJ4TOmM-379bB_myA)
- Language
- English
Relevant content
asked 2 years ago
AWS OFFICIALUpdated a month ago
AWS OFFICIALUpdated 2 years ago