0Pricing
Linux Command Line & Bash Scripting Mastery · Lesson

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 jq wrapper for YAML; syntax differs.

Install the Go version:

  • brew install yq on macOS
  • snap install yq on 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 --version

Reading 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.0

Key read commands:

  • yq '.metadata.name' deployment.yaml — prints my-app
  • yq '.spec.replicas' deployment.yaml — prints 3
  • yq '.spec.template.spec.containers[0].image' deployment.yaml — prints my-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

  1. Filtering and Selecting JSON with jq Pipelines
  2. Transforming and Building JSON Objects with jq
  3. Consuming REST APIs with curl and jq Together
  4. Editing YAML Configuration Files with yq
← Back to Linux Command Line & Bash Scripting Mastery