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

如何用yq向AWS Serverless Function的Policies添加无引号!Ref Policy2

问题描述

现有如下YAML示例:

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      FunctionName: myFunction
      Policies:
        - !Ref Policy1

需求:为所有Type为AWS::Serverless::Function的资源,在其Policies块中追加!Ref Policy2。

执行以下yq命令后:

yq '(.Resources.[] | select(.Type=="AWS::Serverless::Function") | .Properties.Policies) += ["!Ref Policy2"]' example.yaml

得到的结果中,新追加的!Ref Policy2被加上了单引号:

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      FunctionName: myFunction
      Policies:
        - !Ref Policy1
        - '!Ref Policy2'

如何避免追加时出现单引号?

解决方案

出现单引号是因为你把!Ref Policy2当作普通字符串传入,yq会给包含!这类特殊符号的字符串自动添加引号,保证YAML语法合法。要让!Ref作为YAML标签而非字符串处理,需要用yq的标签节点语法来构造值。

使用以下命令即可解决:

yq '(.Resources.[] | select(.Type=="AWS::Serverless::Function") | .Properties.Policies) += [{"!Ref": "Policy2"}]' example.yaml

执行后得到的正确结果:

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      FunctionName: myFunction
      Policies:
        - !Ref Policy1
        - !Ref Policy2

这个命令通过键值对形式构造了YAML标签节点,yq会自动将其解析为无引号的!Ref Policy2格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:20:29