import yaml import re class K8sYaml(): def __init__(self, image_name) -> None: self.image_name = image_name def get_yaml_file_name(self): self.yaml_file_name = re.split(r'[/:]', self.image_name)[-2] + ".yml" return self.yaml_file_name def change_image(self, yaml_location): yaml_list = [] self.get_yaml_file_name() with open(yaml_location + self.yaml_file_name, 'r+') as f: a = f.read() docs = yaml.load_all(a, Loader=yaml.FullLoader) for doc in docs: if doc.get("kind") == "Deployment": image_now = doc.get("spec").get("template").get("spec").get("containers")[0].get("image") if image_now: doc["spec"]["template"]["spec"]["containers"][0]["image"] = self.image_name yaml_list.append(doc) with open(self.yaml_file_name, "w") as f: yaml.dump_all(documents=yaml_list, stream=f, allow_unicode=True) data = """ harbor.ingeek.com/eco/eco-apms-api:develop_0413249_2301171654 harbor.ingeek.com/eco/eco-bdos:release-release-2.3.0_d92b7f3_2302011645 harbor.ingeek.com/eco/eco-damf:develop_18cf665_2302011032 harbor.ingeek.com/eco/eco-dams-api:release-release-2.3.0_bdf082a_2302011549 harbor.ingeek.com/eco/eco-daorder:develop_a3250ef_2301301659 harbor.ingeek.com/eco/eco-keyagent:release-release-2.3.0_8107e88_2302011551 harbor.ingeek.com/eco/eco-org:develop_aa43997_2211221719 harbor.ingeek.com/eco/eco-sms:release-release-2.3.0_19d5d96_2301311047 harbor.ingeek.com/eco/eco-valetadapt:release-release-2.3.1_0a50689_2301311901 harbor.ingeek.com/eco/eco-dkm:release-release-2.3.0_af52d98_2302011552 harbor.ingeek.com/eco/eco-dkm:111 """ data = data.split('\n') data = [ i for i in data if i != '' ] for i in data: print(i) if "eco-dkm" in i or "eco-cdos" in i: yaml_location = 'C:\\Users\\iuxt\\code\\eco_k8s_yml\\pre-ftms-oad\\' else: yaml_location = 'C:\\Users\\iuxt\\code\\eco_k8s_yml\\pre-valet\\eco\\' a = K8sYaml(i) a.change_image(yaml_location)