如何通过bash脚本添加对象到yaml



我有大约200个值。yaml文件在多个目录,我需要纠正,如果它是必要的。循环查找文件不是问题,而是如何使用bash脚本编辑/更新文件而不使用yq。

所以bash脚本需要检查是否值。Yaml文件包含数组:容器,如果有,请添加对象imageprefix: "imagename以下。然而有时价值。在容器部分已经添加了这样的对象,必须跳过它,并且不要重复。

我的yaml文件看起来像

service:
path: /
ports:
- port: 6055
containers:
container1:
name: service
org: "company:"
imagename: thirdparty-service
tagprefix: "-"
volumes:
- name: pod-logs
emptyDir: {}
envMap:
env:
N_PERROUTE: 20
NUM_STREAM_THREADS_CONFIG: 10
NUM_STREAM_T

输出
service:
path: /
ports:
- port: 6055
containers:
container1:
name: service
org: "company:"
imagename: thirdparty-service
imageprefix: ""
tagprefix: "-"
periodSeconds: 30
volumes:
- name: pod-logs
emptyDir: {}
envMap:
env:
N_PERROUTE: 20
NUM_STREAM_THREADS_CONFIG: 10
NUM_STREAM_T

yq实用程序就是为了这个目的而存在的:

yq '.containers.container1.imagename="thirdparty-service" | .containers.container1.periodSeconds=30' input.yml

更多语法,更少输入:

yq '.containers.* |= (.imagename="thirdparty-service" | .periodSeconds=30)' input.yml

您可以使用awk:

script.awk

/tagprefix: "-"/ {
printf "%sn      periodSeconds: 30n", $0
next
}
/imagename: thirdparty-service/ {
printf "%sn    imageprefix: ""n", $0
next
}
{ print }
  • 假设您的输入存储在文件input.yml
  • 像这样使用:awk -f script.awk input.yml
  • 正如在评论中提到的,在python等语言中使用专用的yaml库更加灵活。
  • 这个解决方案是超级特定于你的yaml格式。
  • 交货。如果你有两次行tagprefix: "-",它将添加两次周期秒行。此解决方案不验证yaml层次结构。
  • 但是它可以用于您要求的特定目的。

Bash + sed:

if grep -q '^containers:' input.yml
then
sed -i '/imagename:/a     imageprefix: ""' input.yml
fi