Interesting snippets in Jenkins Declarative Pipeline

Ragavi K
3 min readJun 9, 2021

--

This is an article giving collection of interesting snippets which can be used in Jenkins Declarative Pipeline. It also gives information about some configuration details for the pipeline.

  1. Clean up stage while using Multiple agents in Pipeline

We all know that cleanWs() function wipes out the workspace. But when we’re using multiple agents in a single pipeline, multiple workspaces will be created for each agent where cleanWS() function fails to clear all available workspaces. Here’s a workaround for the same.

stage('Clean-up'){
steps {
echo 'Cleaning up'
#deletes workspace created by Agent 1
deleteDir()
#deletes workspace created by Agent 2
dir("${env.WORKSPACE}@2"){
deleteDir()
}
}
}

2. Using Dockerfile as an agent

Dockerfile can be used as agent in Jenkins Pipeline. While using multiple agents, your Dockerfile stays in the workspace of Agent 1. Now, when you try to use it as Agent 2, Jenkins will try to find the Dockerfile in the workspace of Agent 2 and throws a file not found error. So it’s necessary to give the full path of Dockerfile.

agent{
dockerfile{
# $WORKSPACE refers to the workspace where Dockerfile is stored
filename "$WORKSPACE/Dockerfile"
}
}

3. List all branches from repository as Build parameter

To list the branches as build parameter, make sure that
Active Choices
plugin is installed in your Jenkins server. In the General section of Pipeline, check the option This project is parameterized and click Add Parameter. Choose Active Choices Reactive Parameter.

Give any name to your parameter and select groovy script. The following script will list all the branches of specified repository.

def gettags = ("git ls-remote -t -h repo_url").execute()
return gettags.text.readLines().collect {
it.split()[1].replaceAll('refs/heads/', '').replaceAll('refs/tags/', '').replaceAll("\\^\\{\\}", '')
}

Substitute your repository clone URL (SSH is preferred). Leave the rest of the options as default and save. On clicking Build with Parameter option, you will get the list of branches of your repository.

4. Sending Build log as notification to slack channel

Integrate Jenkins and Slack channel where you want to send notification

Use Role-based Authorization Strategy to configure a user with console output reader permission. Store the user name and password as credentials (slack-user).

The following snippet sends the last 20 lines of console output of any failure builds to the configured slack channel.

withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId:'slack-user', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) 
{
slackSend channel : "channel_name",
teamDomain: "domain_name",
color: "danger",
failOnError: true,
message: "Build Failed: ${env.JOB_NAME} ${env.BUILD_DISPLAY_NAME} \n The ${env.BUILD_URL} failed. (<${env.BUILD_URL}|Open>) \n \n ${sh(script:'curl -u $USERNAME:$PASSWORD ${BUILD_URL}consoleText | tail -n20', returnStdout: true)}",
tokenCredentialId: 'slack-token',
notifyCommitters: true,
username: 'jenkins';
}

5. Autobuild pipeline on changes to a Specific folder

You might have configured auto build pipelines on changes in repository in Jenkins. But ever executed any stage only if there’s change to a specific folder in repository?

The following snippet watches the changes in code particularly the folder. The stage gets executed only if there’s change in the mentioned folder.

stage('Stage_name'){
when {
anyOf {
changeset 'Folder_name/**/*'
}
//steps to execute further
}
}

There’s also allOf option to verify changes in a group of folders and procede with stage execution.

Thank you for reading, if you have anything to add please send a response or add a note!

--

--

No responses yet