TExcelTAD
Home › Automation Scripting: Bash, Python & Go › yq: Querying and Editing YAML

yq: Querying and Editing YAML

yq (Mike Farah's Go implementation, version 4) is jq for YAML. Its expression language is close to jq's, it reads and writes YAML, JSON, XML, TOML, CSV and properties files, and, most importantly for automation, it edits YAML in place while keeping comments and formatting. That makes it the standard tool for "bump the image tag in this manifest" steps in CI.

Note: There is also a Python program called yq (a jq wrapper by Andrey Kislyuk) with different syntax and flags. Check yq --version: this course uses mikefarah/yq 4.54.

Reading values

bash · try it yourself
cat > deploy.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-api
  labels:
    app: shop-api
spec:
  replicas: 2
  template:
    spec:
      containers:
        - name: api
          image: registry.example.com/shop-api:1.4.2   # bumped by CI
          ports:
            - containerPort: 8080
        - name: proxy
          image: envoyproxy/envoy:v1.36.2
YAML
echo "--- a scalar (printed raw, no quotes)"; yq '.spec.replicas' deploy.yaml
echo "--- the first container's image";     yq '.spec.template.spec.containers[0].image' deploy.yaml
echo "--- all container names";             yq '.spec.template.spec.containers[].name' deploy.yaml
echo "--- select by field";                 yq '.spec.template.spec.containers[] | select(.name == "proxy") | .image' deploy.yaml
echo "--- a subtree, as YAML";              yq '.metadata' deploy.yaml
echo "--- the same subtree, as JSON";       yq -o=json -I=0 '.metadata' deploy.yaml
echo "--- count and keys";                  yq '.spec.template.spec.containers | length' deploy.yaml; yq '.metadata | keys' deploy.yaml
--- a scalar (printed raw, no quotes)
2
--- the first container's image
registry.example.com/shop-api:1.4.2
--- all container names
api
proxy
--- select by field
envoyproxy/envoy:v1.36.2
--- a subtree, as YAML
name: shop-api
labels:
  app: shop-api
--- the same subtree, as JSON
{"name":"shop-api","labels":{"app":"shop-api"}}
--- count and keys
2
- name
- labels

Unlike jq, yq prints scalar strings without quotes by default, so tag=$(yq '.image.tag' values.yaml) needs no -r. A missing path prints null; yq -e makes that (and false) an error with exit status 1, like jq -e.

Editing in place, keeping comments

-i writes the result back to the file. Assignments (=, |=), del() and += work as in jq:

bash · try it yourself
cat > deploy.yaml <<'YAML'
# Deployment for the shop API
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-api
spec:
  replicas: 2  # scaled by HPA in prod
  template:
    spec:
      containers:
        - name: api
          image: registry.example.com/shop-api:1.4.2
          env:
            - name: LOG_LEVEL
              value: info
            - name: DEBUG_TOKEN
              value: x-123
YAML
export NEW_TAG=1.5.0
yq -i '
  (.spec.template.spec.containers[] | select(.name == "api") | .image) |= sub(":[^:]+
quot;, ":" + strenv(NEW_TAG)) | .spec.replicas = 3 | del(.spec.template.spec.containers[0].env[] | select(.name == "DEBUG_TOKEN")) | .spec.template.spec.containers[0].env += [{"name": "REGION", "value": "eu-west-1"}] ' deploy.yaml cat deploy.yaml
# Deployment for the shop API
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-api
spec:
  replicas: 3 # scaled by HPA in prod
  template:
    spec:
      containers:
        - name: api
          image: registry.example.com/shop-api:1.5.0
          env:
            - name: LOG_LEVEL
              value: info
            - name: REGION
              value: eu-west-1
  • The comments survived, including the one after replicas. That is the reason to use yq rather than a JSON round trip (yq -o=json | jq … | yq -P), which loses every comment.
  • Pass values through the environment: strenv(NEW_TAG) always gives a string, env(N) parses the value as YAML (so env(REPLICAS) with REPLICAS=3 is a number). Never splice shell variables into the expression string, for the same reasons as with jq's --arg.
  • sub(regex; replacement) rewrites only the tag part; selecting the container by name instead of by index keeps the edit correct when someone adds a sidecar in front.

Multi-document files

Expressions run once per document, so select on a field picks documents out of a manifest bundle:

bash · try it yourself
cat > all.yaml <<'YAML'
apiVersion: v1
kind: ConfigMap
metadata: {name: shop-config}
data: {LOG_LEVEL: info}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: shop-api}
spec: {replicas: 2}
---
apiVersion: v1
kind: Service
metadata: {name: shop-api}
spec: {ports: [{port: 80, targetPort: 8080}]}
YAML
echo "--- kinds";             yq -N '.kind' all.yaml
echo "--- only the Service";  yq 'select(.kind == "Service") | .spec.ports[0].port' all.yaml
echo "--- edit one document in place"
yq -i '(select(.kind == "Deployment") | .spec.replicas) = 4' all.yaml
yq -N 'select(.kind == "Deployment") | .spec' all.yaml
--- kinds
ConfigMap
Deployment
Service
--- only the Service
80
--- edit one document in place
{replicas: 4}

