1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| import json
from remote_cmd import ssh_exec_command
def template_process(template, project_name, remote_image, port, replicas, env): kuber_file = str(template).replace("${project_name}", project_name) kuber_file = kuber_file.replace("${remote_image}", remote_image) kuber_file = kuber_file.replace("${port}", port) kuber_file = kuber_file.replace("${replicas}", str(replicas)) kuber_file = kuber_file.replace("${java_opts}", str(env)) return kuber_file
def deploy_to_k8s(global_project_info: dict, remote_user="root"): """ 部署到 k8s环境 machine 仅代表 master所在节点, replicas 用来控制实例数 env JAVA_OPTS='%s %s -Dspring.profiles.active=%s' :param global_project_info: 全局项目信息 :param remote_ip_list: :param port: :param remote_user: :return: """ java_opts = global_project_info['java_opts'] profile = global_project_info['profile'] project_name = global_project_info['project_name']
if global_project_info["skywalking"] and global_project_info["skywalking_image"]: skywalking_host = global_project_info["skywalking_host"] skywalking_java_opts = '-javaagent:agent/skywalking-agent.jar -Dskywalking.agent.service_name=' + project_name + ' -Dskywalking.collector.backend_service=' + skywalking_host else: skywalking_java_opts = "" env = "%s %s -Dspring.profiles.active=%s" % (skywalking_java_opts, java_opts, profile)
template_file = "cicd/java_k8s_template.yaml"
k8s_custom = global_project_info.get('k8s_custom') if k8s_custom is not None: with open("../" + k8s_custom, 'r') as f: template = f.read() kuber = template else: with open(template_file, 'r') as f: template = f.read() kuber = template_process(template, global_project_info["project_name"], global_project_info["remote_image"], global_project_info["expose"], global_project_info["replicas"], env)
kuber_cmd = """ source .bash_profile echo "%s" | kubectl apply -f - kubectl get po | grep -m1 %s | awk '{print $1}' | xargs -n1 -I{} kubectl delete po {} """ % (kuber, project_name) remote_user = "root" remote_ip = global_project_info["machine"] ssh_port = global_project_info.get('ssh_port') res = ssh_exec_command(remote_ip, remote_user, '', kuber_cmd,port=ssh_port) if not res: raise Exception("执行 K8s 命令失败") print(res)
if __name__ == '__main__': GLOBAL_PROJECT_INFO = 'global_project_info.json' with open(GLOBAL_PROJECT_INFO, 'r', encoding='utf-8') as f: global_project_info = json.load(f) deploy_to_k8s(global_project_info)
|