How to patch multi document yaml file on condition using yq?
Asked Answered
N

2

6

Having YAML document something like:

---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-scraping
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: allow-webhooks

I am trying to get something like

---
apiVersion: **networking.k8s.io/v1beta1**
kind: NetworkPolicy
metadata:
  name: allow-scraping
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: allow-webhooks

So basically get document, if document has kind: NetworkPolicy then patch apiVersion: networking.k8s.io/v1beta1.

Ideally one liner, ideally with yq v4, but other solutions will be helpful too.

Nestle answered 2/3, 2021 at 20:16 Comment(0)
O
13

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.

Orelie answered 3/3, 2021 at 5:54 Comment(0)
M
0

Given that other solutions will be helpful - an alternative solution would be using kustomize:

  1. Create the kustomization.yaml file:
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- network-policy.yaml
patches:
  - target:
      kind: NetworkPolicy
      group: networking.k8s.io
      version: v1
    patch: |
      - op: replace
        path: /apiVersion
        value: networking.k8s.io/v1beta1

  1. Run
kustomize build | kubectl apply -f -

or

kubectl apply -k .
Marquee answered 5/3, 2021 at 11:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.