Jenkinsfile
Disable trace messages (”+ some_command”) on console output
- Issue:
When adding echo shell commands in a Jenkinsfile, like
script { sh ''' echo "Hello world" ''' }
it causes the line to be printed twice, once as a execution trace messages, and once as the original echo command:
+ echo Hello world Hello world
whereas we only want to second line to be shown.
- Cause:
By default, Jenkins launches shell commands with the
set -xoption (see here for more info), which causes all commands to be echoed. For most commands defined inside the Jenkinsfile, that selection makes sense in order to know which command triggered the proceeding console output, but for echo it’s merely a repetition.- Solution:
Deactivate the trace printing by setting
set +x(the “+” switches off the option), before executing the echo command. In case different commands follow in the same shell code block, re-activate it:script { sh ''' # ### Deactivate tracing { set +x; } 2>/dev/null echo "Hello world" # ### Re-activate tracing { set -x; } 2>/dev/null cp some_file /some/dir/ ''' }
This shows the following console output:
Hello world + cp some_file /some/dir
In order to not show the set commands in the output, put them into curly braces assigning their stderr output to
/dev/null:{ set +x; } 2>/dev/null
Check current status of the pipeline
In order to check the current status of the pipeline within or in-between stages, use the following statement:
stage("Do something") {
steps {
echo "currentBuild.currentResult: ${currentBuild.currentResult}"
}
}
You can also use the status as a conditional for execution of a stage:
stage('Do something if pipeline so far OK') {
when {
expression { currentBuild.currentResult == 'SUCCESS' }
}
steps {
// do something
}
}
Print all currently set environmental variables
In order to see all currently available environmental variables, add this line to the respective Jenkinsfile position:
script {
sh 'printenv'
}
which will output them in the following manner:
10:19:18 GIT_USERNAME=****
10:19:18 JENKINS_HOME=/var/jenkins_home
10:19:18 GIT_COMMITTER_NAME=tts jenkins
10:19:18 GIT_PREVIOUS_SUCCESSFUL_COMMIT=de8bcce7ba3662eb36dc36d2d822cb3aa9adf3fb
10:19:18 MAIL=/var/mail/jenkins
10:19:18 LC_TIME=de_DE.UTF-8
...
Each of these variables can be accessed via ${ENVIRONMENT_NAME}, for example:
script {
echo $GIT_COMMITTER_NAME
}
Use time trigger as conditional
In case a certain step is only supposed to happen if a build was started via a time trigger, there is a conditional step, you can use:
if (env.BUILD_USER == "Timer Trigger") {
// do something
}