How does the `when` directive control stage execution?
IntermediateConceptJenkins
Answer
when is evaluated before a stage runs and skips it if false. Common conditions: branch 'main', tag 'v*', changeRequest(), environment name: 'DEPLOY', value: 'true', expression { ... }, changeset 'src/**', plus allOf, anyOf, not. By default when is evaluated after the stage's agent is allocated; add beforeAgent true to evaluate it first and avoid spinning up an agent for a skipped stage.
stage('Deploy') {
when { beforeAgent true; branch 'main' }
agent { label 'deployer' }
steps { sh './deploy.sh' }
}
More on Jenkins
What is Jenkins and how is its architecture organised?BeginnerWhat are executors, nodes and labels in Jenkins?IntermediateWhy should you not run builds on the Jenkins controller?BeginnerHow do inbound (JNLP/WebSocket) and SSH agents connect to the controller?IntermediateWhat is a Jenkinsfile and where does it live?BeginnerDeclarative versus Scripted Pipeline: what are the differences?Intermediate