Python-jenkins模块之job相关操作

实验版本:python_jenkins-0.4.15

测试代码如下:

# coding: utf-8

import jenkins
import datetime

server = jenkins.Jenkins('http://localhost/jenkins', username='username', password='password')
user = server.get_whoami()
version = server.get_version()
print('Hello %s from Jenkins %s' % (user['fullName'], version))

get_version函数有个bug,需要修改site-pakcages/jenkins/__init__.py函数

添加红色部分代码:
Python-jenkins模块之job相关操作_第1张图片
#获取所有jobs,打印job name
jobs = server.get_all_jobs()  # 获取所有job,等价于server.get_jobs()
for job in jobs:
    print job['name']
# 创建job
server.create_job('empty', jenkins.EMPTY_CONFIG_XML)

print server.get_job_config("empty")  # 获取对应job的config配置信息
# 禁用和启用job
server.disable_job('empty')
server.enable_job('empty')
# 复制job
server.copy_job('empty', 'empty_copy')
server.reconfig_job('empty', jenkins.RECONFIG_XML)
# 删除job
server.delete_job('empty')
server.delete_job('empty_copy')
# build job(带参数的job)
server.build_job('empty', {'para1': 'p1', 'para2': 'q2'})
# 获取job empty的build信息
last_build_info = server.get_job_info('empty')
last_success_build_number = last_build_info['lastSuccessfulBuild']['number']
laste_build_number = last_build_info['lastBuild']['number']
laste_unsuccess_build_number = last_build_info['lastUnsuccessfulBuild']['number']
last_unstable_build = last_build_info['lastStableBuild']
builds = last_build_info['builds']  # 获取job所有的build历史记录
# 获取job指定build number的build信息
build_info = server.get_build_info('empty', 1)
started_by_user_info = build_info['actions'][1]['causes'][0]['shortDescription']
build_status = build_info['result']
build_number_display = build_info['displayName']  # 结果 #1
build_duration = build_info['duration']  # build持续时间毫秒
build_parameters = build_info['actions'][0]['parameters']  # build的参数
# job的build日期时间 dt = '2018-02-27 11:19:57'
build_time = build_info['timestamp']/1000  # build的日期timestamp,毫秒需要转化为秒
if isinstance(build_time, (int, float, long)):
    dt = datetime.datetime.fromtimestamp(build_time)
    dt = dt.strftime("%Y-%m-%d %H:%M:%S.%f")

# 查询job是否存在

try:
    server.assert_job_exists('empty2', exception_message='job %s does not exist.......')
except jenkins.JenkinsException, e:
    print e
job empty2 does not exist.......
# 重命名job name
server.rename_job('empty', 'empty2')

# 设置job的next build number
next_bn = server.get_job_info('empty2')['nextBuildNumber']
server.set_next_build_number('empty2', next_bn + 10)
 
  
set_next_build_number()方法需要安装Next Build Number插件,否则会报错 jenkins.NotFoundException: Requested item could not be found

# 停止build
server.stop_build('empty2', '13')

官方地址:http://python-jenkins.readthedocs.io/en/latest/examples.html


你可能感兴趣的:(jenkins,python)