#!/usr/bin/python3
# -*- coding: utf-8 -*-
#==================================================#
#使用到的三方库PyYaml,pip install PyYaml
#用法python3 [脚本] [job-name] [file-path] [new-image] [env-name] [new-env-value]
import yaml,json,os,sys
class Change_yaml:
''' '''
def __init__(self,job_name,file_path,namespace):
self.job_name=job_name
self.file_path=file_path+"/"+job_name+"-online.yaml"
self.namespace=namespace
def get_yaml_file(self):
#通过kubectl将yaml文件输出到指定文件
command="kubectl get deployment/"+job_name+"-online"+" -n "+self.namespace+" -o yaml "+"> "+str(self.file_path)
try:
os.system(command)
result = True
except:
result = False
return result
def file_content(self):
#打开yaml文件读取
file = open(self.file_path,"r",encoding='UTF-8')
file_content = file.read()
file.close()
return file_content
def file_write(self,dict_yaml):
#写入文件
file = open(self.file_path,"w")
file.write(dict_yaml)
file.close()
def yaml_dict(self,yaml_content):
#将读取到的Yaml文件转换为字典格式
yaml_dict = yaml.load(yaml_content,Loader=yaml.FullLoader)
return yaml_dict
def change_dict_image(self,yaml_dict,new_image):
#修改镜像
yaml_dict["spec"]["template"]["spec"]["containers"][0]["image"]=new_image
#print(yaml_dict["spec"]["template"]["spec"]["containers"][0]["image"])
return yaml_dict
def change_dict_env(self,yaml_dict,env_name,new_env_value):
#修改变量
number=0
yaml_dict_env=yaml_dict["spec"]["template"]["spec"]["containers"][0]["env"]
for env in yaml_dict_env:
if env["name"] == env_name:
old_env_value = yaml_dict["spec"]["template"]["spec"]["containers"][0]["env"][number]["value"]
if old_env_value == new_env_value:
pass
else:
yaml_dict["spec"]["template"]["spec"]["containers"][0]["env"][number]["value"] = new_env_value
number+=1
return yaml_dict
def dict_yaml(self,yaml_dict):
#将dict转换为yaml文件
new_yaml_str = yaml.dump(yaml_dict)
return new_yaml_str
if __name__ == '__main__':
namespace = "apm"
job_name = sys.argv[1]
file_path = sys.argv[2]
new_image = sys.argv[3]
env_name = sys.argv[4]
new_env_value = sys.argv[5]
class_func=Change_yaml(job_name,file_path,namespace)
#拉取YAML文件
class_func.get_yaml_file()
#定义类
yaml_content = class_func.file_content()
#将YAML转换为dict
yaml_dict = class_func.yaml_dict(yaml_content)
#修改image
yaml_dict = class_func.change_dict_image(yaml_dict,new_image)
#修改ENV
yaml_dict = class_func.change_dict_env(yaml_dict,env_name,new_env_value)
#将YAML转换为dict
dict_yaml = class_func.dict_yaml(yaml_dict)
#将修改后的字符写入到文件中
class_func.file_write(dict_yaml)