I have a yaml
file that looks like
apiVersion: v1
kind: ConfigMap
metadata:
name: myName
namespace: default
data:
values.yaml: |
people:
- namespace: "fred"
identities:
- name: "one"
- name: "two"
- namespace: "bob"
identities:
- name: "one"
Now i want to add a third identity to Fred (name: "three"), how do I do this with the yq
command
apiVersion: v1
kind: ConfigMap
metadata:
name: myName
namespace: default
data:
values.yaml: |
people:
- namespace: "fred"
identities:
- name: "one"
- name: "two"
- name: "three"
- namespace: "bob"
identities:
- name: "one"
Traverse to .data."values.yaml"
, and update |=
it, by interpreting the YAML string using fromyaml
, then finding those .people[]
that match the given criteria using select
, adding +=
the new item {"name": "three"}
to their array, and encoding all of it again using toyaml
:
yq '.data."values.yaml" |= (
fromyaml
| (.people[] | select(.namespace == "fred")).identities += {"name": "three"}
| toyaml
)'
apiVersion: v1
kind: ConfigMap
metadata:
name: myName
namespace: default
data:
values.yaml: |
people:
- namespace: "fred"
identities:
- name: "one"
- name: "two"
- name: three
- namespace: "bob"
identities:
- name: "one"
Tested with mikefarah/yq v4.35.1