一、安装jenkins库
pip install python-jenkins
使用用户名方式访问
import jenkins server = jenkins.Jenkins('http://10.212.82.86:8080', username='admin', password='admin') server.build_job('test')
通过token方法访问。建议
import jenkins # pip install python-jenkins class jenkinsapi: def __init__(self,server_url,user,token): self.server_url = server_url self.user = user self.token = token self.conn = jenkins.Jenkins(self.server_url, username=self.user, password=self.token)
token的获取方式
进入用户个人页面 —> 点击左边的设置,打开设置页面 —> API Token,Show Api Token
接口整理
import jenkins # pip install python-jenkins class jenkinsapi: def __init__(self,server_url,user,token): self.server_url = server_url self.user = user self.token = token self.conn = jenkins.Jenkins(self.server_url, username=self.user, password=self.token) def get_jobs(self): return [{"name":job["name"],"url":job["url"],"color":job["color"]} for job in self.conn.get_jobs()] def build_job(self,job,**kwargs): dict1 = {"version":11} # 参数话构建 dict2 = {'Status': 'Rollback', 'BUILD_ID': '26'} # 回滚 return self.conn.build_job(job,parameters=kwargs) def get_job_info(self,job): return self.conn.get_job_info(job) def get_build_info(self,job,build_number): return self.conn.get_build_info(job,build_number) def get_job_config(self,job): ''' 获取xml文件 ''' res = self.conn.get_job_config(job) print(res) def create_job(self,name,config_xml): ''' 任务名字 xml格式的字符串 ''' self.conn.create_job(name,config_xml) def update_job(self,name,config_xml): res = self.conn.reconfig_job(name,config_xml) print(res) if __name__ == '__main__': server_url = 'http://192.168.184.102:8080' user = 'root' token = '11de6a8dfff154774c85fc20b342a07cdc' conn = jenkinsapi(server_url,user,token) with open('config.xml',mode='r',encoding='utf-8') as f: data = f.read() print(data,type(data)) conn.update_job("test05",data)
https://blog.csdn.net/u013670453/article/details/114697112
http://<example.com>/job/<your-job-name>/config.xml
三、任务创建
1)自由风格的任务
任务基础模板
<?xml version='1.1' encoding='UTF-8'?> <project> <actions/> <description/> <keepDependencies>false</keepDependencies> <properties/> <scm class="hudson.scm.NullSCM"/> <canRoam>true</canRoam> <disabled>false</disabled> <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding> <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding> <triggers/> <concurrentBuild>false</concurrentBuild> <builders/> <publishers/> <buildWrappers/> </project>
代码展示
import xml.etree.ElementTree as ET
class jenkinsconfig:
def __init__(self,data):
self.data = data
def default_config(self):
tree = ET.parse("config.xml")
root=tree.getroot()
return tree,root
def description_config(self,root):
if self.data["description"]:
for description in root.iter('description'):
description.text = self.data["description"]
def builders_shell_config(self,root):
for builders in root.iter("builders"):
Shell = ET.Element('hudson.tasks.Shell')
command = ET.Element('command')
Rules = ET.Element('configuredLocalRules')
command.text = self.data["builders"]["shell"]
Shell.append(command)
Shell.append(Rules)
builders.append(Shell)
def builders_config(self,root):
if self.data["builders"]:
if "shell" in self.data["builders"]:
self.builders_shell_config(root)
def triggers_config(self,root):
if self.data["triggers"]:
for triggers in root.iter("triggers"):
timertrigger = ET.Element('hudson.triggers.TimerTrigger')
triggers.append(timertrigger)
for timertrigger in root.iter("hudson.triggers.TimerTrigger"):
spec = ET.Element('spec')
spec.text = self.data["triggers"]
timertrigger.append(spec)
def authtoken_config(self,root):
if self.data["authtoken"]:
for iter in root.iter("project"):
authtoken = ET.Element('authToken')
authtoken.text = self.data["authtoken"]
iter.append(authtoken)
def publishers_buildtrigger_config(self,root):
for publishers in root.iter("publishers"):
buildtrigger = ET.Element('hudson.tasks.BuildTrigger')
childprojects = ET.Element('childProjects')
childprojects.text = self.data["publishers"]["buildtrigger"]
threshold = ET.Element('threshold')
name = ET.Element('name')
ordinal = ET.Element('ordinal')
color = ET.Element('color')
completeBuild = ET.Element('completeBuild')
name.text = "SUCCESS"
ordinal.text = "0"
color.text = "BLUE"
completeBuild.text = "true"
threshold.append(name)
threshold.append(ordinal)
threshold.append(color)
threshold.append(completeBuild)
buildtrigger.append(childprojects)
buildtrigger.append(threshold)
publishers.append(buildtrigger)
def publishers_config(self,root):
if self.data["publishers"]:
if self.data["publishers"]["buildtrigger"]:
self.publishers_buildtrigger_config(root)
def properties_config(self,root):
if self.data["properties"]:
if "parameter" in self.data["properties"]:
if "stringparameter" in self.data["properties"]["parameter"]:
for properties in root.iter("properties"):
ParametersDefinitionProperty = ET.Element('hudson.model.ParametersDefinitionProperty')
parameterDefinitions = ET.Element('parameterDefinitions')
for StringParameter in self.data["properties"]["parameter"]["stringparameter"]:
definition = ET.Element('hudson.model.StringParameterDefinition')
name = ET.Element('name')
description = ET.Element('description')
defaultValue = ET.Element('defaultValue')
trim = ET.Element('trim')
name.text = StringParameter["name"]
defaultValue.text = StringParameter["defaultValue"]
trim.text = "false"
definition.append(name)
definition.append(description)
definition.append(defaultValue)
definition.append(trim)
parameterDefinitions.append(definition)
ParametersDefinitionProperty.append(parameterDefinitions)
properties.append(ParametersDefinitionProperty)
def writer_config(self,tree):
tree.write('a.xml')
def main(self):
tree,root = self.default_config()
self.description_config(root)
self.properties_config(root)
self.builders_config(root)
self.authtoken_config(root)
self.triggers_config(root)
self.publishers_config(root)
self.writer_config(tree)
if __name__ == '__main__':
data = {"description":"1234567789",
"builders":{"shell":"ls"},
"authtoken":"xxxxxx",
"triggers":"10 * * * *",
"publishers":{"buildtrigger":"test01"},
"properties":{"parameter":{"stringparameter":[{"name":"version","defaultValue":"1.1"},{"name":"version1","defaultValue":"1.2"}]}}
}
'''
description 描述
builders 构建
shell 执行shell
authtoken 构建触发器的远程令牌
triggers 构建触发器的定时
publishers 构建成功后的操作
buildtrigger 构建其他项目
properties 预览旁边的内容
parameter 参数
stringparameter 字符参数
'''
jen = jenkinsconfig(data)
jen.main()
2)流水线任务
任务默认模板
<flow-definition plugin="workflow-job@2.40"> <description/> <keepDependencies>false</keepDependencies> <properties/> <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.92"> <script/> <sandbox>true</sandbox> </definition> <triggers/> <disabled>false</disabled> </flow-definition>
代码展示
import xml.etree.ElementTree as ET
class jenkinsconfig:
def __init__(self,data):
self.data = data
def default_config(self):
tree = ET.parse("config.xml")
root=tree.getroot()
return tree,root
def actions_config(self,root):
for iter in root.iter("flow-definition"):
actions = ET.Element('actions')
iter.append(actions)
def description_config(self,root):
if self.data["description"]:
self.actions_config(root)
for description in root.iter('description'):
description.text = self.data["description"]
def properties_config(self,root):
if self.data["properties"]:
for properties in root.iter('properties'):
if "concurrent" in self.data["properties"]:
concurrent = ET.Element('org.jenkinsci.plugins.workflow.job.properties.DisableConcurrentBuildsJobProperty')
properties.append(concurrent)
if "triggers" in self.data["properties"]:
pipelinetriggersjob = ET.Element('org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty')
triggers = ET.Element('triggers')
timertrigger = ET.Element('hudson.triggers.TimerTrigger')
spec = ET.Element('spec')
spec.text = self.data["properties"]["triggers"]
timertrigger.append(spec)
triggers.append(timertrigger)
pipelinetriggersjob.append(triggers)
properties.append(pipelinetriggersjob)
def script_config(self,root):
if self.data["script"]:
for script in root.iter("script"):
script.text = self.data["script"]
def writer_config(self,tree):
tree.write('a.xml')
def main(self):
tree,root = self.default_config()
self.description_config(root)
self.properties_config(root)
self.script_config(root)
self.writer_config(tree)
if __name__ == '__main__':
data = {"description":"我是流水线",
"properties":{"concurrent":"0","triggers":"10 * * * *"},
"script":"pipeline { agent any stages { stage('pull') { steps { checkout([$class: 'GitSCM', branches: [[name: '*/test']], extensions: [], userRemoteConfigs: [[url: 'git@192.168.85.30:root/paicollect.git']]]) } } } }"
}
'''
description 描述
properties 预览旁边的内容
concurrent 是否运行并发构建,不传值,则允许并发
triggers 定时任务
script 流水线
'''
jen = jenkinsconfig(data)
jen.main()