简体   繁体   English

如何在使用 yq 的条件下修补多文档 yaml 文件?

[英]How to patch multi document yaml file on condition using yq?

Having YAML document something like:拥有 YAML 文件如下:

---
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 .所以基本上得到文件,如果文件有kind: NetworkPolicy然后补丁apiVersion: networking.k8s.io/v1beta1

Ideally one liner, ideally with yq v4, but other solutions will be helpful too.理想情况下一个班轮,理想情况下使用 yq v4,但其他解决方案也会有所帮助。

With mikefarah/yq on versions beyond 4, you could do a select and update |= operation on the required document在超过 4 的版本上使用mikefarah/yq ,您可以执行select并更新|=对所需文档的操作

yq e 'select(.kind == "NetworkPolicy").apiVersion |= "networking.k8s.io/v1beta1"' yaml

The above works fine on yq version 4.6.0 .以上在yq version 4.6.0上运行良好。 Use the -i flag to replace the file in-place.使用-i标志就地替换文件。

Given that other solutions will be helpful - an alternative solution would be using kustomize :鉴于其他解决方案会有所帮助 - 另一种解决方案是使用kustomize

  1. Create the kustomization.yaml file:创建 kustomization.yaml 文件:
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 .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM