如何用Python或Shell将服务标签文本转为指定YAML格式?
实现服务-镜像标签文本到YAML格式的转换(Python/Shell方案)
现有一份包含服务名称与Docker镜像标签的文本文件,内容如下:
service1:d7e5d468 service2:g7e5d468 service3:h629hg09 nginx:y5227hg89 tomcat:bc1571hg189需要转换为适配CI/CD自动化的YAML格式:
service1: image: tag: d7e5d468 service2: image: tag: g7e5d468
Python实现方案
通过逐行读取文件、分割字段的方式生成目标格式,兼容性强,适合复杂场景扩展。
# 读取输入文件并生成目标YAML格式 with open('services.txt', 'r') as infile, open('output.yaml', 'w') as outfile: for line in infile: line = line.strip() if not line: continue # 按第一个冒号分割,避免标签包含冒号时出错 service_name, tag = line.split(':', 1) outfile.write(f"{service_name}:\n") outfile.write(" image:\n") outfile.write(f" tag: {tag.strip()}\n")
Shell实现方案
使用awk命令快速完成文本转换,适合CI/CD流水线中直接调用,无需额外依赖。
基础命令(处理非空行):
awk -F ':' '/./ {gsub(/^[ \t]+|[ \t]+$/, "", $2); print $1 ":", "\n image:", "\n tag: " $2}' services.txt > output.yaml
命令说明:
-F ':':指定冒号为字段分隔符/./:仅处理非空行gsub(/^[ \t]+|[ \t]+$/, "", $2):清除标签前后的空格与制表符- 按目标格式拼接内容并输出到
output.yaml
内容的提问来源于stack exchange,提问作者ANURAG parchuri
相关产品推荐
相关产品推荐

