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

CloudFormation中CommaDelimitedList参数在!Sub中引用报错的解决方法

解决CloudFormation中CommaDelimitedList参数在!Sub里的引用错误

你遇到的问题很典型:CommaDelimitedList类型的参数本质是数组,而!Sub函数只能直接处理字符串类型的值,直接引用数组就会触发Fn::Sub expression does not resolve to a string错误。要解决这个问题,我们需要先把数组转换成符合配置文件格式要求的字符串,再用!Sub渲染。

具体解决方案

我们可以通过Fn::Map给数组中的每个元素添加双引号,再用Fn::Join把它们拼接成"test1", "test2"的格式,这样就能在!Sub中正常解析了。修改后的配置如下:

configure_xx:
  files:
    /etc/file.conf:
      content: !Sub |
        input {
          logs {
            log_group => [ "${!Join(\", \", !Fn::Map [ \"item\", !Sub '\"${item}\"', !Ref list ])}" ]
            access_key_id => "${logstashUserKey}"
            secret_access_key => "${logstashUserKey.SecretAccessKey}"
            region => "eu-west-1"
          }
        }

代码解释

  • !Ref list:获取到你定义的CommaDelimitedList类型参数,值为数组["test1", "test2"]
  • !Fn::Map [ "item", !Sub '\"${item}\"', !Ref list ]:遍历数组中的每个元素,给每个元素包裹双引号,得到新数组["\"test1\"", "\"test2\""]
  • !Join(\", \", ...):把处理后的数组用", "(逗号加空格)连接,最终生成字符串"test1", "test2"

这样渲染后的/etc/file.conf中,log_group这一行就会变成你需要的格式:

log_group => [ "test1", "test2" ]

简化写法(可选)

如果你习惯用CloudFormation的短函数语法,也可以写成这样:

log_group => [ "{{!Join [\", \", !Map [ item, !Sub '\"${item}\"' , !Ref list ]]}}" ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:16:20