嗨,我想把类似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。
到目前为止我的想法是:
# 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
发布于 2021-10-20 16:35:37
第二种方法可以工作,但以一种迂回的方式工作,因为mikefarah/yq还不支持更新多行块字面值。
使用现有构造解决此问题的一种方法是在下面完成,而不必创建临时的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上面的解决方案依赖于传递用户定义的变量作为字符串,它可以使用strenv()在yq表达式中使用。变量o的值是通过在bash中使用命令替换$(..)特性来设置的。在替换构造中,我们将块文字内容提取为YAML对象,并应用另一个过滤器来根据需要修改标记。因此,在替换结束时,o的值将设置为
image:
tag: "footag"
repository: "myrepo-image"
registry: "myregistry"上面获得的结果现在被直接设置为.spec.source.helm.values的值,这个值由inplace修改标志(-i)来应用于实际文件上的更改。
我在作者的回购中提出了一个特性请求,以提供一种更简单的方法来执行这个支持更新YAML多行字符串#974
发布于 2021-11-29 08:01:47
更新:您现在可以通过from_yaml/to_yaml运算符完成此操作,有关详细信息,请参阅这里。
yq e -i '.spec.source.helm.values |= (from_yaml | .tag = "cool" | to_yaml) argocd.yaml披露:我写了yq
https://stackoverflow.com/questions/69648216
复制相似问题