You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过AWS Boto3获取EC2实例对应的ASG名称及详情

最优实现步骤

1. 直接关联ASG与实例,绕过Requestor ID限制

使用Boto3的autoscaling客户端调用describe_auto_scaling_groups()接口,该接口会返回每个Auto Scaling组(ASG)的完整信息,包括其绑定的所有实例ID,无需依赖DescribeInstances()返回的Requestor ID,能直接建立ASG和实例的对应关系。

示例代码:

import boto3

# 初始化客户端
autoscaling_client = boto3.client('autoscaling')
cloudwatch_client = boto3.client('cloudwatch')

# 获取所有ASG及其关联实例
asg_list = autoscaling_client.describe_auto_scaling_groups()['AutoScalingGroups']

2. 收集实例利用率数据

通过CloudWatch获取实例的CPU、内存等利用率指标(内存需提前配置CloudWatch Agent收集自定义指标),以此判断实例是否属于低利用率范畴。以CPU利用率为例:

import datetime

def get_avg_cpu_utilization(instance_id):
    # 查询过去24小时的小时级平均CPU利用率
    response = cloudwatch_client.get_metric_statistics(
        Namespace='AWS/EC2',
        MetricName='CPUUtilization',
        Dimensions=[{'Name': 'InstanceId', 'Value': instance_id}],
        StartTime=datetime.datetime.utcnow() - datetime.timedelta(hours=24),
        EndTime=datetime.datetime.utcnow(),
        Period=3600,
        Statistics=['Average'],
        Unit='Percent'
    )
    # 计算平均值,无数据时默认标记为高利用率避免误删
    if response['Datapoints']:
        return sum(dp['Average'] for dp in response['Datapoints']) / len(response['Datapoints'])
    return 100

3. 筛选需删除的低利用率ASG

根据业务规则设定利用率阈值(比如平均CPU低于10%),遍历所有ASG,统计其下实例的整体利用率,标记符合删除条件的ASG:

LOW_CPU_THRESHOLD = 10.0
asgs_to_delete = []

for asg in asg_list:
    asg_name = asg['AutoScalingGroupName']
    instance_ids = [inst['InstanceId'] for inst in asg['Instances']]
    
    if not instance_ids:
        continue
    
    # 计算ASG下所有实例的平均CPU利用率
    cpu_avgs = [get_avg_cpu_utilization(inst_id) for inst_id in instance_ids]
    overall_avg = sum(cpu_avgs) / len(cpu_avgs)
    
    if overall_avg < LOW_CPU_THRESHOLD:
        asgs_to_delete.append(asg_name)
        print(f"标记待删除ASG:{asg_name},整体平均CPU:{overall_avg:.2f}%")

4. 删除ASG及关联实例

调用delete_auto_scaling_group()接口,设置ForceDelete=True可强制删除ASG,同时自动终止其关联的实例,无需单独处理实例删除:

for asg_name in asgs_to_delete:
    try:
        autoscaling_client.delete_auto_scaling_group(
            AutoScalingGroupName=asg_name,
            ForceDelete=True
        )
        print(f"成功删除ASG:{asg_name}及其实例")
    except Exception as e:
        print(f"删除ASG {asg_name}失败:{str(e)}")

注意事项

  • 权限配置:确保执行代码的IAM角色拥有autoscaling:DescribeAutoScalingGroups、autoscaling:DeleteAutoScalingGroup、cloudwatch:GetMetricStatistics、ec2:TerminateInstances等权限。
  • 阈值调整:根据业务场景调整利用率阈值和统计时间范围,避免误删核心业务实例。
  • 预验证:生产环境执行前,先在测试环境验证逻辑,或先标记待删除ASG,人工确认后再执行删除操作。

内容的提问来源于stack exchange,提问作者Kanika Singla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:07:14