Reputation: 254
I am trying to add namespace to a multi document kubernetes yaml file if it doesn't exist but if the namespace field already exists don't update it using yq but i can't seem to get it to work. Is this possible?
e.g.
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: serviceaccount1
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: serviceaccount2
namespace: namespace2
should end up something like this:
apiVersion: v1
kind: ServiceAccount
metadata:
name: serviceaccount1
namespace: namespace1
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: serviceaccount2
namespace: namespace2
UPDATE:
After successfully updating the yaml file thanks to:
https://stackoverflow.com/a/74736018/16126608
I am getting the namespace populated however due to the fact my yaml file was produced as an output of a helm template I am seeing the following issue where an empty document is having {} added as a result of the yq command, e.g.
---
# Source: path/to/chart/templates/configmap.yaml
---
# Source: ppath/to/chart/templates/network-policy.yaml
---
Is coming out like this afterwards:
---
# Source: path/to/chart/templates/configmap.yaml
---
{}
# Source: path/to/chart/templates/network-policy.yaml
---
{}
Is it possible to have yq to not add the {} and ignore the empty documents?
I am using mikefarah/yq
Upvotes: 0
Views: 1312
Reputation: 36033
You can use has
to check the existence of a field, and not
to negate, then select
it and add the new field.
Which implementation of yq
are you using?
Using kislyuk/yq:
yq -y 'select(.metadata | has("namespace") | not).metadata.namespace = "namespace1"'
Using mikefarah/yq:
yq 'select(.metadata | has("namespace") | not) |= .metadata.namespace = "namespace1"'
Upvotes: 2