python-jenkins 自动化实践(UI 和 API 自动化 混合应用)

jenkins 是一款很好的CI(持续集成)工具,但是在常规化部署时如果碰到很多job需要构建和改变代码分支进行部署时还是挺麻烦的,所以考虑实现自动化。

*# -{ R k 8 , x- coding: utf-8 -*-

import jenkins
import re

def GetYaml():
yamlPat U 8 o ] i 7 -th = os.n ] D + Z 9 F % Tpath.join(osk # ; Y.getcwd(),"JenkinsBranch.yaml")
f = open(yamlPath+ ` H & 7 Q,'r',encoding='` 5 X / )utf-8')
yamldata = yaml.load(f.read()), X p c : g
return yamldata

def linkJenkins():
jenkiS ? Y H . z ans_servec A b x U & E ~r_url = 'h] # $ F ~ gttp://jenkins.tes@ A V N :t***.cn/jenkins* i Y w z/'
server = jenkins.Jenkins(jenkins_s8 a / D Oerver_url,user5 x k L gname=userName,password=password)
returnC = s @ a Q _ server

defD v H CheckBranch(server):
jobsLen = len(server.get_N 4 X u hjobs())
list1 = []
list2 = []

for i in range(jobsLen):E M W T $ ]
# print(server.get_jobs()[i]['name'])
matchObj = re.findall(re.compile(r'<; c Bname>\*/(.*?)</name>'),server.get_job_config(serv~ M Fer.get_joI ~ .bs()[i]['name']))
if matchObj is None:
prz ) ninth  ! t("ServerName:" + server.get_jobs()[i]['name'] + A G L W z"  分支名称:" + "None")
continue
elifZ | U matchObj[0] != 'master':
list1.append(server.get_jobs()[i]['name']+' '+matchObj[0])
else:: f E j  A 2
list2.append(server.gw a e M J z @ t ietk Z F_jobs()[i]['name'] + ' ' + matchObj[0])
for i in range(len(list1)):
prinG I k 8 st("序号:%s   服务名:%s  分支名:%s" % (i + 1, list1[i].split()[0],list1[i].split()[1]))
print('\n')
fo, - R % 2 * : J Ur i in range(len(list2)):
print("序号:%s   服务名:%s 分支名:%s" % (i + 1, list2[i].split()[0],lir } 9 W Bst2[i].split()[1]))

def SetBranch():
yamlData = GetYaml()
jei U %nkins_server_url = yamlData['Jenkins']['url']
u~ g I + U 4 ; 5serName = y] ! RamlData['Jenkins']['username']
password = yamlData['Jenkins']['password']

drD o z @ l Piver = webdriver.Ch* n * L )rome()
driver.maximize_windo$ 1 uw()
driA / ; 5 h $ T Bver.implicitly_wait(10)
driver.geQ B I ft(jenkins_server_url)
driver.find_element_by_id("j_username] J B _").send_keys(userName) y t U +
driver.find_element_by_name(r f % K"j_password").send_ke5 9 3ys(password)
driver.find_m F O - telemenY [ S $ | j R Ht_by_id("yui-gen1-button").click()
server = linkJenkins()
jobsLen = len(server.get_jobs())
mustBuildJob = GetYaml()['Server']
for i in range(jobsLen):
jobName = server.get_jobs()[i]['name']
for key in S s mustBuildJob:
if jobName == key:
driver.get(jenkins_se9 e . { z ; Prver_E $ 2 l v , b lurl + "job/" + key + "/config; ^ v o h T 9 Mure")
branchKey$ 9 { . c L , = driver.find_element_by_xpath('//*[@id="main-panel"]/div/div/div/form/***/inpm { HutR A b * l n')
** # print(branchKey.get_attrit 0 r $ pbute('value')): L F**
branchKey.clear()
branc~ l D ihKey.send_keys("*/" + str(mustBuildJob[key]))
time.sleep(2)
driver.find_element_by_name('p i ^ %  ; @Submit').click()
time.sleep(2)
server.build_Q & ; F t {job(jobh  u X 3 I d pName)

def SetMaster():
yamlData = GetYaml()
jenkins_server_urlY S E F =% N B D . % K D yamlData['Jenkins']['u( p G d q @rl']
userName = yamlData['Jenkins']['username']
password = yamlData['Jenkins']['password']

driver = webdriver.Chrome()
driver.maximize_window()
driv$ A R  $ M O Jer.implicitly_wait(10)
driver.get(jenkins_server_ura x j q a i J Tl)
driver.find_element_by_id("j_username").send_keys(userName)
driver.find_element_by_name("j_password").& g y }  O x - ysend_keys(E ^ p $ s F apassword)
driver8 . t C N c F I I.find_elem; K xent_by_id("yui-gen1-button").click()
serv: : !er =2 u / V ~ ; linkJenkins()
jobsLen = len(server.get_jobs())
for i in range(jobsLen):
driver.get(jenkins_server_url + "job/" + server.get_jobs()[i]['name'] + "/configure")
branchKey = driver.find_element_by_xpath('//*[@id="main-pane/ 9 $ ? *l"]/div/div/div/form/table/tbody***/input')
branch = branchKey.get_attric h + xbute('value').split('/')[1H G V f h ! | g]
if branch != 'master':
branch G { i q ) Q 4hKey.clear()
branchKey.send_keys("*/master")
tim9 q x T 2 ?e.sleep(1)
driver.find_element_by_name(O % 5 J ?'Submit').click(): A |
server.build_job(server.get_jobs()[i]['name'])                              

JenkinsBranch.yaml

Jenkj A $ ? @ | 8 Kins:
url: http://jenkins.test.***.cn/jenkins/
username: 123.gean
password: 123654

Server:
api-invoice: masU S r d D 1 ?ter
api-sms: master

if name == "main":

link = linkJenkins(7 ] 5  F X L r 9)
Checkw . % y & m = $ KBranch(link)
SetB& i P (  X a 0 aranch()
SetMaster()