gitlab推送代码触发jenkins构建

发布时间 2023-04-03 14:32:38作者: 怀里的懒猫

预期:推送devloop或者master分支的代码, 自动执行jenkins 发布测试环境

  1. 首先,jenkins中需要安装如下插件

  2. 打开一个任务配置,构建触发器中勾选"Build when a change is pushed to GitLab."并过滤指定分支, 这里需要记下GitLab webhook URL一会儿配置到gitlab上

3.gitlab中添加配置

4.点击测试 ok

如果提示403,一般描述为Error 403 anonymous is missing the Job/Build Permission
解决方法:
系统管理-->系统设置-->去掉 Enable authentication for '/project' end-point

此时已经可以正常触发了;

  1. pipeline配置发布时使用传输过来的分支
def createVersion() {
    // 定义一个版本号作为当次构建的版本,输出结果 年月日_构建ID 
    return new Date().format('yyyyMMdd') + "_${env.BUILD_ID}"
}
         if(env.gitlabBranch != null) {  //如果gitlab自动构建传过来的分支参数不为空
           env.branch = env.gitlabBranch   //则将传输过来的分支重新赋值给branch变量
           echo "自动构建的代码分支是========【 $branch 】"
         } else {
           echo "branch  ==============【 $branch 】"
         }

pipeline {
    agent any

    environment {      // 在 environment 引入上边定义的函数,以便于全局调用
        _version = createVersion()
    }

    stages {
        stage('拉取代码'){
            steps{
                 git branch: '${branch}', credentialsId: '用户凭据', url: '代码地址'
            }
        }        
    }   
}

成功

当GitLab通过插件触发构建时,会根据GitLab发送的JSON有效负载设置各种环境变量.您可以在整个作业配置中使用这些.可用的变量有:

gitlabBranch  获取提交到 gitlab 仓库的当前分支名
gitlabSourceBranch 当用户合并分支时,获取要合并的 gitlab 源分支名
gitlabActionType 获取当前 gitlab 操作类型,如:NOTE, PUSH, MERGE
gitlabUserName 获取提交到 gitlab 仓库的用户名称
gitlabUserUsername 获取提交到 gitlab 仓库的用户用户名
gitlabUserEmail 获取提交到 gitlab 仓库的用户邮箱地址
gitlabSourceRepoHomepage 获取提交到 gitlab 源仓库地址
gitlabSourceRepoName 获取提交到 gitlab 源仓库名
gitlabSourceNamespace 获取提交到 gitlab 源仓库的命名空间