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. Checkyq --version: this course usesmikefarah/yq4.54.
Reading values
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:
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 (soenv(REPLICAS)withREPLICAS=3is 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:
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:
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
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?
- jq cannot edit numbers
- yq -i keeps comments and formatting; the JSON round trip loses all comments
- yq is always faster
- jq cannot read files
How should a CI script pass the new tag into a yq expression?
- Splice it:
yq ".image.tag = \"$TAG\"" - Export it and use
strenv(TAG)in the expression - Write it to a temporary YAML file first
- 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?
- base.yaml's
- prod.yaml's, because later files are merged on top
- Neither: yq reports a conflict
- It depends on alphabetical order