Jenkinsfile §
- The
agent
directive tells Jenkins where and how to execute the Pipeline
Simple Jenkinsfile §
pipeline {
agent { docker { image 'maven:3.9.0-eclipse-temurijn-11' } }
stages {
stage('build') {
sh 'mvn --version'
}
}
}
Timeout, Retry, Post Action §
pipeline {
agent any
stages {
stage('Build') {
steps {
sh './gradlew build'
}
}
stage('Sanity check') {
steps {
input "Continue with Deploy?"
}
}
stage('Deploy') {
steps {
retry(3) {
sh './flakey-deploy.sh'
}
timeout(time: 3, unit: 'MINUTES') {
sh './health-check.sh'
}
}
}
}
post {
always {
echo 'This will always run'
archiveArtifacts artifacts: 'build/libs/**/*.jar', fingerprint: true
junit 'build/reports/**/*.xml'
}
success {
echo 'This will run only if successful'
slackSend channel: '#ops-room',
color: 'good',
message: "The pipeline ${currentBuild.fullDisplayName} completed successfully."
}
failure {
echo 'This will run only if failed'
mail to: 'team@example.com',
subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
body: "Something is wrong with ${env.BUILD_URL}"
}
unstable {
echo 'This will run only if the run was marked as unstable'
}
changed {
echo 'This will run only if the state of the Pipeline has changed'
echo 'For example, if the Pipeline was previously failing but is now successful'
}
}
}
String Interpolation §
- Jenkins uses the identical rules Groovy has for String interpolation
- These variables will be masked by Jenkins in the console output
- But Env vars in double quotes will be expandend by the shell, exposing it to operating system process listings
- So to avoid leaking credentials, use single quoted String interpolation
node {
withCredentials([string(credentialsId: 'mytoken', variable: 'TOKEN')]) {
sh '''
set +x
curl -H "Token: $TOKEN" https://some.api/
'''
}
}
/* LESS SECURE! */
node {
withCredentials([string(credentialsId: 'mytoken', variable: 'TOKEN')]) {
sh """
set +x
curl -H "Token: $TOKEN" https://some.api/
"""
}
}