pipeline
Snippet Generator: Pipeline syntax / Declarative Directive Generator
agent
Use Jenkins agents at pipeline level
Example:
agent {label 'slave'}
agent {label 'docker-slave'}
environment
Jenkins environment variables for all sages
Define key-value pairs
Example:
environment {
PROJECT = "demo"
}
tools
Use build tools, e.g. Maven, Gradle, etc.
Tools are defined in Manage Jenkins / Global Tool Configuration
Example:
tools {
gradle 'gradle5.4'
}
options
Define Jenkins job options
Example:
options {
// Discard old builds, keep 15 days build
buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '15', numToKeepStr: '')
// Do not allow concurrent build
disableConcurrentBuilds()
// Set the quiet period for the job as 5 seconds
quietPeriod 5
// Enforce time limit as 30 minutes
timeout(30)
// Add timestamps to the Console Output
timestamps()
}
triggers
Define Jenkins job build triggers
Example:
triggers {
cron 'H/15 * * * *'
}
parameters
Define Jenkins job parameters
Can change parameters when click build with parameters
Example:
parameters {
// boolean parameter
booleanParam defaultValue: false, description: '', name: 'SkipTest'
// Mutli-choices parameter
choice choices: 'Test Env\nPre-Prod Env\nProd Env', description: '', name: 'DeployTo'
// String parameter
string defaultValue: 'demo1', description: '', name: 'ProjectName', trim: true
}
libraries
Import shared libraries to reuse codes.
TODO
stages
Define stages in Jenkins pipeline.
stage
Define a stage.
agent
Use Jenkins agent at stage level.
See above agent
.
environment
Jenkins environment variables at stage level.
See above environment
.
tools
Use build tools.
See above tools
.
when
When condition, skip the stage if when condition is false.
Example:
parameters {
// boolean parameter
booleanParam defaultValue: false, description: '', name: 'SkipTest'
}
stage('Package') {
when {
expression {return params.SkipTest}
}
steps {
sh 'mvn clean package -Dmaven.test.skip=true'
}
}
Use parameters instead when
statement.
Example:
stage('Package') {
steps {
sh "mvn clean package -Dmaven.test.skip=${params.SkipTest}"
}
}
Use if/else
instead of when
statement.
Example:
stage('Package') {
steps {
script {
if (params.SkipTest == true) {
sh "mvn clean package -Dmaven.test.skip=true"
} else {
sh "mvn clean package"
}
}
}
}
input
Wait user input in stage.
Example:
stage('Deploy') {
input {
message 'Are you sure to deploy?'
ok 'Deploy'
parameters {
choice choices: 'Dev\nQA\nPre-Prod\nProduction', description: 'Choose a target env', name: 'deployEnv'
}
}
steps {
echo "Deploy to ${deployEnv}"
}
}
steps
Jenkins steps block.
Put DSL statements in steps
.
script
Jenkins scripted pipeline statements
post
Post actions at the end of stage.
Example:
post {
always {
echo "Notify always"
}
aborted {
echo "Notify aborted"
}
success {
echo "Notify success"
}
failure {
echo "Notify failure"
}
}
post
Post actions at the end of pipeline.
See above post
.