python实现Jenkins版本号迭代
背景:
在持续集成过程中每天可能编译多个版本,这些版本的版本号需要按照规定的格式进行迭代,可以通过python脚本获取Jenkins上一次编译成功的状态来定义当前编译的版本号。
实现步骤:
1、安装Jenkins插件inject environment variables
2、使用python脚本将生成的版本号写入一个临时文件中
3、使用inject environment variables插件读取版本号作为环境变量
代码实现:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, io, sys, requests, subprocess, json, re
from datetime import datetime
from subprocess import Popen, PIPE, call, check_call
if __name__ == "__main__":
dt = datetime.now()
year = dt.strftime('%y')
unix_week = int(dt.strftime('%W')) + 1
week = str(unix_week)
day = dt.strftime('%w')
r = requests.get('http://localhost:8080/job/Jenkins_api_test/lastSuccessfulBuild/api/json?', auth=('username', 'password'))
if r.status_code == requests.codes.ok:
result = json.loads(r.text)
print('result:', result)
if result['description'] != 'null':
lastBuildNumber = result['description']
print('lastBuildNumber:', lastBuildNumber)
else:
lastBuildNumber = 'None'
print('lastBuildNumber is empty!!!')
if lastBuildNumber:
buildWord = lastBuildNumber[-1:]
lastBuildDigital = lastBuildNumber[:-1][2:]
newbuildWord = chr(ord(buildWord)+1)
nowTime = year + week + day
if lastBuildDigital == nowTime:
BUILD_NUMBER = 'DB' + nowTime + newbuildWord
else:
BUILD_NUMBER = 'DB' + nowTime + 'A'
else:
print('count the BUILD_NUMBER directly!')
BUILD_NUMBER = 'DB' + year + week + day + 'A'
with open('BUILD_NUMBER.property', 'wt') as f:
f.write('BUILD_NUMBER=' + BUILD_NUMBER)
print('BUILD_NUMBER:' + BUILD_NUMBER)
读取成功后这个参数就可以作为后续脚本的环境变量:
实现效果:
当然也可以把字母迭代修改为按数字迭代,以需求为准。