Lesson content
Read, practise, then check your understanding
Jenkinsfile: Pipeline as Code
A Jenkinsfile gives pipeline changes history, review, branching, and reproducibility. Declarative Pipeline supplies a structured pipeline {} model with validation and standard directives. Scripted Pipeline uses Groovy control flow and offers lower-level flexibility.
Core ideas
agentchooses execution capacity globally or per stage.environmentdeclares values; credentials helpers should scope sensitive data narrowly.optionsconfigures behavior such as timeouts, timestamps, retry, durability, and retention.postruns actions for states such asalways,success,failure, orcleanup.
How it works
Keep the top-level Jenkinsfile readable as a delivery map. Move reusable, tested logic into scripts or a governed Shared Library, not large inline Groovy blocks. Declarative syntax is the default choice for consistent team pipelines; use script only where its flexibility is necessary.
Configuration example
pipeline {
agent { label 'linux' }
options {
timestamps()
timeout(time: 20, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '30'))
}
environment { APP_ENV = 'ci' }
stages {
stage('Check') { steps { sh './ci/check.sh' } }
}
post {
always { junit testResults: 'reports/*.xml', allowEmptyResults: true }
cleanup { deleteDir() }
}
}
The sample is intentionally small. In a real installation, replace hostnames, labels, credentials, retention, and commands with reviewed values from your own platform standards.
Production guidance
- Avoid Groovy interpolation of secrets; let the shell expand bound environment variables where safe.
- Pin external tools and library versions so an old commit remains buildable.
- Use Replay only for diagnosis, then commit the resulting pipeline change to source control.
The chapter quiz follows this lesson and tests both terminology and safe operating choices.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.