我在文本檔案中有一個值串列,如下所示:
service-1 | a /
service-1 | b /path2/
service-2 | b /path3/
service-2 | b /path4/
我還有一個 YAML 用于每個服務,例如service-1.yaml,service-2.yaml等。每個服務都有一個入口路徑,我需要在其中放置路徑:
ingress:
instances:
- auth: a
path:
<to be filled in>
<to be filled in>
- auth: b
path:
<to be filled in>
<to be filled in>
我想在 Shell 中決議文本檔案,然后更新 YAML 中的相應欄位。我知道我可以使用 cut 決議第一部分和第二部分,例如,
echo "service-1 | a /" | cut -d "|" -f1或echo "service-1 | a /" | cut -d "|" -f2,但我如何確定 YAML 中哪個服務是哪個以及哪些路徑去哪里?任何建議表示贊賞。
uj5u.com熱心網友回復:
您可以使用 YAML 處理器kislyuk/yq來解決這個任務。以下代碼顯示了一種僅針對一個檔案的解決方案。您可以將它放在一個遍歷所有檔案的 bash 回圈中。
SERVICE='service-1' # or 'service-2'
PATHS='servicePaths.txt'
FILE_IN="$SERVICE.yaml"
FILE_OUT="$SERVICE.out.yaml"
yq -y --arg service $SERVICE --rawfile paths $PATHS '
def getPath($auth):
$paths / "\n" # split lines by "\n"
| map(. / "|" # split each line by "|"
| map(sub("^\\s ";"") | sub("\\s $";"")) # trim strings
| select(any) # remove empty array (empty lines in file servicePaths.txt)
| [.[0], (.[1] / " " | .[0], .[1])] # split auth/path by " "
| select(.[0] == $service and .[1] == $auth)) # keep only definitions where $service and $auth match
| .[0][2] // "path undefined"; # return path of first match or default if no match found
.ingress.instances |= map(.path = getPath(.auth))' "$FILE_IN" > "$FILE_OUT"
檔案service-1.out.yaml
ingress:
instances:
- auth: a
path: /
- auth: b
path: /path2/
檔案service-2.out.yaml
ingress:
instances:
- auth: a
path: path undefined
- auth: b
path: /path3/
評論
yq-i如果您想替換原始模板檔案而不是使用 $FILE_OUT,則提供檔案就地編輯選項。- 該函式
getPath($auth)從檔案中建立路徑查找,servicePaths.txt然后為$service和選擇正確的路徑$auth .ingress.instances |= map(...)最后一行更新所有服務的路徑(|=是更新操作員)- 解決方案是故障安全的:
service, auth如果沒有定義路徑servicePaths.txt則"path undefined"插入。- 如果定義了多個路徑,
servicePaths.txt則插入第一個路徑。
變化
如果對同一服務/身份驗證具有多個路徑定義是有效的,請使用以下小修改:
SERVICE='service-1' # or 'service-2'
PATHS='servicePaths.txt'
FILE_IN="$SERVICE.yaml"
FILE_OUT="$SERVICE.out.yaml"
yq -y --arg service $SERVICE --rawfile paths $PATHS '
def getPath($auth):
$paths / "\n" # split lines by "\n"
| map(. / "|" # split each line by "|"
| map(sub("^\\s ";"") | sub("\\s $";"")) # trim strings
| select(any) # remove empty array (empty lines in file servicePaths.txt)
| [.[0], (.[1] / " " | .[0], .[1])] # split auth/path by " "
| select(.[0] == $service and .[1] == $auth)) # keep only definitions where $service and $auth match
| map(.[2]); # return paths of all matches
.ingress.instances |= map(.path = getPath(.auth))' "$FILE_IN" > "$FILE_OUT"
檔案service-1.out.yaml
ingress:
instances:
- auth: a
path:
- /
- auth: b
path:
- /path2/
檔案service-2.out.yaml
ingress:
instances:
- auth: a
path: []
- auth: b
path:
- /path3/
- /path4/
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535682.html
標籤:壳yaml
