如何用Python(boto3)跨区域获取EC2实例CPU使用率并停止低负载实例?
使用Python Boto3监控跨区域EC2实例CPU使用率并自动停止
我来帮你搞定这个跨区域EC2监控的需求!其实用boto3实现起来逻辑很清晰,核心就是三步:通过CloudWatch拉取目标实例的CPU数据,判断是否低于设定阈值,最后调用EC2 API停止实例。下面给你详细拆解和可直接用的代码示例:
前提条件
- 先确保安装了boto3:
pip install boto3 - 执行脚本的实体(本地用户/EC2实例角色等)要有足够的IAM权限:
- CloudWatch权限:
cloudwatch:GetMetricStatistics(用来获取CPU使用率指标) - EC2权限:
ec2:StopInstances(用来停止目标实例)
- CloudWatch权限:
- 目标EC2实例默认已经开启了CloudWatch基础监控(如果需要更实时的监控,可手动启用详细监控)
完整代码实现
import boto3 from datetime import datetime, timedelta def check_and_stop_ec2(target_region, instance_id, cpu_threshold): # 初始化目标区域的CloudWatch和EC2客户端(必须指定区域,否则找不到跨区域实例) cloudwatch = boto3.client('cloudwatch', region_name=target_region) ec2 = boto3.client('ec2', region_name=target_region) # 设置时间范围:取最近5分钟的数据(匹配EC2基础监控的5分钟周期) end_time = datetime.utcnow() start_time = end_time - timedelta(minutes=5) try: # 从CloudWatch拉取CPU使用率的统计数据 metric_response = cloudwatch.get_metric_statistics( Namespace='AWS/EC2', MetricName='CPUUtilization', Dimensions=[{'Name': 'InstanceId', 'Value': instance_id}], StartTime=start_time, EndTime=end_time, Period=300, # 300秒=5分钟,和基础监控周期对齐 Statistics=['Average'], Unit='Percent' ) # 处理无数据的异常情况(比如实例刚启动、监控未生效) if not metric_response['Datapoints']: print(f"⚠️ 警告:未获取到实例 {instance_id} 的CPU数据,请检查实例状态或监控配置") return # 提取最新的CPU使用率平均值(按时间排序确保拿到最新数据) latest_datapoint = sorted(metric_response['Datapoints'], key=lambda x: x['Timestamp'])[-1] current_cpu = latest_datapoint['Average'] print(f"📊 实例 {instance_id} 最近5分钟平均CPU使用率:{current_cpu:.2f}%") # 判断是否触发停止条件 if current_cpu < cpu_threshold: print(f"🔴 CPU使用率低于阈值 {cpu_threshold}%,开始停止实例...") ec2.stop_instances(InstanceIds=[instance_id]) print(f"✅ 实例 {instance_id} 停止请求已成功发送") else: print(f"🟢 CPU使用率高于阈值 {cpu_threshold}%,无需操作") except Exception as e: print(f"❌ 操作出错:{str(e)}") # -------------------------- 配置参数 -------------------------- TARGET_REGION = 'us-west-2' # 替换为目标实例所在的AWS区域 INSTANCE_ID = 'i-1234567890abcdef0' # 替换为你的目标EC2实例ID CPU_THRESHOLD = 10 # 替换为你设定的CPU使用率阈值(百分比) # ------------------------------------------------------------- # 执行监控逻辑 check_and_stop_ec2(TARGET_REGION, INSTANCE_ID, CPU_THRESHOLD)
关键细节说明
- 跨区域核心:一定要在初始化boto3客户端时显式指定
region_name,否则脚本会默认使用当前环境的区域,根本找不到跨区域的实例和监控数据。 - 监控周期适配:代码用的是5分钟周期(基础监控),如果需要1分钟级别的实时监控,得先给目标实例启用详细监控,然后把
Period改成60,start_time改成end_time - timedelta(minutes=1)。 - 数据准确性:通过对数据点按时间排序,确保拿到的是最新的CPU平均值,避免CloudWatch返回数据顺序不稳定导致的误判。
- 错误优化:如果需要更精准的错误提示,可以把通用
Exception替换成boto3.exceptions.ClientError,然后根据错误码(比如InvalidInstanceID.NotFound、AccessDenied)给出针对性提示。
内容的提问来源于stack exchange,提问作者FCoding
相关产品推荐
相关产品推荐

