如何借助EC2实现基于入站连接IP数阈值的已有服务器自动启动?
How to Auto-Start an EC2 Instance When Inbound Source IP Count Exceeds X
Got it, let's walk through building this solution step by step—this combines AWS EC2 with other core services to get the custom monitoring and automation you need.
1. Capture Inbound Traffic & Calculate Unique Source IPs
First, we need to track how many distinct source IPs are sending traffic to your resources. Here's the reliable way to do this:
- Enable VPC Flow Logs: Turn on VPC Flow Logs for your target VPC (or specific subnets/network interfaces) and configure them to send logs to CloudWatch Logs. Filter for
ACCEPTaction andingressdirection to focus on valid incoming connections—this avoids counting rejected traffic that doesn't count as actual inbound connections. - Build a Lambda Function to Generate Custom Metrics: Create a Lambda function that runs on a schedule (via EventBridge) to:
- Query CloudWatch Logs Insights with this SQL to count unique source IPs in the last 5 minutes:
fields @timestamp, srcaddr | filter action = 'ACCEPT' and direction = 'ingress' | stats count_distinct(srcaddr) as unique_source_ips | sort @timestamp desc | limit 1 - Pull the
unique_source_ipsvalue from the query results. - Send this value as a custom metric to CloudWatch using the
put_metric_dataAPI. Name the metricUniqueInboundSourceIPsunder a namespace likeCustomNetworkMetricsfor easy tracking.
- Query CloudWatch Logs Insights with this SQL to count unique source IPs in the last 5 minutes:
2. Set Up a CloudWatch Alarm to Trigger the Action
Once your custom metric is live in CloudWatch, create an alarm to trigger when the threshold is hit:
- Navigate to CloudWatch > Alarms > Create alarm.
- Select your custom metric (
CustomNetworkMetrics > UniqueInboundSourceIPs). - Set the threshold to your value
X, chooseGreaterThanThresholdas the comparison operator, and set the evaluation period (e.g., 1 period of 5 minutes for quick detection). - For the alarm action, create or use an existing SNS topic, then subscribe your instance-starting Lambda function to this topic.
3. Write the Lambda Function to Start Your EC2 Instance
Create a second Lambda function (or add this logic to your existing metric function if it makes sense) to handle the SNS trigger and start your target instance:
- Here's a sample Python snippet to get you started:
import boto3 ec2 = boto3.client('ec2') TARGET_INSTANCE_ID = 'i-1234567890abcdef0' # Replace with your instance ID def lambda_handler(event, context): try: response = ec2.start_instances(InstanceIds=[TARGET_INSTANCE_ID]) print(f"Successfully started instance {TARGET_INSTANCE_ID}: {response}") return { 'statusCode': 200, 'body': f"Instance {TARGET_INSTANCE_ID} started successfully" } except Exception as e: print(f"Error starting instance: {e}") raise e - Configure IAM Permissions: Make sure the Lambda execution role has the
ec2:StartInstancespermission for your target instance. Attach a policy like this (replace placeholders with your region, account ID, and instance ID):{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ec2:StartInstances", "Resource": "arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0" } ] }
4. Test the Workflow
- Simulate inbound traffic from multiple source IPs (use
curlfrom different machines or cloud instances, for example). - Check CloudWatch to confirm your custom metric updates with the correct IP count.
- Verify that when the metric exceeds
X, the alarm triggers, the SNS topic sends a notification, and your Lambda function starts the EC2 instance successfully.
Quick Notes
- Instance State: Your target EC2 instance must be in a
stoppedstate (not terminated) to be started. - Cost: This setup uses low-cost services (VPC Flow Logs, Lambda, CloudWatch, SNS) but double-check AWS pricing for your region to avoid unexpected charges.
- Tuning: Adjust the Lambda schedule and alarm evaluation periods based on how quickly you need to respond to threshold breaches.
内容的提问来源于stack exchange,提问作者user1898525
相关产品推荐
相关产品推荐

