2018-09-10

Jenkins pipeline if-else for null variable

I was struggling few days with solving scripting problem in Jenkins Pipeline job definition. Since my Powershell scripts are using parameters from Jenkins and accepting of zero lenght / null values is problem in command line. So how to secure the script?

It was about variable $env:GIT_PREVIOUS_SUCCESSFUL_COMMIT whis is empty unless first run was actually successful, but you need to think about it in script definition. It's about one ternary operation in any normal scripting language, but not in Groovy which is used in Jenkins pipeline.

So how to do? Option one is stage based:
stage('First-run')
{
when { environment name: 'GIT_PREVIOUS_SUCCESSFUL_COMMIT', value: ''
}
steps
{
echo 'There is no successful previous build, need to run completely.'
}
}

stage('Regular-run')
{
when { not { environment name: 'GIT_PREVIOUS_SUCCESSFUL_COMMIT', value: '' }}
steps
{
echo "Regular run with ${GIT_PREVIOUS_SUCCESSFUL_COMMIT}"
powershell 'powershell -File $env:WORKSPACE\\script.ps1 -phrase "start" -buildNumber $env:BUILD_NUMBER -gitprevious $env:GIT_PREVIOUS_SUCCESSFUL_COMMIT -gitcurrent $env:GIT_COMMIT -jenkinsUrl $env:JENKINS_URL'
}
}
There you see that variable is checked for step block and block is executed only when variable fits. This solution sometimes not fulfill all requirements of condition, so there is also another solution for inside if-else expression.

stage('Everytime-run')
{
steps
{
script
{
if(env.GIT_PREVIOUS_SUCCESSFUL_COMMIT !=  null)
{
echo "PREVIOUS COMMIT IS NOT NULL - ${GIT_PREVIOUS_SUCCESSFUL_COMMIT}"
powershell 'powershell -File $env:WORKSPACE\\script.ps1 -phrase "start" -buildNumber $env:BUILD_NUMBER -gitprevious $env:GIT_PREVIOUS_SUCCESSFUL_COMMIT -gitcurrent $env:GIT_COMMIT -jenkinsUrl $env:JENKINS_URL'
}
else
{
echo 'PREVIOUS COMMIT IS NULL'
}
}
}

}
Exploration of these constructions took me some time, so I hope you can solve it without issues. You can improve it by moving IF construction to block WHEN before the steps clausule.

Žádné komentáře :

Okomentovat

Dotaz, připomínka, oprava?
(pokud máte problém s vložením příspěvku, vyzkoušejte to v prohlížeči Chrome)