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.

Mike Chaliy
  • 25,801
  • 18
  • 67
  • 105

2 Answers2

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.

Inian
  • 80,270
  • 14
  • 142
  • 161
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 .
Bohdan Blyzniuk
  • 575
  • 6
  • 14