嗨,我想將類似 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。
到目前為止我的想法是:
- 將值提取到另一個 values.yaml 中
- 更新標簽
- 使用 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
uj5u.com熱心網友回復:
你的第二個方法可以作業,但以一種迂回的方式,因為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
上面的解決方案依賴于將用戶定義的變數作為字串傳遞,可以在 yq 運算式中使用strenv(). 變數的值o是通過使用bash 中的命令替換 $(..)功能設定的。在替換結構中,我們將塊文字內容提取為 YAML 物件,并根據需要應用另一個過濾器來修改標簽。所以在替換結束時,的值o將被設定為
image:
tag: "footag"
repository: "myrepo-image"
registry: "myregistry"
上面獲得的結果現在.spec.source.helm.values直接設定為-i將更改應用于實際檔案的就地修改標志 ( )的值
我在作者的 repo 中提出了一個功能請求,以提供一種更簡單的方法來執行此操作支持更新 YAML 多行字串 #974
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331131.html
