如何在 yq 中的特定键之后在 yaml 中插入或添加字段

How to insert or add a field in a yaml after a specific key in yq

我有一个包含以下块的 k8s yaml 文件

spec:
  replicas: 1
  strategy:
    type: Recreate

我想在 "spec:"

之后添加下面的块
selector:
  matchLabels:
    app: test-app

文件很大,有很多"spec:"个字段,所以应该在第一次匹配时添加。

最终文件内容应如下所示:

spec:
  selector:
    matchLabels:
      app: test-app
  replicas: 1
  strategy:
    type: Recreate

我使用带有正确缩进的 yq 提出了这个可行的解决方案,但它附加在文件的末尾,维护和读取类似的 100 个文件很痛苦。

yq  -i -y '.spec += {selector:{matchLabels:{app:"test-app"}}}' filename.yaml

欢迎使用 sed 或 awk 等工具回答任何​​问题。

我不熟悉yq,但我知道它支持有限JSON I/O。这是 jq 结构问题的解决方案:

.spec |= ({selector: {matchLabels: {app: "test-app"}}} + .)

或许值得一试原生 yq

示例管道(未测试):

yq r -j k8s.yaml | jq "$script" | yq r --prettyPrint

还有 these jq yamlifiers 不可救药的 Jeff Mercado。

给你

$ yq --yaml-output '.spec |= ({selector: {matchLabels: {app: "test-app"}}} + .)' </tmp/your-yaml-file.yaml 

spec:
  selector:
    matchLabels:
      app: test-app
  replicas: 1
  strategy:
    type: Recreate

由于您提到您有数百个文件并且每个文件都有许多 spec 元素,因此不清楚这是否能解决您的实际问题,但希望它能有所帮助。祝你好运!

您想要皮卡车解决方案。我建议改用推土机。
(注意:以下需要安装 Node.JS、Java-8 和命令行 Git)。

npm install -g commander@2.20.0
npm install -g @asux.org/cli-npm
export NODE_PATH=`npm root -g`
asux

以上是安装。


为了你想要的.. 创建一个包含以下行的 /tmp/batch-file.txt

## This is a comment.  No temporary files are created by this.
saveTo !ORIGINALINPUT
yaml read spec
saveTo !SAVED
useAsInput !ORIGINALINPUT
yaml delete 'spec/*'
yaml insert spec @/tmp/HugeSelectorFile.yaml
yaml insert spec !SAVED

运行命令:

asux yaml batch @/tmp/batch-file.txt -i ./YOURORIGINAL.yaml -o ./NEW.yaml

假设:
1) 您的原始 YAML 文件是 ./YOURORIGINAL.yaml
2) 你想要一个名为 ./NEW.yaml
的新文件 3) 您的 "huge selector" 文件名为 /tmp/HugeSelectorFile.yaml(参见上面 batch.txt 中倒数第二个 lime)

注意:文件名前面的“@”字符是特意设计的(因为没有那个“@”字符,这意味着您正在传递 JSON/YAML 内联 在命令行中)。

可以在 https://github.com/org-asux/org-ASUX.github.io/wiki/Welcome-to-WIKI-for-org.ASUX

找到更多内容