kar*_*101 5 yaml jq kubernetes yq
我有一个包含以下块的 k8s yaml 文件
spec:
replicas: 1
strategy:
type: Recreate
Run Code Online (Sandbox Code Playgroud)
我想在“spec:”之后添加以下块
selector:
matchLabels:
app: test-app
Run Code Online (Sandbox Code Playgroud)
该文件很大并且有很多“spec:”字段,因此应该在第一次匹配时添加它。
最终文件内容应如下所示:
spec:
selector:
matchLabels:
app: test-app
replicas: 1
strategy:
type: Recreate
Run Code Online (Sandbox Code Playgroud)
我想出了这个工作解决方案,使用 yq 和正确的缩进,但它附加在文件末尾,维护和读取类似的 100 个文件很痛苦。
yq -i -y '.spec += {selector:{matchLabels:{app:"test-app"}}}' filename.yaml
Run Code Online (Sandbox Code Playgroud)
欢迎使用 sed 或 awk 等工具提供任何答案。
我不熟悉yq,但我知道它支持有限的JSON I/O。这是结构问题的解决方案jq:
.spec |= ({selector: {matchLabels: {app: "test-app"}}} + .)
Run Code Online (Sandbox Code Playgroud)
也许值得一试本地语言yq?
示例管道(未经测试):
yq r -j k8s.yaml | jq "$script" | yq r --prettyPrint
Run Code Online (Sandbox Code Playgroud)
还有由无可救药的 Jeff Mercado 设计的jq yamlifiers。