【发布时间】:2018-11-27 18:00:33
【问题描述】:
我有一个包含多个 yaml 块的 yaml 文件。文件可见here。
基本上,我正在尝试更新文件最后一个 yaml 块中一个图像键 (ctrl+f blockfreight/go-bftx:) 的值。但是,我想保留有关文件的所有内容(包括 cmets),除了我正在更新的一个值。
我有以下代码:
"""
Retrieves a truncated version of the latest git commit sha and updates
the go-bftx container image tag in app.yaml
"""
import sys
import ruamel.yaml
from subprocess import check_output
yaml_path = 'app.yaml'
for yaml_block in ruamel.yaml.round_trip_load_all(stream=open(yaml_path)):
pass
# parse the most recent git commit sha from command line
docker_image = 'blockfreight/go-bftx:ci-cd-' + check_output('git log -1 -- pretty=format:%h'.split()).decode()
# update go-bftx image with most recent git-commit-sha tag in the StatefulSet block
yaml_block['spec']['template']['spec']['containers'][1]['image'] = docker_image
ruamel.yaml.round_trip_dump(yaml_block, sys.stdout)
这成功编辑了值,保持 cmets 完整,但只将最终的 yaml 块发送到标准输出。
我有什么方法可以只编辑 app.yaml 中的第六个(也是最后一个)yaml 块,并保持文件的其余部分完好无损(包括 cmets)?
我尝试将上述代码中的pass 替换为将前五个yaml 发送到stdout 的if 语句,然后编辑第六个值中的值,并将其发送到stdout。我的想法是使用 bash 将所有标准输出发送到文件(例如 python app_modifier.py > app1.yaml),但这仅发送了第六个 yaml 的输出。
该代码如下所示:
for i, yaml_block in enumerate(ruamel.yaml.round_trip_load_all(stream=open(yaml_path))):
if i != 5:
ruamel.yaml.round_trip_dump(yaml_block, sys.stdout)
else:
# parse the most recent git commit sha from command line
docker_image = 'blockfreight/go-bftx:ci-cd-' + check_output('git log -1 --pretty=format:%h'.split()).decode()
# update go-bftx image with most recent git-commit-sha tag in the StatefulSet blocks
yaml_block['spec']['template']['spec']['containers'][1]['image'] = docker_image
ruamel.yaml.round_trip_dump(yaml_block, sys.stdout)
任何帮助将不胜感激!谢谢!
【问题讨论】: