Consider this Jenkins declarative pipeline snippet using the agent directive:
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Running on any available agent'
}
}
}
}What will Jenkins do when this pipeline runs?
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Running on any available agent'
}
}
}
}Think about what agent any means in Jenkins pipelines.
The agent any directive tells Jenkins to run the pipeline on any available agent node. It does not restrict to master or docker unless specified.
In Jenkins declarative pipelines, how do you specify that the pipeline should run only on agents with a specific label?
Labels help Jenkins pick specific nodes.
The syntax agent { label 'my-label' } tells Jenkins to run the pipeline on an agent node that has the label 'my-label'.
Given this Jenkins pipeline snippet:
pipeline {
agent none
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
}
}Why does Jenkins fail to run this pipeline?
pipeline {
agent none
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
}
}Think about what agent none means and where agents can be specified.
agent none disables automatic agent allocation for the whole pipeline. If no agent is specified at the stage level, Jenkins has no node to run the steps on, causing failure.
You want to run the 'Build' stage on an agent labeled 'linux' and the 'Test' stage on an agent labeled 'windows'. Which pipeline snippet achieves this?
Remember that agent none disables global agent and you can specify agents per stage.
Setting agent none at pipeline level disables automatic agent allocation. Then each stage can specify its own agent { label '...' } to run on different nodes.
In a Jenkins declarative pipeline with multiple stages requiring different environments, what is the best practice for using the agent directive?
Think about flexibility and resource optimization in pipelines.
Using agent none at the pipeline level disables automatic agent allocation, allowing each stage to specify its own agent. This is best for pipelines with stages needing different environments, optimizing resource use.