0
0
JenkinsHow-ToBeginner · 3 min read

How to Use Agent in Jenkins Pipeline: Syntax and Examples

In Jenkins Pipeline, use the agent directive to specify where your pipeline or individual stages run, such as on any available agent or a specific label. You can define agent any for any available node or agent none to disable automatic allocation and specify agents per stage.
📐

Syntax

The agent directive tells Jenkins where to run your pipeline or stages. It can be used at the pipeline level or inside individual stages.

  • agent any: Runs on any available agent.
  • agent none: No automatic agent allocation; you must specify agents in stages.
  • agent { label 'label-name' }: Runs on an agent with the specified label.
  • agent { docker 'image-name' }: Runs inside a Docker container.
groovy
pipeline {
    agent any
    stages {
        stage('Example') {
            agent { label 'linux' }
            steps {
                echo 'Running on a Linux agent'
            }
        }
    }
}
💻

Example

This example shows a pipeline that runs on any available agent by default, but the 'Build' stage runs specifically on an agent labeled 'linux'.

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            agent { label 'linux' }
            steps {
                echo 'Building on Linux agent'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing on default agent'
            }
        }
    }
}
Output
[Pipeline] echo Building on Linux agent [Pipeline] echo Testing on default agent
⚠️

Common Pitfalls

Common mistakes when using agent include:

  • Using agent none without specifying agents in all stages, causing the pipeline to fail.
  • Specifying conflicting agents at pipeline and stage levels.
  • Forgetting to use agent any or a valid label, leading to no node allocation.
groovy
pipeline {
    agent none
    stages {
        stage('Build') {
            steps {
                echo 'This will fail because no agent is specified here'
            }
        }
    }
}

// Correct way:
pipeline {
    agent none
    stages {
        stage('Build') {
            agent { label 'linux' }
            steps {
                echo 'Runs on linux agent'
            }
        }
    }
}
📊

Quick Reference

Agent DirectiveDescription
agent anyRun on any available agent
agent noneNo automatic agent; specify per stage
agent { label 'label-name' }Run on agent with specific label
agent { docker 'image-name' }Run inside Docker container

Key Takeaways

Use agent to control where your pipeline or stages run in Jenkins.
agent any runs on any available node; agent none disables automatic allocation.
Specify agents at the stage level when using agent none at pipeline level.
Avoid conflicting agent declarations between pipeline and stages.
Use labels or Docker images in agent to target specific environments.