Editing YAML Configuration Files with yq
Read and patch Kubernetes and CI YAML in place using yq while preserving structure and comments.
What Is yq and Why Use It for YAML?
yq is a portable command-line YAML processor, similar to how jq handles JSON. It lets you read, filter, and edit YAML files without writing a script in Python or Ruby.
There are two popular tools named yq:
- mikefarah/yq (Go) — actively maintained, supports YAML, JSON, XML, TOML. This lesson uses this version.
- kislyuk/yq (Python) — a
jqwrapper for YAML; syntax differs.
Install the Go version:
brew install yqon macOSsnap install yqon Linux- Or download the binary:
wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/local/bin/yq && chmod +x /usr/local/bin/yq
Verify: yq --version should print v4.x.x. Version 4 uses a different expression syntax than v3, so the version matters.
# Install yq (Go version) on Linux
wget -q https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 \
-O /usr/local/bin/yq
chmod +x /usr/local/bin/yq
# Confirm version
yq --versionReading Values from a Kubernetes Deployment YAML
Before editing anything, learn to read YAML fields. Given a Kubernetes Deployment, you can extract any nested value with dot-notation paths.
Example deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
namespace: production
spec:
replicas: 3
template:
spec:
containers:
- name: app
image: my-app:1.0.0Key read commands:
yq '.metadata.name' deployment.yaml— printsmy-appyq '.spec.replicas' deployment.yaml— prints3yq '.spec.template.spec.containers[0].image' deployment.yaml— printsmy-app:1.0.0
Output is plain text by default (no quotes). Add -r flag or use | yq -r if you need raw strings in scripts.
# Create a sample deployment YAML
cat > /tmp/deployment.yaml << 'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
namespace: production
spec:
replicas: 3
template:
spec:
containers:
- name: app
image: my-app:1.0.0
EOF
# Read individual fields
echo "App name: $(yq '.metadata.name' /tmp/deployment.yaml)"
echo "Replicas: $(yq '.spec.replicas' /tmp/deployment.yaml)"
echo "Image: $(yq '.spec.template.spec.containers[0].image' /tmp/deployment.yaml)"All lessons in this course
- Filtering and Selecting JSON with jq Pipelines
- Transforming and Building JSON Objects with jq
- Consuming REST APIs with curl and jq Together
- Editing YAML Configuration Files with yq