使用客户端库时,在创建客户端时,传关键字参数useCrumb即可。如果是纯API操作需要手动获取Crumb
获取方法:
http://JENKINS_URL/crumbIssuer/api/xml
获取后通过head头传入
纯API示例
#coding=utf8
import sys
import os
import requests
import json
import time
username = ''
password =
server_ip=''
job_name=''
req = requests.get('http://{}/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)'.format(server_ip), auth=(username, password))
res=req.text
crumb=res.split(':')[-1].strip()
print crumb
headers={'Jenkins-Crumb':crumb,'Content-Type':'application/json;UTF-8'}
#查询上一次任务,如果在执行,则终止
url='http://{}/job/{}/lastBuild/api/json?pretty=true'.format(server_ip,job_name)
req = requests.post(url,headers=headers,data={}, auth=(username, password))
res=json.loads(req.text)
build_number=res['id']
status=res['building']
if status==True :
# 查询上一次任务,如果在执行,则终止
url = 'http://{}/job/{}/{}/stop/api/json?pretty=true'.format(server_ip, job_name,build_number)
req = requests.post(url, headers=headers, data={}, auth=(username, password))
time.sleep(5)
build_number=int(build_number)+1
#开始创建任务
url='http://{}/job/{}/build'.format(server_ip,job_name)
req = requests.post(url,headers=headers,data={}, auth=(username, password))
print req.text
time.sleep(8)
while 1:
try:
url='http://{}/job/{}/{}/api/json?pretty=true'.format(server_ip,job_name,build_number)
req = requests.get(url,headers=headers, auth=(username, password))
result= json.loads(req.text)['building']
if result==False:
break
except:
pass
url='http://{}/job/{}/lastBuild/api/json?pretty=true'.format(server_ip,job_name)
req = requests.post(url,headers=headers,data={}, auth=(username, password))
res=json.loads(req.text)['result']
if res=='SUCCESS':
print '安装包构建成功'
else:
print '安装包构建失败'
sys.exit(1)
客户端库示例
from jenkinsapi.jenkins import Jenkins
jenkins_url = 'http://jenkins.xxx.cn'
jenkins_user = 'admin'
jenkins_password = '可以是密码或用户token'
xml='''
<flow-definition plugin="workflow-job@2.41">
<description>测试API创建JOB</description>
<keepDependencies>false</keepDependencies>
<properties>
<com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty plugin="gitlab-plugin@1.5.20">
<gitLabConnection></gitLabConnection>
<jobCredentialId></jobCredentialId>
<useAlternativeCredential>false</useAlternativeCredential>
</com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty>
</properties>
<definition class="org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition" plugin="workflow-cps@2.92">
<scm class="hudson.plugins.git.GitSCM" plugin="git@4.7.2">
<configVersion>2</configVersion>
<userRemoteConfigs>
<hudson.plugins.git.UserRemoteConfig>
<url>https://git.kaifazhe.me/devops/jenkins-chajiu.git</url>
<credentialsId>b7a7b300-e89c-4a4c-bbc3-958a0b73135b</credentialsId>
</hudson.plugins.git.UserRemoteConfig>
</userRemoteConfigs>
<branches>
<hudson.plugins.git.BranchSpec>
<name>*/master</name>
</hudson.plugins.git.BranchSpec>
</branches>
<doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
<submoduleCfg class="empty-list"/>
<extensions/>
</scm>
<scriptPath>assets-vue-boms/jenkinsfile</scriptPath>
<lightweight>true</lightweight>
</definition>
<triggers/>
<disabled>false</disabled>
</flow-definition>
'''
# h='customHeaders: [["Jenkins-Crumb": "1df50faa6b41762ec7072d4c1dc40abdd5431248aafbac5c1b37bbfb864ee667"]]'
def creater_job(job_name):
ss = Jenkins(jenkins_url, jenkins_user, jenkins_password,timeout=10,useCrumb=True)
#copy_job_name = 'job1' # jenkins的job
#xml = ss[copy_job_name].get_config() # 获取配置文件
job = ss.create_job(job_name, xml.encode(encoding="utf-8"))
print(ss.keys())
if __name__ == '__main__':
creater_job("python-api-create-job")
创建客户端
from jenkinsapi.jenkins import Jenkins
jk = Jenkins('http://10.0.0.1:8080', username=None, password=None, timeout=10, useCrumb=True)
Jenkins 要求在 POST 请求中包含 Crumb 参数,避免 CSRF 攻击
查询 job :
job_names = jk.keys() # 返回一个包含所有 job 名字的列表
jk.get_jobs() # 返回一个可迭代对象,每次迭代返回一个二元组(job 名字,job 对象)
job = jk.get_job('test1') # 根据名字,获取指定的 job 对象,如果不存在则抛出异常
job.url # 返回 job 的 URL
jk.delete_job('test1') # 删除一个 job
job 的配置:
xml = job.get_config() # 导出 job 的 XML 配置
job = jk.create_job(jobname, xml) # 创建一个 job
job.update_config(xml) # 修改 job 的 XML 配置
job 的构建:
jk.build_job('test_job', params={'tag': 'v1.0.0'}) # 构建一个 job(按需要发送参数)
b = job.get_build(20) # 返回指定编号的 build 对象
b = job.get_last_build() # 返回最后一次构建的 build 对象
job.get_next_build_number() # 返回下一次构建的编号(如果为 1 则说明还没有构建)
b.job.name # 返回这次构建所属 job 的名字
b.get_number() # 返回这次构建的编号
b.get_params() # 返回一个字典,包含这次构建的所有参数
b.stop() # 停止构建,如果成功停止则返回 True
b.is_running() # 如果这次构建正在运行,则返回 True
b.get_status() # 返回这次构建的结果,可能是 SUCCESS、FAILURE、ABORTED 等状态,如果仍在构建则返回 None
b.get_console() # 返回这次构建的控制台 stdout
b.get_timestamp().strftime('%Y/%m/%d-%H:%M:%S') # 返回开始构建的时间
b.get_duration().total_seconds() # 返回这次构建的耗时,如果仍在构建则返回 0