yml配置文件的参数替换

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_41715077/article/details/95237171

1、应用场景

K8S 版本发布时对POD 样本yml文件中公共配置统一替换。

2、代码示例

    Python 代码

#!/usr/bin/python

#coding:utf-8

"""

"""

import sys,os

from contextlib import contextmanager

profileList = {};

def PropValue(envfile):

    with open(envfile) as profile:

        new_profile = profile.readlines();

        for line in new_profile:

            line_key = line.strip().split("=", 1)[0];

            profileList[line_key] = line.strip().split("=", 1)[1];

def EnvReplaceYaml(yamlOldfile, yamlNewfile):

    try:

        with (open(yamlOldfile), open(yamlNewfile, 'w')) as (yml_file, yml_output):

            yml_file_lines = yml_file.readlines();

            for line in yml_file_lines:

                new_line = line;

                if (new_line.find('$$PLACEHOLDER$$') > 0):

                    env_list = new_line.split(':');

                    env_name = env_list[0].strip();

                    replacement = "";

                    if env_name in profileList.keys():

                        replacement = profileList[env_name];

                    new_line = new_line.replace('$$PLACEHOLDER$$', replacement);

                yml_output.write(new_line);         

    except ( IOError) as e:

        print("Error: " + format(str(e)));

        raise;


if __name__ == "__main__":

    PropValue(sys.argv[1]);

    EnvReplaceYaml(sys.argv[2],sys.argv[3]);

    Shell 脚本代码

#!/bin/bash

# arg1 配置文件

# arg2 模板文件

# arg3 新文件

if [ $# -gt 0 ];then

  python dy.py $1 $2 $3  

else

  echo '参数错误'

fi

 

执行命令

./config.sh 参数模板文件  待替换的yml  替换后的yml

3、示例文件

参数文件:

ip=localhost
port=3306

待替换的yml:

 ip: "$$PLACEHOLDER$$"

 port: "$$PLACEHOLDER$$"

猜你喜欢

转载自blog.csdn.net/weixin_41715077/article/details/95237171