Webhook 触发CICD job

gitlab是怎么触发Jenkins job的?
使用Webhook在推送代码或创建Issue时触发一个事前配置好的URL,GitLab会向设定的Webhook的URL发送一个POST请求。
配置webhook 需要 Maintainer权限

模板Jenkinsfile详解
Jenkinsfile 名:Jenkinsfile_Pre_build_MR

语句的作用参考 // 后的注释,标黄部分必须根据项目实际情况修改

pipeline {
    agent { // 2~33行 编译环境初始化
        kubernetes {
            label "${UUID.randomUUID().toString()}"
            yaml """
                metadata:
                  labels:
                    some-label: some-label-value
                    class: KubernetesDeclarativeAgentTest
                  namespace: scm
                spec:               
                  nodeSelector:
                    jenkins-ci: "true"
                  containers:
                    - name: prepare
                      image: hub.hobot.cc/builder/cicd-common-tool:v9
                      command:
                      - cat
                      tty: true
                      env:
                        - name: CONTAINER_ENV_VAR
                          value: prepare
                    - name: build
                      image: hub.hobot.cc/builder/ubuntu16.04:20220402
                      command:
                      - cat
                      tty: true
                      env:
                        - name: CONTAINER_ENV_VAR
                          value: build
            """
        }
    }
    stages{
        stage('lanuch') { //25~43 调用get_code()函数执行下载代码
            steps {
                container('prepare') {
                    script {
                        sh 'env'
                        get_code()       
                    }
                }
            }
        }
        stage('building') { //44~52 执行编译,配置需要编译的脚本
            steps {
                container('build') { //括号里的"build"是23行定义的name
                    script {
                        sh 'bash -ex build.sh' 
                    }
                }
            }
        }
    }
    options {
      gitLabConnection('Gitlab connector by hobot.ci')
    }
    triggers {//58 ~78 行 trigger触发器参数配置
    //更多触发器配置参考:https://www.cnblogs.com/hellxz/p/how-to-add-gitlab-trigger-for-jenkins.html
        gitlab( //以下配置按项目实际需要修改
                triggerOnPush: true,
                //是否 Push 事件时触发
                triggerOnMergeRequest: true,
                //是否 Merge Request 事件时触发,MR 包含创建、变更、接受等很多情况
                triggerOpenMergeRequestOnPush: "never",
                //Merge Request 中源分支或目的分支被Push时触发
                triggerOnNoteRequest: true,
                 //注释触发,根据提交时写的注释触发
                noteRegex: "Jenkins",
                //注释触发正则表达式
                skipWorkInProgressMergeRequest: true,
                //跳过正在合并过程中的 Merge Request
                ciSkip: true,
                //允许 CI 跳过
                setBuildDescription: true,
                //是否添加构建触发原因描述
                addNoteOnMergeRequest: true,
                addCiMessage: true,
                addVoteOnMergeRequest: true,
                acceptMergeRequestOnSuccess: true,
                //构建成功时向GitLab发起接收 Merge Request 事件
                pendingBuildName: "Jenkins",
                cancelPendingBuildsOnUpdate: true,
                //当源码更新时取消正在 Pending 状态的构建,适当开启有助于减少构建次数,
                branchFilterType: "All",
                //分支匹配类型:基于名称 NameBasedFilter,基于正则表达式 RegexBasedFilter,两者混用 ALL
                //includeBranchesSpec: "",
               //branchFilterType 为 NameBasedFilter生效,监听哪些分支的事件,多分支使用英文逗号分开
                //excludeBranchesSpec: "",
        )
    }
    parameters { //92~100 定义jenkins job参数
        string defaultValue: '', description: 'Enter gitlabActionType', name: 'gitlabActionType_replay', trim: true
        string defaultValue: '', description: 'Enter gitlabSourceBranch', name: 'gitlabSourceBranch_replay', trim: true
        string defaultValue: '', description: 'Enter gitlabTargetBranch', name: 'gitlabTargetBranch_replay', trim: true
        string defaultValue: '', description: 'Enter gitlabSourceRepoHomepage', name: 'gitlabSourceRepoHomepage_replay', trim: true
        string defaultValue: '', description: 'Enter gitlabMergeRequestIid', name: 'gitlabMergeRequestIid_replay', trim: true
        string defaultValue: '', description: 'Enter gitlabMergeRequestLastCommit', name: 'gitlabMergeRequestLastCommit_replay', trim: true
        string defaultValue: '', description: 'Enter gitlabSourceRepoSshUrl', name: 'gitlabSourceRepoSshUrl_replay', trim: true
    }
    
    environment { //101~109 环境变量
        gitlabActionType = "${env.gitlabActionType ? "${env.gitlabActionType}" : "${env.gitlabActionType_replay}"}"
        gitlabSourceBranch = "${env.gitlabSourceBranch ? "${env.gitlabSourceBranch}" : "${env.gitlabSourceBranch_replay}"}"
        gitlabTargetBranch = "${env.gitlabTargetBranch ? "${env.gitlabTargetBranch}" : "${env.gitlabTargetBranch_replay}"}"
        gitlabSourceRepoHomepage = "${env.gitlabSourceRepoHomepage ? "${env.gitlabSourceRepoHomepage}" : "${env.gitlabSourceRepoHomepage_replay}"}"
        gitlabMergeRequestIid = "${env.gitlabMergeRequestIid ? "${env.gitlabMergeRequestIid}" : "${env.gitlabMergeRequestIid_replay}"}"
        gitlabMergeRequestLastCommit = "${env.gitlabMergeRequestLastCommit ? "${env.gitlabMergeRequestLastCommit}" : "${env.gitlabMergeRequestLastCommit_replay}"}"
        gitlabSourceRepoSshUrl = "${env.gitlabSourceRepoSshUrl ? "${env.gitlabSourceRepoSshUrl}" : "${env.gitlabSourceRepoSshUrl_replay}"}"
    }
    
    post {//112 ~ 142 根据构建结果执行不同的后续步骤,没有特殊需求不用修改
        failure {
            container('prepare') {
                updateGitlabCommitStatus name: "Jenkins", state: 'failed'
            }
        }
        success {
            container('prepare') {
                updateGitlabCommitStatus name: "Jenkins", state: 'success'
            }
        }
        unstable {
            container('prepare') {
                updateGitlabCommitStatus name: "Jenkins", state: 'success'
            }
        }
        aborted {
            container('prepare') {
                updateGitlabCommitStatus name: "Jenkins", state: 'canceled'
            }
        }
        always {
            container('prepare') {
                script {
                    if (["MERGE", "NOTE"].contains(env.gitlabActionType)) {
                        addGitLabMRComment(comment: "Build Result: ${currentBuild.currentResult}\n\nJob Link: ${env.BUILD_URL}")
                    }
                }
            }
        }
    }
}

