Search code examples
yamlyq

Replace an empty map with map data from a variable in yq


Using mikefarah/yq (4.25.3) I am trying to replace an empty map in a yaml file with a map stored in a string.

This is the map data:

RESOURCES=$(cat <<EOF
limits:
  cpu: 4000m
  memory: 3600Mi
requests:
  cpu: 500m
  memory: 900Mi
EOF
)

And this is what I am trying to execute:

yq -i ".cluster.resources = \"${RESOURCES}\"" values.yaml

As a result I get a multiline string (instead of a map):

resources: |-
    limits:
      cpu: 4000m
      memory: 3600Mi
    requests:
      cpu: 500m
      memory: 900Mi

How do I insert a map instead?

resources:
  limits:
    cpu: 4000m
    memory: 3600Mi
  requests:
    cpu: 500m
    memory: 900Mi

Solution

  • Use the env() operator to load environment variable into yq:

    RESOURCES=$(cat <<EOF
    limits:
      cpu: 4000m
      memory: 3600Mi
    requests:
      cpu: 500m
      memory: 900Mi
    EOF
    )  yq --null-input ".cluster.resources = env(RESOURCES)"
    

    Will produce:

    cluster:
      resources:
        limits:
          cpu: 4000m
          memory: 3600Mi
        requests:
          cpu: 500m
          memory: 900Mi