Skip to content
Latchkey

yq: Append to and Index Arrays

yq indexes arrays with [n], appends with += or [+], and removes elements with del().

Adding an env var, an arg, or a volume to a list is a common manifest edit. yq offers both append (+=) and explicit-index assignment for arrays.

What it does

Arrays are indexed with [n], negative indices count from the end ([-1] is last), and .[] iterates every element. To append, use .list += ["x"] (concatenate a one-element array) or .list[+] = "x" (the explicit append-index). del(.list[n]) removes an element.

Common usage

Terminal
# append an arg to the first container
yq -i '.spec.template.spec.containers[0].args += ["--verbose"]' deploy.yaml
# append a whole env entry
yq -i '.services.web.environment[+] = "DEBUG=1"' compose.yaml
# read the last element
yq '.spec.template.spec.containers[-1].name' deploy.yaml

Array operations

ExpressionEffect
.list[0]First element
.list[-1]Last element
.list[]Iterate every element
.list += ["x"]Append (concatenate a one-item array)
.list[+] = "x"Append via the append-index
del(.list[1])Delete the element at index 1
.list | lengthNumber of elements

In CI

To add a sidecar or an extra env var before deploy: yq -i '.spec.template.spec.containers[0].env += [{"name":"LOG","value":"debug"}]' deploy.yaml. Wrap the new value in [...] so += concatenates rather than failing on a non-array.

Common errors in CI

.list += "x" (a bare string) errors or yields a wrong result because += expects an array on the right; use += ["x"]. "Error: cannot index array with 'name'" means you used a map key on a list; iterate with [] and select() first. On Python yq, append is jq-style .list + ["x"] without -i, so an in-place array edit not persisting points to the wrong yq.

Related guides

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