Wednesday 27 October 2021

Trigger Jenkins on a Merge Request from Gitlab

 



Imagine you're using Gitlab to host your source code and want to trigger a Jenkins pipeline/job when you open a merge request on specific branches. In this guide we'll explain all that you need to do that.

Before starting, we recommend you to read our guide on the basic connection between Gitlab and Jenkins, explaining all the prerequisites you need to setup to go on (user credentials and permissions).


Now, let's pretend we want to trigger the pipeline on a MR from feature/* to develop.

1) Install the "Generic Webhook trigger" plugin on Jenkins

2) In your pipeline configuration section, enable the plugin:


3) In Post Content Parameters section, you have to add these variables:

Variable

Expression

branch

$.object_attributes.source_branch

merge_status

$.object_attributes.state

body

$

For example, for the branch variable, you should have something like this:


4) In Token section, insert a token of your choice.

5) In Optional filter section, insert the following:



6) Go to Gitlab, inside your Repository -> Settings -> Integrations

In the URL section insert: https://<jenkins_url>/generic-webhook-trigger/invoke?token=<your_token>

and below, enable the flag:  "Merge request events"


Done!

You can test if your job/pipeline starts clicking on Test button, and choosing Merge Request events.



Monday 25 October 2021

Get last commit changed files in Jenkins Pipeline




To get all the modified files when starting a Jenkins Pipeline, you've just have to do 2 steps.


1. Add to the end of your scripted pipeline the following function:

 @NonCPS
def getChangedFilesList() {
    changedFiles = []

for (changeLogSet in currentBuild.changeSets) {

for (entry in changeLogSet.getItems()) { //for each commit in detected changes

for (file in entry.getAffectedFiles()) {

if (!changedFiles.contains(file.getPath())) {
// do not add duplicates

changedFiles.add(file.getPath())

}
}
}
}

return changedFiles
}


2. Call the function in a stage, after cloning the repo of your source code, to get the list of changed files (with their relative paths):

stage('Check environment') {
    steps {
        script {
            modified_files = getChangedFilesList()
            if ("myfile.txt" in modified_files) {
                echo "The file has been changed"
            } else {
                echo "The file has not been changed"
}
}
}
}

That's all!