使用 yq 替换 yaml 文件中的字符串

Azu*_*Ice 3 bash shell json yq

我正在尝试用 yq 替换 yaml 文件中的所有子字符串。

文件:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: <SOME_NAME>
  name: <SOME_NAME>
  namespace: default
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: <SOME_NAME>
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: <SOME_NAME>
    spec:
      serviceAccountName: api
      containers:
        - image: some-docker-repo/<SOME_NAME>:latest
Run Code Online (Sandbox Code Playgroud)

现在我正在使用这样的命令:

yq e '
  .metadata.labels.app = "the-name-to-use" |
  .metadata.name = "the-name-to-use" |
  .spec.selector.matchLabels.app = "the-name-to-use" |
  .spec.template.metadata.labels.app = "the-name-to-use" |
  .spec.template.spec.containers[0].image |= sub("<SOME_NAME>", "the-name-to-use")
' template.yaml  > result.yaml
Run Code Online (Sandbox Code Playgroud)

但我确信它可以作为一句台词来完成。我尝试使用不同的变体

yq e '.[] |= sub("<SOME_NAME>", "the-name-to-use")' template.yaml  > result.yaml
Run Code Online (Sandbox Code Playgroud)

但我收到了类似的错误

Error: cannot substitute with !!map, can only substitute strings. Hint: Most often you'll want to use '|=' over '=' for this operation.
Run Code Online (Sandbox Code Playgroud)

你能建议我可能错过了重点吗?

作为一个额外的请求,如果模板文件中有 2 个替换,会是什么样子?

ex <SOME_NAME_1> 和 <SOME_NAME_2> 需要分别替换为 some_var_1 和 some_var_2。

mik*_*e.f 9

技巧是使用 '..' 匹配所有节点,然后过滤掉仅包含字符串

yq e ' (.. | select(tag == "!!str")) |= sub("<SOME_NAME>", "the-name-to-use")' template.yaml
Run Code Online (Sandbox Code Playgroud)

披露:我写了 yq