python脚本批量创建job并自动添加视图

python脚本批量创建job并自动添加视图,第1张

python脚本批量创建job并自动添加视图

由于我们项目jenkinsfile和deployment.yaml都是单独分开放在git仓库上管理的,脚本实现的是通过批量创建对应的文件和job任务自动提交git仓库,并把job加入到视图里!

话不多说贴脚本:

import os
import re
import shutil
import jenkins
from colorama import init, Fore, Style

init(autoreset=True)
'''
脚本基于python3,windows环境,linux环境使用将路径变量改成linux的格式
1.批量创建流水线job需要目录和文件:jenkinsfile和deployment.yaml,在对模板文件进行替换修改
2.创建job并将其加入到视图
注意:
repo_name.txt内容格式:'job名,k8s服务名,job的description信息'

'''

#将创建修改好的文件提交到git仓库
def updata_git(dir):
    print('进入到目录:%s' % dir)
    os.chdir(dir)
    print('执行git pull拉取代码')
    os.system('git pull origin master')
    print('将代码添加到本地缓冲区')
    os.system('git add .')
    print('执行git status')
    cmd = os.popen('git status').readlines()
    if any("Changes to be committed:" in s for s in cmd):
        description = input('please input your Commit description: ')
        print('执行commit提交到远程仓库')
        os.system('git commit -m "%s"' % commit_msg)
        print('执行push上传到远程仓库')
        os.system('git push origin master')
    else:
        print('Local code not change')


#批量创建jenkinsfile和k8s发布的deployment.yaml文件
def create_many(jenkins_dir, docker_dir, src_jenkinsfile, src_deployfile):
    if not os.path.exists(jenkins_dir):
        os.makedirs(jenkins_dir)
        shutil.copy(src_jenkinsfile, jenkins_dir)
    else:
        print(Style.BRIGHT + Fore.RED + '%s 目录已存在!!!' % jenkins_dir)
    if not os.path.exists(docker_dir):
        os.makedirs(docker_dir)
        shutil.copy(src_deployfile, docker_dir)
    else:
        print(Style.BRIGHT + Fore.RED + '%s 目录已存在!!!' % docker_dir)


#将创建好的文件进行替换修改
def replace_file(file_path, old_str, new_str):
    if os.path.exists(file_path):
        with open(file_path, 'r', encoding='UTF-8') as f:
            lines = f.readlines()

        if any(old_str in s for s in lines):
            with open(file_path, 'w+', encoding='UTF-8') as f:
                for line in lines:
                    content = re.sub(old_str, new_str, line)
                    f.writelines(content)
            print(Style.BRIGHT + Fore.GREEN + '**********已成功将%s替换为:%s**********' % (old_str, new_str))
        else:
            print(Style.BRIGHT + Fore.RED + 'old_str not found,Can't replace!!!')
    else:
        print(Style.BRIGHT + Fore.RED + '%s目录文件不存在!!!' % file_path)

#创建job并把job任务添加到视图
def create_jobs(job_name, job_branch, description, view_name):
    server = jenkins.Jenkins(jenkins_url, jenkins_user, jenkins_password)
    with open(template_xml, encoding='utf-8') as f:
        xml_path = f.read()
    job_conf = xml_path.replace("${description_name}", description).replace("${project_name}", job_name).replace(
        '${branch}', job_branch)
    if not server.job_exists(job_name):
        server.create_job(job_name, job_conf)
        print(Fore.GREEN + 'Job create successful.')
        if not server.view_exists(view_name):
            print(Style.BRIGHT + Fore.GREEN + '创建视图并添加job到视图.')
            server.create_view(view_name, jenkins.EMPTY_VIEW_CONFIG_XML)
            view_config = server.get_view_config(view_name).strip()
            new_view_config = re.sub('',
                                     '%sn' % job_name,
                                     view_config)
            server.reconfig_view(view_name, new_view_config)

        else:
            print(Style.BRIGHT + Fore.GREEN + '视图已存在,添加job到视图.')
            view_config = server.get_view_config(view_name).strip()
            new_view_config = re.sub('',
                                     '%sn' % job_name,
                                     view_config)
            server.reconfig_view(view_name, new_view_config)
            # print(server.get_view_config(view_name))

    else:
        print(Style.BRIGHT + Fore.RED + 'Job already exists.')


if __name__ == "__main__":
    ##git仓库本地路径
    jenkins_local_path = 'D:git_codeJenkinsfile-manage\'
    docker_local_path = 'D:git_codedocker-deploy-manage\'


    ##jenkinfile和deployment.yaml要拷贝的模板文件路径
    src_jenkinsfile = r'E:scm_templatetemplate_cloudJenkinsfile-manageJenkinsfile'
    src_deployfile = r'E:scm_templatetemplate_clouddocker-deploy-managedeployment.yaml'
    ##jenkins登录相关信息
    jenkins_url = 'jenkins_url.com'
    jenkins_user = 'admin'
    jenkins_password = '123456'
    job_branch = 'dev'
    view_name = '视图名称'
    ##jenkins的job配置文件模板config.xml
    template_xml = "config_test.xml"
    ##项目名存放list清单文件
    list_repo = r'E:py_projectrepo_name.txt'

    with open(list_repo, encoding='utf-8') as f:
        #遍历需创建的项目名
        for i in f.readlines():
            #将list_repo文件内容分割取出
            line, new_str_repo, description = i.strip().split(',')
            # jenkinsfile和deployment.yaml的目录存放路径--dest
            jenkins_dir = jenkins_local_path  + line + '\dev'
            docker_dir = docker_local_path + line


            jenkins_file = r'%sJenkinsfile' % jenkins_dir
            deploy_file = r'%sdeployment.yaml' % docker_dir

            # 创建jenkinsfile目录和yaml目录文件
            print('开始创建%s的jenkinsfile和yaml相关目录文件......' % line)
            create_many(jenkins_dir, docker_dir, src_jenkinsfile, src_deployfile)
            # 替换jenkinsfile和deployment.yaml文件内容
            replace_file(jenkins_file, 'REPO_template', new_str_repo)
            replace_file(jenkins_file, 'DEPLOYMENT_template', line)
            replace_file(deploy_file, 'template_deployment', new_str_repo)
            # replace_file(deploy_file, '8080', '8080')

            # create_jobs(job_name, job_branch, description, view_name)job_name代表的job名,job_branch代表的job的分支,description代表名称显示,view_name代表视图名
            print('开始创建%s的job...' % line)
            create_jobs(line, job_branch, description, view_name)
            print()

        print('开始提交到git仓库......')
        updata_git(jenkins_local_path)
        updata_git(docker_local_path)
        print()

        print(Fore.GREEN + 'Execution Completed.....')

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5571825.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存