Pipelines as code: reading a Jenkinsfile
A Jenkinsfile describes the pipeline in a file stored with the code. A declarative pipeline names the agent to run on, a list of stages each containing steps, and a post section that runs at the end. Conditions, approvals and credentials are all part of the same file.
A complete declarative pipeline
pipeline { agent { label 'linux' } environment { APP = 'payroll' } stages { stage('Build') { steps { sh './build.sh' } } stage('Test') { steps { sh './run-tests.sh' junit 'reports/*.xml' } } stage('Package') { steps { sh './package.sh ${BUILD_NUMBER}' archiveArtifacts artifacts: 'dist/*.tar.gz', fingerprint: true } } stage('Deploy to test') { when { branch 'main' } steps { sh './deploy.sh test' } } } post { failure { echo "Build ${env.BUILD_NUMBER} failed" } always { cleanWs() } } }
Reading it block by block
pipeline { }agent { label 'linux' }agent any means any available agent.environment { }stages / stage('Build')steps { sh '...' }sh runs a shell command and fails the stage if it exits non-zero.junit / archiveArtifactswhen { branch 'main' }post { failure / always }Approvals and secrets
An input step pauses the pipeline until a person approves, which is a common gate in front of production: input message: 'Deploy release 1.4.2 to production?'. A credential is brought in by ID, for example environment { DEPLOY_KEY = credentials('prod-deploy-key') }. Its value is available to the steps and is masked in the console.
Declarative and scripted
There are two syntaxes. Declarative, which starts with pipeline {, is structured and easy to read, and it is what Jenkins recommends. Scripted, which starts with node {, is plain Groovy code: more flexible, but harder for others to follow. You will mostly write and read declarative pipelines.
Which step in a Jenkinsfile runs a shell command such as ./build.sh?
Show a hint
Two letters.
Show the solution
sh, as in sh './build.sh'.
Examples are for learning. Run commands and jobs only on a system you are authorised to use, such as a training or test system, and never on production without approval.
Common mistakes
Without a when { branch 'main' } condition, any experimental branch could deploy. Gate deployment stages.
Without post, nobody hears about failures and workspaces fill the disk. Notify on failure and clean up always.
A password typed into the Jenkinsfile lives in Git history for ever. Use credentials() and an ID.
What you will see at work
- Because the Jenkinsfile is in Git, a pipeline change goes through a pull request, just like code.
- The stage names become the column titles in Jenkins' stage view, so choose names people understand at a glance.
- Many teams keep shared pipeline code in a Jenkins shared library, so dozens of repositories reuse the same tested stages.
Key terms
Check your understanding.
Take this lesson's quiz and save your progress. Free.