这篇文章我们将会介绍一下如果使用gitlab和jenkins进行结合,通过api动态设定gitlab的webhook,实现每次向gitlab进行push操作的时候,jenkins的job会自动被执行的效果。
试验版本
工具 |
版本 |
gitlab |
10.4.2 |
jenkins |
2.73.3 |
Jenkins设定
pipeline
创建一个jenkins的pipeline的job,job名称设定为:devops-pipeline-webhook。另外为了简单演示,具体的jenkinsfile设定如下:
node {
stage('build'){
echo 'build';
}
stage('test'){
echo 'test';
}
stage('deploy'){
echo 'deploy';
}
}
gitlab hook plugin
需要在jenkin上设定gitlab hook plugin,此plugin支持gitlab8及以后的版本。详细信息可以参看如下说明:
https://wiki.jenkins.io/display/JENKINS/Gitlab+Hook+Plugin
job设定
为了建立jenkins的job和gitlab的webhook之间的关联,所创建的jenkins的job只需要做如下设定即可:
选中 Trigger builds remotely (e.g, from scripts)
同时设定gitlab调用的token:此处设定为liumiao
而具体在gitlab设定的jenkins的URL则为:
http://192.168.163.154:32002/job/devops-pipeline-webhook/build?token=liumiao
另外如果此job如果是需要传入参数的类型,具体调用方式不是/build而换成/buildWithParameters即可
gitlab的webhook
gitlab下有system hook和web hook,web hook的增删改查在项目的setting/Integrations下进行操作,当然也可以通过上篇文章中所提到的api来实现。
[root@devops ~]
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 511 100 396 100 115 12807 3719 --:--:-- --:--:-- --:--:-- 13200
{
"id": 4,
"url": "http://192.168.163.154:32002/job/devops-pipeline-webhook/build?token=liumiao",
"created_at": "2018-02-04T04:24:50.499Z",
"push_events": true,
"tag_push_events": false,
"repository_update_events": false,
"enable_ssl_verification": false,
"project_id": 1,
"issues_events": false,
"merge_requests_events": false,
"note_events": false,
"pipeline_events": false,
"wiki_page_events": false,
"job_events": false
}
[root@devops ~]
创建之后可以通过gitlab进行结果确认
git push
做完以上设定,只要向此gitlab的project进行push操作,就会出发jenkins的job,让我们来向此project添加一个hello文件并进行push。
[root@devops ~]
Cloning into 'demodefaultprj'...
remote: Counting objects: 5, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 5 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (5/5), done.
[root@devops ~]
[root@devops demodefaultprj]
[root@devops demodefaultprj]
[root@devops demodefaultprj]
[master f8af63b] for push test
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 hello
[root@devops demodefaultprj]
Username for 'http://127.0.0.1:32001': root
Password for 'http://root@127.0.0.1:32001':
Counting objects: 4, done.
Writing objects: 100% (3/3), 237 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To http://127.0.0.1:32001/root/demodefaultprj.git
e07b882..f8af63b master -> master
Branch master set up to track remote branch master from origin.
[root@devops demodefaultprj]
jenkins结果确认
可以看到已经被自动触发执行了