yq - 将 yaml 添加到 yaml 中的问题

yq - issue adding yaml into yaml

你好,我想将类似 yaml 的字符串更新为 yaml

我有以下 yaml 文件argocd.yaml

---
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  namespace: mynamespace
  name:my-app
spec:
  project: xxx
  destination:
    server: xxx
    namespace: xxx
  source:
    repoURL: xxx
    targetRevision: dev
    path: yyy
    helm:
      values: |-
        image:
          tag: "mytag"
          repository: "myrepo-image"
          registry: "myregistry"

最终我想替换标签的值。不幸的是,这是 yaml 配置中的 yaml。

到目前为止我的想法是:

  1. 将值提取到另一个 values.yaml
  2. 更新标签
  3. 用 values.yaml 评估 argocd.yaml 中的值 所以有效的是:
# get the yaml in the yaml and save as yaml
yq e .spec.source.helm.values argocd.yaml > helm_values.yaml
# replace the tag value
yq e '.image.tag=newtag' helm_values.yaml

然后我想将 helm_values.yaml 文件的内容作为字符串添加到 argocd.yaml 我尝试了以下但无法正常工作

# idea 1
###################
yq eval 'select(fileIndex==0).spec.source.helm.values =  select(fileIndex==1) | select(fileIndex==0)' argocd.yaml values.yaml

# this does not update the values but add back slashes 

values: "\nimage:\n  tag: \"mytag\"\n  repository: \"myrepo-image\"\n  registry: \"myregistry\""

# idea 2
##################
yq eval '.spec.source.helm.values = "'"$(< values.yaml)"'"' argocd.yam

here i am not getting the quite escape correctly and it fails with

Error: Parsing expression: Lexer error: could not match text starting at 2:9 failing at 2:12.
        unmatched text: "newtag"

知道如何解决这个问题,或者是否有更好的方法来替换此类文件中的值? 我正在使用来自 https://mikefarah.gitbook.io/yq

的 yq

你的第二种方法可以工作,但是是迂回的方式,因为mikefarah/yq does not support updating multi-line block literals

使用现有构造解决此问题的一种方法是执行以下操作,而无需创建临时 YAML 文件

o="$(yq e '.spec.source.helm.values' yaml | yq e '.image.tag="footag"' -)" yq e -i '.spec.source.helm.values = strenv(o)' argocd.yaml

上述解决方案依赖于 bash 中的 passing a user defined variable as a string, that can be used in the yq expression using strenv(). The value for the variable o is set by using Command substitution $(..) 功能。在替换构造中,我们将块文字内容提取为 YAML 对象,并根据需要应用另一个过滤器来修改标签。所以在替换结束时,o的值将被设置为

image:
  tag: "footag"
  repository: "myrepo-image"
  registry: "myregistry"

上面得到的结果现在直接设置为.spec.source.helm.values的值,直接将就地修改标志(-i)应用于实际文件


我在作者的回购协议中提出了一个功能请求,以提供一种更简单的方法来做到这一点Support for updating YAML multi-line strings #974

更新:您现在可以通过 from_yaml/to_yaml 运算符执行此操作,详情请参阅 here

yq e -i '.spec.source.helm.values |= (from_yaml | .tag = "cool" | to_yaml) argocd.yaml

爆料:我写了yq