Search code examples
yamlyq

yq - add into a list that has custom types


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

I have an example yaml as such, and I'd like to append Policy2 into the Policies block for all resources that has Type: AWS::Serverless::Function

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

And this ends up with:

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

Where !Ref Policy2 is single quoted. Any guidance on how I can append the policy without it being single quoted?

Thank you


Solution

  • !Ref is a tag, and not part of the string value. Set it explicitly:

    yq '
      (.Resources.[] | select(.Type=="AWS::Serverless::Function").Properties.Policies
      ) += ["Policy2" | . tag = "!Ref"]
    ' example.yaml
    
    Resources:
      MyFunction:
        Type: AWS::Serverless::Function
        Properties:
          PackageType: Image
          FunctionName: myFunction
          Policies:
            - !Ref Policy1
            - !Ref Policy2