How to Restrict Jenkins Job to a Specific Agent
To restrict a Jenkins job to a specific agent, assign a unique
label to that agent and configure the job to run only on nodes with that label by setting the Restrict where this project can be run option with the agent's label. This ensures the job runs exclusively on the chosen agent.Syntax
In Jenkins, you restrict a job to a specific agent by using the Label assigned to that agent. The key parts are:
agent_label: The label name assigned to the agent.Restrict where this project can be run: A job configuration option to specify the label.
For pipeline jobs, use the agent { label 'agent_label' } syntax inside the Jenkinsfile.
groovy
pipeline {
agent { label 'agent_label' }
stages {
stage('Example') {
steps {
echo 'Running on specific agent'
}
}
}
}Example
This example shows how to restrict a Jenkins pipeline job to run only on an agent labeled linux-agent. The job will run the echo command on that specific agent.
groovy
pipeline {
agent { label 'linux-agent' }
stages {
stage('Build') {
steps {
echo 'Building on linux-agent only'
}
}
}
}Output
[Pipeline] Start of Pipeline
[Pipeline] node
Running on linux-agent
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] echo
Building on linux-agent only
[Pipeline] }
[Pipeline] }
[Pipeline] End of Pipeline
Common Pitfalls
Common mistakes when restricting jobs to specific agents include:
- Not assigning the correct label to the agent, so the job cannot find a matching node.
- Using a label that does not exist or is misspelled in the job configuration.
- For freestyle jobs, forgetting to check
Restrict where this project can be runand enter the label. - In pipeline jobs, placing the
agent { label '...' }block incorrectly or omitting it.
Always verify the agent's label and job configuration match exactly.
groovy
/* Wrong: label misspelled or missing */ pipeline { agent { label 'linux-agnt' } // typo here stages { stage('Test') { steps { echo 'This will fail to find agent' } } } } /* Correct: exact label used */ pipeline { agent { label 'linux-agent' } stages { stage('Test') { steps { echo 'Runs on correct agent' } } } }
Quick Reference
Summary tips to restrict Jenkins jobs to specific agents:
- Assign a unique label to the desired agent in Jenkins node configuration.
- For freestyle jobs, enable
Restrict where this project can be runand enter the label. - For pipeline jobs, use
agent { label 'your-label' }in the Jenkinsfile. - Double-check label spelling and agent availability before running the job.
Key Takeaways
Assign a unique label to the Jenkins agent you want to restrict the job to.
Enable 'Restrict where this project can be run' and specify the label for freestyle jobs.
Use 'agent { label "label-name" }' in pipeline jobs to restrict execution to that agent.
Always verify the label matches exactly between the job and the agent configuration.
Incorrect or missing labels cause the job to fail to find a suitable agent.