How to Use Agent with Label in Jenkins for Job Assignment
In Jenkins, use
agent { label 'your-label' } inside a pipeline to run the job on an agent with that label. This tells Jenkins to pick any available agent that matches the label for executing the job.Syntax
The basic syntax to use an agent with a label in a Jenkins pipeline is:
agent { label 'label-name' }Here, agent defines where the pipeline or stage runs, and label 'label-name' specifies the agent group by label.
groovy
pipeline {
agent { label 'linux' }
stages {
stage('Build') {
steps {
echo 'Running on a Linux agent'
}
}
}
}Example
This example shows a Jenkins pipeline that runs on any agent labeled docker. It prints a message to confirm the agent selection.
groovy
pipeline {
agent { label 'docker' }
stages {
stage('Test') {
steps {
echo 'This job runs on an agent with the docker label'
}
}
}
}Output
[Pipeline] echo
This job runs on an agent with the docker label
[Pipeline] End of Pipeline
Common Pitfalls
- Label does not exist: If no agent has the specified label, the job will stay in the queue indefinitely.
- Typo in label name: Labels are case-sensitive; a typo causes Jenkins to fail to find the agent.
- Using
agent anyinstead of label: This runs on any available agent, ignoring labels.
Always verify agent labels in Jenkins configuration before using them in pipelines.
groovy
pipeline {
agent { label 'wrong-label' }
stages {
stage('Build') {
steps {
echo 'This will not run if label is wrong'
}
}
}
}
// Correct usage:
pipeline {
agent { label 'correct-label' }
stages {
stage('Build') {
steps {
echo 'Runs on the correct labeled agent'
}
}
}
}Quick Reference
| Concept | Description | Example |
|---|---|---|
| agent | Defines where the pipeline runs | agent { label 'linux' } |
| label | Specifies agent group by label | label 'docker' |
| agent any | Runs on any available agent | agent any |
| Label case sensitivity | Labels must match exactly | label 'Linux' ≠ label 'linux' |
Key Takeaways
Use
agent { label 'label-name' } to run Jenkins jobs on specific labeled agents.Ensure the label exists and matches exactly to avoid jobs stuck in queue.
Labels are case-sensitive; double-check spelling in your pipeline and agent configuration.
If no label is specified,
agent any runs the job on any available agent.Verify agent labels in Jenkins global configuration before using them in pipelines.