Skip to content
Latchkey

yq: Preserve and Strip YAML Comments

mikefarah/yq preserves comments through in-place edits and exposes operators to read, set, or remove them.

A big reason teams pick Go yq is that it keeps comments when it rewrites a file. You can also deliberately read or strip them when needed.

What it does

When yq -i edits a YAML file, mikefarah/yq retains existing comments by default, unlike most YAML libraries. The lineComment and headComment operators read or set comments; ... comments="" strips every comment recursively.

Common usage

Terminal
# edit a value; surrounding comments survive
yq -i '.version = "2.0.0"' chart.yaml
# strip all comments
yq -i '... comments=""' values.yaml
# set a line comment on a key
yq -i '.image.tag line_comment="set by CI"' values.yaml

Comment operators

OperatorWhat it does
... comments=""Remove all comments recursively
.a line_comment="x"Set the trailing comment on key a
.a head_comment="x"Set the comment above key a
.a | line_commentRead the line comment of key a
.a | head_commentRead the head comment of key a

In CI

Because comments are preserved, a pipeline can bump a single value in a heavily commented values.yaml without producing a noisy diff. If a downstream tool chokes on comments (some strict JSON-ish parsers), strip them first with ... comments="".

Common errors in CI

If an edit unexpectedly drops all comments, the most common cause is that the runner has kislyuk/yq (Python), which round-trips through JSON and discards comments entirely; Go yq keeps them. Converting to JSON also drops comments by design. A comment "reappearing" on the wrong key usually means it was attached to the node you moved or deleted.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →