首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >yq -在yaml中添加yaml

yq -在yaml中添加yaml
EN

Stack Overflow用户
提问于 2021-10-20 14:47:41
回答 2查看 733关注 0票数 4

嗨,我想把类似yaml的字符串更新成yaml

我确实有以下yaml文件argocd.yaml

代码语言:javascript
复制
---
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. 使用argocd.yaml对values.yaml中的值进行评估,因此所起作用的是:
代码语言:javascript
复制
# 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中,我尝试了如下,但我无法使它工作

代码语言:javascript
复制
# 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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-10-20 16:35:37

第二种方法可以工作,但以一种迂回的方式工作,因为mikefarah/yq还不支持更新多行块字面值

使用现有构造解决此问题的一种方法是在下面完成,而不必创建临时的YAML文件。

代码语言:javascript
复制
o="$(yq e '.spec.source.helm.values' yaml | yq e '.image.tag="footag"' -)" yq e -i '.spec.source.helm.values = strenv(o)' argocd.yaml

上面的解决方案依赖于传递用户定义的变量作为字符串,它可以使用strenv()在yq表达式中使用。变量o的值是通过在bash中使用命令替换$(..)特性来设置的。在替换构造中,我们将块文字内容提取为YAML对象,并应用另一个过滤器来根据需要修改标记。因此,在替换结束时,o的值将设置为

代码语言:javascript
复制
image:
  tag: "footag"
  repository: "myrepo-image"
  registry: "myregistry"

上面获得的结果现在被直接设置为.spec.source.helm.values的值,这个值由inplace修改标志(-i)来应用于实际文件上的更改。

我在作者的回购中提出了一个特性请求,以提供一种更简单的方法来执行这个支持更新YAML多行字符串#974

票数 3
EN

Stack Overflow用户

发布于 2021-11-29 08:01:47

更新:您现在可以通过from_yaml/to_yaml运算符完成此操作,有关详细信息,请参阅这里

代码语言:javascript
复制
yq e -i '.spec.source.helm.values |= (from_yaml | .tag = "cool" | to_yaml) argocd.yaml

披露:我写了yq

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69648216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档