前言:
Jenkins作为众多CI/CD中的佼佼者相信大家并不陌生,在各大互联网公司广泛使用,并二次开发将jenkins的某些功能封装到了自己公司所开发的运维平台中,省去很多不必要操作提高发布效率,避免很多在发布中的出现的误操作。
简介:
由于本人最近在学习Python在百无聊赖之时写了一个基于Python-Jenkins API的自动部署脚本,该脚本满足日常常用的需求。
参考资料:
Python-Jenkins官网:https://pypi.org/project/python-jenkins/
Python-Jenkins Doc:https://python-jenkins.readthedocs.io/en/latest/api.html
Jenkins结合gitlab实现持续集成:http://www.linuxops.cc/2018/07/12/Jenkins%E7%BB%93%E5%90%88gitlab%E5%AE%9E%E7%8E%B0%E6%8C%81%E7%BB%AD%E9%9B%86%E6%88%90/ (本人所写的另一篇博文,可做搭建基础环境的参考)
实现:
Python菜鸟如有错误的地方,请联系本人~
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# author:Macro
# time:2018-08-18
# version:0.0.1
import jenkins #引入jenkins类库
import time
class Jenkins_task:
def __init__(self,jenkins_url,job_name):
self.jenkins_url = jenkins_url #jenkins网页url
self.job_name = job_name #任务名称
self.user = 'macro' #登陆jenkins网页端用户名
self.password = '123456' #登陆jenkins网页端秘密
self.jenkins_login() #执行jenkins_login函数
def jenkins_login(self): #登陆jenkins
self.server = jenkins.Jenkins(url=self.jenkins_url,username=self.user,password=self.password)
return self.server
def get_version(self): #获取用户名与版本
user = self.user
version = self.server.get_version()
print('您好%s!您当前使用版本是:%s' % (user,version))
def create_job(self,job_conf): #创建任务
try:
self.server.create_job(self.job_name,job_conf)
print('任务已创建:%s' % self.job_name)
except Exception as error:
return error
def get_job_list(self): #获取任务列表
job_list = self.server.get_jobs()
print(job_list)
def del_job(self,job_name): #删除任务
try:
self.server.delete_job(job_name)
print("该项目已删除:%s" % job_name)
except jenkins.NotFoundException as error:
return error
def build_job(self,job_name): #构建任务
try:
self.server.build_job(job_name)
print('正在构建任务%s...' % job_name)
except jenkins.JenkinsException as error:
return error
def get_build_job_status(self): #获取任务构建状态
next_build_number = self.server.get_job_info(self.job_name)['nextBuildNumber'] #获取构建任务号码,这个号码是唯一的
time.sleep(10) #睡10秒,因为有时候jenkins还没反应过来代码已经走到这了,因此会找不到该任务
get_build_console_output = self.server.get_build_console_output(self.job_name,next_build_number) #获取控制台输出
status = self.server.get_build_info(self.job_name,next_build_number)
while True:
if status != None and str(status['result']) == "SUCCESS":
print('%s构建任务已完成'% self.job_name)
return get_build_console_output
else:
if str(status['building']) == True:
continue
else:
print('Error:构建过程中发现未知错误!')
return get_build_console_output
default_xml = '''<?xml version='1.1' encoding='UTF-8'?> #该变量内容为任务配置文件
<project>
<actions/>
<description>auto-deploy</description>
<keepDependencies>false</keepDependencies>
<properties>
<com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty plugin="gitlab-plugin@1.5.10">
<gitLabConnection></gitLabConnection>
</com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty>
</properties>
<scm class="hudson.plugins.git.GitSCM" plugin="git@3.9.1">
<configVersion>2</configVersion>
<userRemoteConfigs>
<hudson.plugins.git.UserRemoteConfig>
<url>git@172.16.47.227:root/auto-deploy.git</url>
<credentialsId>2abd9cc6-2dc8-4da6-93c0-5fe133cf28ac</credentialsId>
</hudson.plugins.git.UserRemoteConfig>
</userRemoteConfigs>
<branches>
<hudson.plugins.git.BranchSpec>
<name>*/master</name>
</hudson.plugins.git.BranchSpec>
</branches>
<doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
<submoduleCfg class="list"/>
<extensions/>
</scm>
<canRoam>true</canRoam>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers>
<com.dabsquared.gitlabjenkins.GitLabPushTrigger plugin="gitlab-plugin@1.5.10">
<spec></spec>
<triggerOnPush>true</triggerOnPush>
<triggerOnMergeRequest>true</triggerOnMergeRequest>
<triggerOnPipelineEvent>false</triggerOnPipelineEvent>
<triggerOnAcceptedMergeRequest>false</triggerOnAcceptedMergeRequest>
<triggerOnClosedMergeRequest>false</triggerOnClosedMergeRequest>
<triggerOnApprovedMergeRequest>true</triggerOnApprovedMergeRequest>
<triggerOpenMergeRequestOnPush>never</triggerOpenMergeRequestOnPush>
<triggerOnNoteRequest>true</triggerOnNoteRequest>
<noteRegex>Jenkins please retry a build</noteRegex>
<ciSkip>true</ciSkip>
<skipWorkInProgressMergeRequest>true</skipWorkInProgressMergeRequest>
<setBuildDescription>true</setBuildDescription>
<branchFilterType>All</branchFilterType>
<includeBranchesSpec></includeBranchesSpec>
<excludeBranchesSpec></excludeBranchesSpec>
<sourceBranchRegex></sourceBranchRegex>
<targetBranchRegex></targetBranchRegex>
<secretToken>{AQAAABAAAAAwAwXZPpnSrZAm6QjiN241dhz5+iqr+nUSZ7u1aDL0N+5BEgE7MpcMMiMSohtLb1gJNLH4ljOKQrBFFTEcCQO8Xw==}</secretToken>
<pendingBuildName></pendingBuildName>
<cancelPendingBuildsOnUpdate>false</cancelPendingBuildsOnUpdate>
</com.dabsquared.gitlabjenkins.GitLabPushTrigger>
</triggers>
<concurrentBuild>false</concurrentBuild>
<builders>
<hudson.tasks.Shell>
<command></command>
</hudson.tasks.Shell>
</builders>
<publishers/>
<buildWrappers/>
</project>'''
server = Jenkins_task('http://172.16.47.228:8080','auto-deploy')
server.get_version()
server.create_job(default_xml)
server.build_job('auto-deploy')
print(server.get_build_job_status())
server.del_job('auto-deploy')
执行结果:
您好macro!您当前使用版本是:2.138.2
正在构建任务auto-deploy...
auto-deploy构建任务已完成
由用户 unknown or anonymous 启动
构建中 在工作空间 /var/lib/jenkins/workspace/auto-deploy 中
> git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url git@172.16.47.227:root/auto-deploy.git # timeout=10
Fetching upstream changes from git@172.16.47.227:root/auto-deploy.git
> git --version # timeout=10
using GIT_SSH to set credentials
> git fetch --tags --progress git@172.16.47.227:root/auto-deploy.git +refs/heads/*:refs/remotes/origin/*
> git rev-parse refs/remotes/origin/master^{commit} # timeout=10
> git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision 6a70ece6179a2d97f20cac813e9d987602c5e5b6 (refs/remotes/origin/master)
> git config core.sparsecheckout # timeout=10
> git checkout -f 6a70ece6179a2d97f20cac813e9d987602c5e5b6
Commit message: "Add new file"
> git rev-list --no-walk 6a70ece6179a2d97f20cac813e9d987602c5e5b6 # timeout=10
[auto-deploy] $ /bin/sh -xe /tmp/jenkins2672158772340840607.sh
Finished: SUCCESS
auto-deploy构建任务已完成