//146~196 函数
def get_code() {
    if (["MERGE", "NOTE"].contains(env.gitlabActionType)) {
        echo "merge process"
        checkout([
            $class: 'GitSCM', 
            branches: [[name: "origin/${env.gitlabSourceBranch}"]], 
            doGenerateSubmoduleConfigurations: false, 
            extensions: [
                [$class: 'CloneOption', depth: 0, noTags: false, reference: '', shallow: false], 
                [$class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', trackingSubmodules: true], 
                [$class: 'AuthorInChangelog'], 
                [$class: 'PreBuildMerge', options: [mergeRemote: 'origin', mergeTarget: "${env.gitlabTargetBranch}"]],
                [$class: 'UserIdentity', email: 'xxxx@horizon.ai', name: 'xxxx'],
            ], 
            submoduleCfg: [], 
            userRemoteConfigs: [[credentialsId: 'e48xxxxx', url: "${env.gitlabSourceRepoSshUrl}"]]
        ])
    }
    else {
        echo "push process"
        checkout([
            $class: 'GitSCM', 
            branches: [[name: "origin/${env.gitlabSourceBranch}"]], 
            doGenerateSubmoduleConfigurations: false, 
            extensions: [
                [$class: 'CloneOption', depth: 0, noTags: false, reference: '', shallow: false], 
                [$class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', trackingSubmodules: true], 
                [$class: 'AuthorInChangelog'],
                [$class: 'UserIdentity', email: 'xxxx@horizon.ai', name: 'hobot.ci'],
            ], 
            submoduleCfg: [], 
            userRemoteConfigs: [[credentialsId: 'e48xxxx', url: "${env.gitlabSourceRepoSshUrl}"]]
        ])
        if (env.REVISION_ID) {
            echo "apply patch from ph"
            PH_BRANCH_NAME = sh (script: 'curl -s https://cr.hobot.cc/api/differential.diff.search -d api.token= -d constraints[ids][0]=$DIFF_ID | python3 -c "import sys, json; print(json.load(sys.stdin)[\'result\'][\'data\'][0][\'fields\'][\'refs\'][1][\'name\'])"',returnStdout: true).trim().replaceAll("/", "%2F")
            sh """
                git config --global user.name xxxx
                git config --global user.email xxxx@horizon.ai
                git reset --hard origin/"${PH_BRANCH_NAME}"
                git clean -fd -f
                arc patch --diff "$DIFF_ID" --nobranch --force --conduit-uri=https://cr.hobot.cc/ --conduit-token=
            """
        }

    }
}

怎么使用模板
拷贝Jenkinsfile 模板并修改

  • 拷贝Jenkinsfile_Pre_build_MR 模板,根据项目情况修改docker image、用户 编译步骤等
  • 将修改完的Jenkinsfile_Pre_build_MR命名为Jenkinsfile ,提交到项目代码仓库里

配置Jenkins job
创建Jenkins job
配置Jenkins job ,调用代码仓库中的Jenkinsfile

配置webhook
webhook只有maintainer有权限配置
配置Trigger URL
Webhook URL格式:
https://<用户名>:@ci.hobot.cc/project/
<用户名>: 可以直接使用 hobot.ci:11d6a277ee2

配置trigger条件
配置完webhookurl后,勾选Trigger选项,如下图中的2.
在这里插入图片描述

配置完成后点击Save changes 保存
验证配置是否正确
Edit 刚添加的Webhook
下拉Test ,点击event, 测试本次配置是否正确。
点击View details查看trigger 返回信息

如果返回值是200,且Headers 和 Request 返回正常 说明配置正确
Jenkins job触发成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值