Jenkins API集成与应用实践
Jenkins Python API接口使用
官方文档参考:https://python-jenkins.readthedocs.io/en/latest/
项目库地址:https://pypi.org/project/python-jenkins/
Python版本兼容性说明
当前该库仅支持Python 3.6及以下版本。
基础应用示例
pip3 install python-jenkins
import jenkins
# Jenkins服务器连接配置
jenkins_server = jenkins.Jenkins('http://jenkins-server:8080',
username='admin',
password='your-password',
timeout=15)
# 获取当前用户信息
current_user = jenkins_server.get_whoami()
# 获取Jenkins版本信息
jenkins_version = jenkins_server.get_version()
print('欢迎 %s,您正在使用 Jenkins %s' % (current_user['fullName'], jenkins_version))
Jenkins REST API接口应用
API接口概览
Jenkins提供了丰富的RESTful API接口,可以通过以下方式访问:
# 全局API文档地址
http://${jenkins_url}/api/
# 特定任务的API接口
http://${jenkins_url}/job/${job_name}/api/
# 凭据管理API接口
http://${jenkins_url}/manage/credentials/api/
# 单个凭据的API接口
http://${jenkins_url}/manage/credentials/store/system/domain/_/credential/${credential_id}/api/
常用任务操作API
通过REST API可以执行多种Jenkins任务管理操作,如构建、禁用、启用和删除任务等。
基于REST API的共享库封装
创建API访问令牌
在Jenkins系统中创建API访问令牌,用于安全认证。
配置认证凭据
在Jenkins凭据管理中添加API令牌作为认证凭据。
凭据有效性验证示例
pipeline {
agent any
stages {
stage("任务管理") {
steps {
httpRequest authentication: 'jenkins-auth',
httpMode: 'POST',
responseHandle: 'NONE',
url: 'http://jenkins-server:8080/job/your-job-name/disable' // 禁用指定任务
}
}
}
}
Jenkinsfile与共享库集成示例
共享库实现 (jenkinsapi.groovy)
package org.devops.tools
// HTTP请求封装方法
def sendHttpRequest(requestType, requestUrl, requestBody) {
def jenkinsAddress = 'http://jenkins-server:8080/'
def response = httpRequest authentication: 'jenkins-auth',
httpMode: requestType,
consoleLogResponseBody: true,
ignoreSslErrors: true,
requestBody: requestBody,
url: "${jenkinsAddress}/${requestUrl}"
return response
}
// 创建新项目
def createNewProject(projectName) {
withCredentials([usernamePassword(credentialsId: 'jenkins-admin-cred',
passwordVariable: 'apiPassword',
usernameVariable: 'apiUser')]) {
// 从模板项目获取配置
sh """
curl -u ${apiUser}:${apiPassword} -X GET 'http://jenkins-server:8080/job/template-project/config.xml' -o project-config.xml
curl -u ${apiUser}:${apiPassword} -X POST 'http://jenkins-server:8080/createItem?name=${projectName}' -H 'Content-Type:text/xml' --data-binary @project-config.xml
"""
}
}
// 项目管理操作
def manageProject(projectName, operation) {
def operationMap = [
"disable": "disable",
"enable": "enable",
"delete": "doDelete",
"build": "build"
]
def result = sendHttpRequest('POST', "job/${projectName}/${operationMap[operation]}", '')
return result
}
Jenkinsfile示例
@Library("shared-library@main") _
def jenkinsTools = new org.devops.tools.jenkinsapi()
String targetProject = "${env.PROJECT_NAME}"
String managementAction = "${env.ACTION}"
pipeline {
agent { label "master" }
stages {
stage("项目操作") {
steps {
script {
if (managementAction == "create") {
jenkinsTools.createNewProject(targetProject)
} else {
jenkinsTools.manageProject(targetProject, managementAction)
}
}
}
}
}
}
Jenkins Core API
Jenkins Core API是基于Java的官方API接口,提供了对Jenkins核心功能的全面访问。详细文档可参考:https://javadoc.jenkins.io/index-core.html
该API适用于需要深度集成Jenkins功能的Java应用程序开发。