一、核心理解
构建 Webhook 触发器(钩子)本质是一个 HTTP 回调:开发人员向 GitLab 提交代码后,GitLab 主动推送事件到 Jenkins,触发自动构建。
常见场景:
只有在开发人员向develop分支提交代码的时候会自动触发代码构建和部署至测试环境,而向主分支提交的代码不会自动构建,需要运维人员手动部署代码到生产环境。
场景拆解:
| 分支 | 谁提交 | 触发行为 | 部署目标 |
|---|---|---|---|
develop |
开发人员 | 自动构建 + 部署 | 测试环境 |
main / master |
开发人员 | 不自动构建,运维手动点 | 生产环境 |
核心思路:webhook 对两个分支都会推送过来,靠 Jenkins 端的分支过滤规则区分------develop 放行自动跑,main 直接忽略。
触发方式选择:Generic Webhook Trigger(GWT)
- ✅ 免 CSRF(不关全局安全)
- ✅ 支持 JSONPath 提取变量 + 正则过滤分支
- ✅ 生产推荐
二、配置步骤
2.1 Jenkins 安装插件
纯文本
Generic Webhook Trigger Plugin
Pipeline: Stage View Plugin
Pipeline Graph View Plugin
Pipeline: Declarative
GitLab
Git Parameter Plug-In
#确认以上插件已安装
2.2 Jenkins 凭据准备
bash
#生成随机字符串
[root@jenkins ~]#openssl rand -hex 16
2fba1c66e5f5ab1ac17e0173a384dd07
Manage Jenkins → Credentials → System → Global → Add Credentials:
| ID | 类型 | 说明 |
|---|---|---|
gitlab-xiaoming-sshkey |
SSH Username with private key | GitLab SSH 拉代码 |
gitlab-gwt-token |
Secret Text | 2fba1c66e5f5ab1ac17e0173a384dd07 |
2.3新建 Pipeline Job
首页 → 新建Item → 名称填:pipeline-webhook-demo → 选 Pipeline → 确定
Pipeline → Definition 选 Pipeline script,粘贴:
groovy
pipeline {
agent any
triggers {
GenericTrigger(
genericVariables: [
[key: 'REF', value: '$.ref', expressionType: 'JSONPath', defaultValue: ''],
[key: 'USER', value: '$.user_name', expressionType: 'JSONPath', defaultValue: '']
],
regexpFilterText: '$REF',
regexpFilterExpression: '^refs/(heads/main|tags/.*)$',
tokenCredentialId: 'gitlab-gwt-token',
printContributedVariables: true,
printPostContent: false
)
}
options {
buildDiscarder(logRotator(numToKeepStr: '10'))
timeout(time: 5, unit: 'MINUTES')
}
stages {
stage('Checkout') {
steps {
script {
if (env.REF && env.REF.startsWith('refs/tags/')) {
def tagName = env.REF.replaceFirst('refs/tags/', '')
echo "🏷️ 检测到 tag 触发: ${tagName}"
checkout([
$class: 'GitSCM',
branches: [[name: "refs/tags/${tagName}"]],
doGenerateSubmoduleConfigurations: false,
extensions: [
[$class: 'CloneOption', noTags: false, shallow: false]
],
submoduleCfg: [],
userRemoteConfigs: [[
url: 'git@gitlab.chenchengpei.cn:devops/spring-boot-helloworld.git',
credentialsId: 'gitlab-xiaoming-sshkey'
]]
])
echo "✅ 代码拉取成功 (tag: ${tagName})"
} else {
echo "🌿 检测到分支触发: main"
git(
branch: 'main',
url: 'git@gitlab.chenchengpei.cn:devops/spring-boot-helloworld.git',
credentialsId: 'gitlab-xiaoming-sshkey'
)
echo "✅ 代码拉取成功 (branch: main)"
}
}
}
}
}
post {
always {
deleteDir()
}
}
}
保存 → 手动点一次 Build Now(激活 GWT 触发器,关键!)
2.4测试
bash
#域名解析
[root@gitlab ~]#cat /etc/hosts
10.0.0.101 gitlab.chenchengpei.cn
10.0.0.100 jenkins.chenchengpei.cn
[root@gitlab ~]#curl http://jenkins.chenchengpei.cn:8080/generic-webhook-trigger/invoke?token=2fba1c66e5f5ab1ac17e0173a384dd07 -I
HTTP/1.1 200 OK
[root@gitlab ~]#curl -X POST "http://jenkins.chenchengpei.cn:8080/generic-webhook-trigger/invoke?token=2fba1c66e5f5ab1ac17e0173a384dd07"
{"jobs":{"freestyle-webhook-demo":{"regexpFilterExpression":"","triggered":true,"resolvedVariables":{},"regexpFilterText":"","id":33,"url":"queue/item/33/"}},"message":"Triggered jobs."}[root@gitlab ~]#
"triggered":true + "message":"Triggered jobs." = GWT 成功触发了 freestyle-webhook-demo,构建已经进了队列(queue/item/33/)
#触发成功
2.5GitLab配置
bash
管理员身份登录 → 点击管理员(右上角图标)→ 设置 → 网络 → 出站请求
允许来自 webhooks 和集成对本地网络的请求:勾选(核心开关)
允许系统钩子向本地网络发送请求:勾选
强制执行 DNS 重新绑定攻击保护:勾选
保存更改
chen用户登录(群组所有者) → 点击主页(左上角小狐狸图标)→ 群组 → devops → Spring Boot Helloworld
设置 → Webhooks → 添加新的 Webhooks →
URL:http://jenkins.chenchengpei.cn:8080/generic-webhook-trigger/invoke?token=2fba1c66e5f5ab1ac17e0173a384dd07
名称L:jenkins
触发器:
标签推送事件:勾选 ,启用SSL验证:勾选
添加Webhooks
点击测试 → 标签推送事件
Hook executed successfully: HTTP 200
测试成功
2.6 看控制台输出
bash
[Pipeline] echo
✅ 代码拉取成功 (branch: main)
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] deleteDir
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // timeout
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
三、将Jenkinsfile放 GitLab里
优点:
版本可控------Jenkinsfile 的每次修改都在 Git 历史里,能回滚
代码和构建配置在一起------别人 clone 项目就能看到完整构建流程
可 review------改 Jenkinsfile 也要走 MR/PR 流程
换 Jenkins 机器零成本------重新指向仓库就行
多人协作------谁都能改,有记录
3.1在仓库根目录创建 Jenkinsfile
bash
[root@gitlab ~]#cd /data/
[root@gitlab data]#rm -rf spring-boot-helloworld/
[root@gitlab data]#git clone git@gitlab.chenchengpei.cn:devops/spring-boot-helloworld.git
[root@gitlab data]#cd spring-boot-helloworld/
[root@gitlab spring-boot-helloworld]#vim Jenkinsfile
# 粘贴 Pipeline 代码
[root@gitlab spring-boot-helloworld]#git add Jenkinsfile
[root@gitlab spring-boot-helloworld]#git commit -m "ci: add Jenkinsfile"
[root@gitlab spring-boot-helloworld]#git push origin main
3.2Jenkins Job 配置改成 from SCM
纯文本
Pipeline → Definition: Pipeline script from SCM
→ SCM: Git
→ Repository URL: git@gitlab.chenchengpei.cn:devops/spring-boot-helloworld.git
→ Credentials: gitlab-xiaoming-sshkey
→ Branch: */main
→ Script Path: Jenkinsfile
3.3保存,手动构建一次验证
四、模拟开发改版本
bash
[root@gitlab data]#cd spring-boot-helloworld/
[root@gitlab spring-boot-helloworld]#git tag
v0.1
v0.2
v0.3
v0.4
v0.5
v0.6
v1.0
v1.1
v1.2
v1.3
v1.4
v1.5
# 模拟开发改版本
[root@gitlab spring-boot-helloworld]#vim src/main/java/com/neo/controller/HelloWorldController.java
return "version v1.5\n";
改为 return "version v1.6\n";
[root@gitlab spring-boot-helloworld]#git commit -am "feat: bump version to v1.6 for GWT webhook trigger test"
[root@gitlab spring-boot-helloworld]#git push --all
[root@gitlab spring-boot-helloworld]#git tag v1.6
[root@gitlab spring-boot-helloworld]#git push --tags
4.1验证
groovy
#jenkins控制台输出
[Pipeline] echo
✅ 代码拉取成功 (tag: v1.6)
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] deleteDir
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // timeout
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
五、写在最后
本博客持续分享Linux、云计算运维实战内容,整理大量环境部署、集群搭建、故障排查干货。
如果文章对你工作与学习有所帮助,欢迎点赞、收藏 ;后续持续更新运维实操内容,点个关注不迷路,一起交流进步。