Merging files: base plus overrides

Combining a base config with an environment-specific file is a classic yq job. ea (eval-all) loads every file first, so the expression can see all of them; * merges deeply, with the right side winning:

bash · try it yourself
cat > base.yaml <<'YAML'
replicas: 2
image: {repository: shop-api, tag: "1.4.2"}
resources: {limits: {cpu: 500m, memory: 256Mi}}
features: [search]
YAML
cat > prod.yaml <<'YAML'
replicas: 6
resources: {limits: {memory: 1Gi}}
features: [search, recommendations]
YAML
echo "--- deep merge, arrays replaced"
yq ea '. as $f ireduce ({}; . * $f)' base.yaml prod.yaml
echo "--- arrays appended instead (*+)"
yq ea -o=json -I=0 '. as $f ireduce ({}; . *+ $f) | .features' base.yaml prod.yaml
--- deep merge, arrays replaced
replicas: 6
image:
  repository: shop-api
  tag: "1.4.2"
resources: {limits: {cpu: 500m, memory: 1Gi}}
features: [search, recommendations]
--- arrays appended instead (*+)
["search","search","recommendations"]

resources.limits.cpu came from the base and memory from prod: that is the deep merge. yq also keeps each node's style, so values written in flow style ({…}, […]) stay that way. Arrays are replaced as a whole by *; *+ appends them, which here duplicates search (add | unique if that matters). Helm values files are merged the same way, which is why this is worth knowing before the Helm & Kustomize course.

Converting formats

bash · try it yourself
printf '{"name": "shop-api", "ports": [8080, 9090], "tls": {"enabled": true}}\n' > app.json
echo "--- JSON to YAML";        yq -p=json -o=yaml app.json
echo "--- YAML to properties";  yq -p=json -o=props app.json
echo "--- a section as shell variables"; yq -p=json -o=shell '.tls' app.json
--- JSON to YAML
name: shop-api
ports:
  - 8080
  - 9090
tls:
  enabled: true
--- YAML to properties
name = shop-api
ports.0 = 8080
ports.1 = 9090
tls.enabled = true
--- a section as shell variables
enabled=true

-p sets the input format and -o the output format. -o=shell produces KEY=value lines (quoted safely) that a script can source, a quick way to turn a config section into environment variables.

Test yourself

Why prefer yq -i over yq -o=json | jq ... | yq -P to edit a manifest?

  1. jq cannot edit numbers
  2. yq -i keeps comments and formatting; the JSON round trip loses all comments
  3. yq is always faster
  4. jq cannot read files

How should a CI script pass the new tag into a yq expression?

  1. Splice it: yq ".image.tag = \"$TAG\""
  2. Export it and use strenv(TAG) in the expression
  3. Write it to a temporary YAML file first
  4. yq cannot use variables

In yq ea '. as $f ireduce ({}; . * $f)' base.yaml prod.yaml, which value wins for a key present in both files?

  1. base.yaml's
  2. prod.yaml's, because later files are merged on top
  3. Neither: yq reports a conflict
  4. It depends on alphabetical order