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

如何在CloudFormation中输出EC2实例的Tags标签?

解决CloudFormation输出EC2实例Tags的问题

CloudFormation中AWS::EC2::Instance资源不支持通过Fn::GetAtt获取Tags属性,直接使用Fn::GetAtt [Ec2Instance, Tags]会触发错误:Template error: resource Ec2Instance does not support attribute type Tags in Fn::GetAtt。以下是两种可行的解决方法:

方案1:复用模板内定义的标签原始值

既然标签是你在模板中明确配置的,最直接的方式就是在Outputs中直接复用这些定义好的标签内容:

输出完整标签数组

"Outputs": {
  "Ec2InstanceTags": {
    "Description": "EC2实例的所有标签",
    "Value": {
      "Tags": [
        {   
          "Key": "Name",
          "Value": "Sample-TOPOLOGY"
        },
        {   
          "Key": "Resources",
          "Value": "r0"
        }
      ]
    }
  }
}

如果标签值是通过Ref或Fn::GetAtt引用参数/其他资源的,直接复用对应的引用逻辑即可,比如标签值是{"Ref": "InstanceNameParam"},就把Output里的Value换成这个引用。

输出单个标签的值

如果只需要输出某一个标签的内容,直接提取对应值即可:

"Outputs": {
  "Ec2InstanceNameTag": {
    "Description": "EC2实例的Name标签",
    "Value": "Sample-TOPOLOGY"
  },
  "Ec2InstanceResourcesTag": {
    "Description": "EC2实例的Resources标签",
    "Value": "r0"
  }
}

方案2:用自定义资源获取动态标签(适合非模板定义的标签)

如果标签是实例创建后动态添加的(不是模板里预先定义的),可以通过自定义资源调用EC2 API获取标签:

  1. 创建Lambda函数:编写一个处理自定义资源请求的Lambda函数,调用EC2的DescribeTags接口获取实例标签:
import boto3
import json

def lambda_handler(event, context):
    ec2_client = boto3.client('ec2')
    instance_id = event['ResourceProperties']['InstanceId']
    
    tag_response = ec2_client.describe_tags(
        Filters=[{'Name': 'resource-id', 'Values': [instance_id]}]
    )
    
    return {
        'Status': 'SUCCESS',
        'PhysicalResourceId': instance_id,
        'Data': {'Tags': tag_response['Tags']}
    }
  1. 在模板中定义自定义资源:
"GetInstanceTagsCustomResource": {
  "Type": "AWS::CloudFormation::CustomResource",
  "Properties": {
    "ServiceToken": "arn:aws:lambda:你的区域:你的账号ID:function:你的Lambda函数名",
    "InstanceId": {"Ref": "Ec2Instance"}
  },
  "DependsOn": "Ec2Instance"
}
  1. 在Outputs中获取标签:
"Outputs": {
  "Ec2InstanceTags": {
    "Description": "EC2实例的所有标签",
    "Value": {"Fn::GetAtt": ["GetInstanceTagsCustomResource", "Tags"]}
  }
}

内容的提问来源于stack exchange,提问作者Manas Pal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:53:14