zoukankan      html  css  js  c++  java
  • 用python迁移jenkins任务

    jenkins需要迁移平台时,可以用以下脚本,该脚本内部还带了环境配置更改的代码

    #!/usr/bin/env python
    #coding=utf8
    import os
    import sys
    import getpass
    from subprocess import Popen, PIPE
    import requests
    import re
    import json
    # import xml.etree.ElementTree as ET
    import time
    
    # def convert_xml_file_to_str(path_to_config_file):
    #     tree = ET.parse(path_to_config_file)
    #     root = tree.getroot()
    #     return ET.tostring(root, encoding='utf8', method='xml').decode()
    
    dest_env="dev"
    if dest_env=='test':
        password="xxxx"
        remote_ip="xxx"
    elif dest_env=='dev':
        password = "xxxx"
        remote_ip = "xxxxx"
    # file_name='product_list.txt'
    
    # with open(file_name, 'r') as f:
    #     out = f.readlines()
    #
    # product_names = []
    # for i in out:
    #     if not i.startswith('='):
    #         product_names.append(i.strip())
    
    product_names = os.environ["job_names"]
    product_names=product_names.strip().split(',')
    server_ip='{}:8080'.format(remote_ip)
    headers={'Content-Type':'application/json;UTF-8'}
    
    
    def run_cmd(cmd, run_as=None):
        if run_as and os.name != 'nt' and run_as != getpass.getuser():
            cmd = '''su - {} -c '{}' '''.format(run_as, cmd)
        print cmd
        close_fds = os.name != 'nt'
        p = Popen(
            cmd,
            stdout=PIPE,
            stdin=PIPE,
            stderr=PIPE,
            shell=True,
            close_fds=close_fds)
        stdout, stderr = p.communicate()
        if p.returncode and stderr:
            print 'Run cmd: {} 
    Code: {}, Stderr: {}'.format(cmd, p.returncode, stderr)
        return p.returncode, stdout.strip()
    
    
    def move_jobs(job_name):
        '''移动当前环境任务'''
        global password,remote_ip
        name=job_name.strip()
        username = 'tester'
        cmd="cd /home/jenkins/jobs;sshpass -p {} rsync -av {} root@{}:/home/jenkins/jobs/".format(password,name,remote_ip)
        print(cmd)
        code,res=run_cmd(cmd)
        if code!=0:
            print(res)
            sys.exit(1)
        else:
            print('{}迁移成功'.format(name))
    
    
    def change_env(job_name):
        '''修改目的服务器环境'''
        global server_ip,headers
        username = 'test'
        password = 'xxxxxxx!'
        # job_name='xxxxxx'
        url = 'http://{}/job/{}/config.xml'.format(server_ip, job_name)
        print url
        req = requests.get(url, headers=headers, auth=(username, password))
        res=req.content
        print res
        # res = res.replace('if (setEnv =="test"){','if (setEnv == "test"){
        test_url="xxxxx"
        host_ips="xxxxx"')
        if remote_ip=='xxxx':
            res=res.replace('setEnv="dev"','setEnv="test"')
        elif remote_ip=='xxxx':
            res=res.replace('setEnv="test"','setEnv="dev"')
        with open('/tmp/config.xml','w') as f:
            f.writelines(res)
    
        res=requests.post('http://{}/job/{}/config.xml'.format(server_ip, job_name),
                          data=file('/tmp/config.xml','rb').read(),
                          auth=(username, password),headers=headers)
        if res.status_code==200:
            print('{}修改成功'.format(job_name))
        else:
            print('{}修改失败'.format(job_name))
            # print(res.content)
            # sys.exit(1)
    
    def get_run_jobs():
        '''获取目的服务器的jenkins状态,若空闲返回True'''
        global server_ip,headers,username
        username = 'test'
        password = 'xxxxx!'
        url = 'http://{}/computer/api/json'.format(server_ip)
        print url
        req = requests.get(url, headers=headers, auth=(username, password))
        res = json.loads(req.content)['computer']
        for i in res:
            if i["_class"]== "hudson.model.Hudson$MasterComputer":
                return i['idle']
    
    if __name__=='__main__':
        for job_name in product_names:
            move_jobs(job_name)
    
        #查看远程jenkins 是否有任务在执行
        while 1:
            if get_run_jobs():
                cmd='sshpass -p {} ssh -o StrictHostKeyChecking=no root@{} "service jenkins status"'.format(password,remote_ip)
                res=run_cmd(cmd)
                print res
                break
            time.sleep(20)
    
        time.sleep(100)
        for job_name in product_names:
            change_env(job_name)
    

      

  • 相关阅读:
    jdb应用 远程调试
    maven POM总结
    jvm
    jdbc取出表名 名称
    nginx配置openssl证书
    DNS A记录 CNAME NS记录等的区别
    linux文件目录类命令|--cd指令
    linux文件目录类命令--ls命令
    linux文件目录类命令--pwd命令
    linux 帮助指令
  • 原文地址:https://www.cnblogs.com/slqt/p/13631015.html
Copyright © 2011-2022 走看看