HTTP Request插件

在做持续集成的过程中,项目的代码管理基本上采用的就是gitlab。在进行集成流水线的过程中需要跟gitlab做一些交互。
例如:

  • 将构建状态返回给gitlab。
  • 通过流水线自动创建gitlab标签。
  • 获取gitlab代码库中的配置文件等等

在Jenkins插件管理安装插件 “HTTP Request”,然后在“流水线语法”中生成Jenkinsfile。

主要填写的信息:

  • 接口地址
  • 请求方式
  • 数据接收与返回格式
  • 接口认证信息(可以使用用户密码/用户token认证)

image.png

注意:如果需要认证,需要提前在jenkins中创建gitlab用户的凭据。

httpRequest acceptType: 'APPLICATION_JSON_UTF8', authentication: '24982560-17fc-4589-819b-bc5bea89da77', contentType: 'APPLICATION_JSON_UTF8', responseHandle: 'NONE', url: 'http://gitlab.demo.com/api/v4/xxxx'

package org.demo<br />def HttpReq(reqUrl,reqMode,reqBody)
{ response = httpRequest acceptType: 'APPLICATION_JSON_UTF8',
authentication: '24982560-17fc-4589-819b-bc5bea89da77',
contentType: 'APPLICATION_JSON_UTF8',
url: 'http://gitlab.demo.com/api/v4/xxxx',
requestBody: """{"aa":"bb","cc":"dd"}"""
response = readJSON text: "${response.content}"
return response}

常用的gitlabAPI整理

Gitlab 接口文档, 分为ce 和ee 。 例如ce= https://docs.gitlab.com/ce/api/

  • Group管理(获取所有项目)
  • Project管理(项目ID)
  • branch管理(新建/过滤)
  • Tag管理(创建标签)
  • Pipeline管理(运行/成功/失败)
  • Repofile 管理(获取/创建/删除)
  • Commit管理(获取)
  • MergeRequest管理(创建)

Gitlab Hook插件

1. 安装插件

jenkins系统管理下的插件管理,在线安装Gitlab Hook Plugin和Gitlab Plugin这两个插件

2. jenkins job配置

创建pipeline时, 勾选”Build when a change is pushed to GitLab”. 记住后面的GitLab CI Service URL 后面要填在gitlab的webhooks中; 同时点击“高级”,生成 “Secret token“

jenkins-gitlab 集成 - 图2

3. gitlab webhook 配置

在链接那里输入之前jenkins上提供的webhook url 以及“Secret token“,编辑完后保存

jenkins-gitlab 集成 - 图3

点击测试,如果返回200,那就成功了,去jenkins看看有没有自动构建的记录
jenkins-gitlab 集成 - 图4

jenkins build结果反馈给gitlab

  1. pipeline {
  2. agent any
  3. options {
  4. gitLabConnection('Your GitLab Connection')
  5. }
  6. stages {
  7. stage('build') {
  8. steps {
  9. updateGitlabCommitStatus name: 'build', state: 'running'
  10. hogehoge
  11. }
  12. }
  13. }
  14. post {
  15. success {
  16. updateGitlabCommitStatus name: 'build', state: 'success'
  17. }
  18. failure {
  19. updateGitlabCommitStatus name: 'build', state: 'failed'
  20. }
  21. }
  22. }
  • gitLabConnection 是和GitLab接续的名称。根据用户的权限,可以在View Configuration > General > GitLab
  • Connection 处看到接续的情报。GitLab名称的设定是在jenkins管理>系统设定>Gitlab当中设置详细的gitlab url和token
  • updateGitlabCommitStatus
    • name: build 名称
    • state: pending, running, canceled, success, failed