How to patch multi document yaml file on condition using yq?
With mikefarah/yq on versions beyond 4, you could do a select
and update |=
operation on the required document
yq e 'select(.kind == "NetworkPolicy").apiVersion |= "networking.k8s.io/v1beta1"' yaml
The above works fine on yq version 4.6.0
. Use the -i
flag to replace the file in-place.
Given that other solutions will be helpful - an alternative solution would be using kustomize:
- Create the kustomization.yaml file:
apiVersion: kustomize.config.k8s.io/v1beta1kind: Kustomizationresources:- network-policy.yamlpatches: - target: kind: NetworkPolicy group: networking.k8s.io version: v1 patch: | - op: replace path: /apiVersion value: networking.k8s.io/v1beta1
- Run
kustomize build | kubectl apply -f -
or
kubectl apply -k .