在 gitlab MR 的合并事件上触发 Jenkins 管道作业

Trigger Jenkins Pipeline job on merge event for gitlab MR

这应该是相当基础的,但是当我研究时,我发现了诸如 gerrit triggrs 之类的东西,对于像这样简单的事情来说,它们似乎太复杂了。

我想在 JobDSL 脚本中做这样的事情:

pipelineJob('deploy-game') {
    definition {
        environmentVariables {
          env('ENVIRONMENT', "${ENVIRONMENT}")

          keepBuildVariables(true)
        }
        cpsScm {
            scm {
                git{
                    remote {
                        url('https://blabla.git')
                        credentials('gitlab-credentials')
                    }
                    branches('${gitlabsourcebranch}')
                }
            }
            scriptPath('path/to/this.jenkinsfile')
        }
        triggers {
            gitlabPush {
                buildOnMergeRequestEvents(true)
                if ($gitlabMergeRequestState == 'merged')  // this part
            }
        }
    }
}

或者,触发所有MR事件,然后在管道脚本中过滤掉:

pipeline {
  agent none
  environment {
    ENVIRONMENT   = "${ENVIRONMENT}"
  }
  triggers {
    $gitlabMergeRequestState == 'merged' // this one
  }
  stages {
        stage ('do-stuff') {
          agent {
            label 'agent'
          }
          steps {
            sh 'some commands ...'
          }
        }
   }
}

我该怎么做?

这就是应该的样子,希望这就是您要找的。

pipelineJob('Job_Name') {
          definition {
            cpsScm {
                lightweight(true)
                triggers {
                    gitlabPush {
                        buildOnMergeRequestEvents(true) // it will trigger build when MR is opened.
                        buildOnPushEvents(true)
                        commentTrigger('retry a build') // When you write the comment on MR on gitlab. it will also trigger build
                        enableCiSkip(true)
                        rebuildOpenMergeRequest('source')
                        skipWorkInProgressMergeRequest(false)
                        targetBranchRegex('.*master.*|.*release.*') //This mean only push happened to master or release then only trigger jenkins build. Do not trigger build on normal feature branch push until the MR is opened.                   
                    }
                }
                configure {
                    it / triggers / 'com.dabsquared.gitlabjenkins.GitLabPushTrigger' << secretToken('ADD_TOKEN_FROM_JENKINS_JOB')
                }
                scm {      
                    git {
                        remote {
                            credentials('ID')
                            url("git@URL.git")
                            branch("refs/heads/master")
                        }
                    }
                }
                scriptPath("jenkinsfile")
            }
          }
        }