如何在CloudFormation标签键中使用两个内置函数引用其他栈输出?
AWS CloudFormation:为EKS Nodegroup添加含导入值的动态标签解决方案
问题场景
尝试为AWS::EKS::Nodegroup资源添加包含其他栈导出值的动态标签时,直接使用!Sub会触发解析错误:
Resources: Nodegroup: Type: AWS::EKS::Nodegroup Properties: Tags: firstKey: firstValue !Sub randomString-${Fn::ImportValue: ClusterName}: true
报错信息:Nested mappings are not allowed in compact mappings,原因是CloudFormation会把函数里的冒号当作键值分隔符处理。给函数加引号后,!Sub会被当作字符串而非执行;而用数组形式的!Sub会生成完整字符串,无法作为标签对象使用。
可行解决方案
方案一:兼容新版CloudFormation(2023.09.01+)
如果模板使用AWSTemplateFormatVersion: 2023-09-01或更高版本,可利用!Merge合并静态标签和动态生成的标签对象:
AWSTemplateFormatVersion: 2023-09-01 Resources: Nodegroup: Type: AWS::EKS::Nodegroup Properties: Tags: !Merge - # 静态标签集合 firstKey: firstValue env: production - # 动态生成的标签对象 !Sub '{"randomString-${ClusterName}": true, "cluster-${ClusterName}": "eks-nodegroup"}' ClusterName: !ImportValue ClusterName
!Sub生成JSON格式的字符串后,CloudFormation会自动解析为标签对象,再和静态标签合并,支持同时添加多个动态标签。
方案二:兼容所有CloudFormation版本
对于旧版模板,直接用!Join拼接动态标签键,避免冒号解析冲突:
AWSTemplateFormatVersion: 2010-09-09 Resources: Nodegroup: Type: AWS::EKS::Nodegroup Properties: Tags: firstKey: firstValue # 单个动态标签 !Join ['', ['randomString-', !ImportValue ClusterName]]: true # 添加更多动态标签 !Join ['', ['cluster-', !ImportValue ClusterName]]: "managed-nodegroup" # 继续添加静态标签 team: devops
这种写法直接通过字符串拼接生成合法的标签键,既支持动态值导入,也能自由混合静态标签。
注意事项
- 标签键需符合AWS规则:长度≤128字符,仅允许字母、数字、空格及
_ . : / = + - @符号 - 确保导入的
ClusterName值不会导致标签键违反规则
内容的提问来源于stack exchange,提问作者JeremyJR
相关产品推荐
相关产品推荐

