首页 > 解决方案 > 使用 yq 更新 yaml 数组

问题描述

我有以下要替换命令字段的 yaml

apiVersion: batch/v1
kind: Job
metadata:
  name: test004
spec:
  template:
    spec:
      containers:
        - name: "eee"
          image: "test"
          command: ["a", "b", "c"]

apiVersion: batch/v1
kind: Job
metadata:
  name: test004
spec:
  template:
    spec:
      containers:
        - name: "eee"
          image: "test"
          command: ["a", "b", "c", "d"]
yq  -i n --style  myfile.yaml 'spec.template.spec.containers[0].command' "["a", "b", "c","d"]"

有没有办法用 wq 来实现这一点,我尝试使用样式但没有成功,如果我将它更改为简单的字符串,它可以工作,但当我想传递完整数组时,你知道吗?

标签: yamlyq

解决方案


您可以使用字段[+]表示法在 yq v3 中附加字段。所以你的命令导致

yq --style double w -i myfile.yaml 'spec.template.spec.containers[0].command[+]' "c"

上面的命令将条目附加"c"到数组中。

或者,如果您想更新整个数组command,您可以在 v4 中进行。请注意,这会在与 OP 中显示的内容不同的行中创建数组条目。请参阅YAML 多行数组

yq e '.spec.template.spec.containers[0].command |= ["a", "b", "c","d"] | ..style="double"' yaml

请注意,yq v4 已经存在并支持非常强大的路径表达式和操作。有关说明,请参阅从 v3 升级


推荐阅读