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

如何使用Boto3为已有AWS Auto Scaling Group添加标签

解决Boto3给已有ASG添加标签的问题

你之前的代码报错是因为create_or_update_tags()和delete_tags()的参数规则和describe_auto_scaling_groups()不一样,这俩方法不需要单独传ASG名称列表,而是要把ASG的信息写到每个标签的字典里。

正确添加标签的代码示例

import boto3

asg_client = boto3.client("autoscaling")
asg_name = "foo-bar20220502044025104700000001"

# 定义要添加的标签,每个标签必须包含ResourceId和ResourceType
my_tags = [
    {
        'ResourceId': asg_name,
        'ResourceType': 'auto-scaling-group',
        'Key': 'Environment',
        'Value': 'Production',
        'PropagateAtLaunch': True  # 控制标签是否传播给ASG启动的EC2实例,按需设置
    },
    {
        'ResourceId': asg_name,
        'ResourceType': 'auto-scaling-group',
        'Key': 'Project',
        'Value': 'FooBar',
        'PropagateAtLaunch': False
    }
]

# 执行标签创建/更新操作
response = asg_client.create_or_update_tags(Tags=my_tags)
print("标签操作响应:", response)

关键说明

  • ResourceId:填写目标ASG的名称,就是你之前用的asg_name
  • ResourceType:固定为auto-scaling-group,明确要操作的资源类型
  • PropagateAtLaunch:设为True时,标签会自动同步到ASG后续启动的EC2实例;如果只需要给ASG本身打标签,设为False即可

删除标签的示例

如果需要删除标签,用法类似,指定要删除的标签信息即可:

# 定义要删除的标签
tags_to_delete = [
    {
        'ResourceId': asg_name,
        'ResourceType': 'auto-scaling-group',
        'Key': 'Environment',
        'Value': 'Production',  # 无值标签可省略Value字段
        'PropagateAtLaunch': True
    }
]

# 执行删除操作
response = asg_client.delete_tags(Tags=tags_to_delete)
print("删除标签响应:", response)

内容的提问来源于stack exchange,提问作者Florin Andrei

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:50:18