Change YAML configuration with yq

Read and update a nested YAML value with mikefarah/yq, preview the result, then write it to a disposable file.

how-to4 steps

Updated

in short

Use mikefarah/yq v4 to preview a nested assignment before applying the same expression with -i.

Use the small fixture below to check the workflow before applying it to your own project.

Tools used

Before you start

  • A Bash or Zsh terminal on Linux or macOS
  • The listed tools installed and available on PATH

Steps

  1. Step 1: Check the implementation

    Several programs use the name yq. The version output should identify mikefarah/yq and v4.

    sh
    yq --version
  2. Step 2: Create a configuration file

    This example changes only a disposable fixture.

    sh
    trmn_guide_dir="$(mktemp -d)"
    cd "$trmn_guide_dir"
    cat > app.yaml <<'EOF'
    service:
      port: 8080
      replicas: 2
    EOF
  3. Step 3: Read and preview a change

    The second command prints changed YAML without writing it.

    sh
    yq '.service.replicas' app.yaml
    yq '.service.replicas = 3' app.yaml
    output
    2
    service:
      port: 8080
      replicas: 3
  4. Step 4: Write and verify

    Use -i only after reviewing the preview.

    sh
    yq -i '.service.replicas = 3' app.yaml
    yq '.service.replicas' app.yaml
    output
    3

Further reading

[yq documentation](https://mikefarah.gitbook.io/yq)

FAQ

Why quote the expression?
Single quotes prevent the shell from interpreting expression characters before yq sees them.
Will all formatting stay identical?
Do not assume byte-for-byte preservation. Review the diff when editing a real configuration file.

related