0
0
Jenkinsdevops~5 mins

Agent directive in Jenkins - Commands & Configuration

Choose your learning style9 modes available
Introduction
When running automated tasks in Jenkins, you need to tell it where to run those tasks. The agent directive tells Jenkins which machine or environment to use for running your pipeline steps.
When you want your Jenkins pipeline to run on a specific machine or container.
When you need to run different parts of your pipeline on different environments.
When you want to use a Docker container as the environment for your build.
When you want to run your pipeline on the Jenkins master node itself.
When you want to avoid running your pipeline on any node and just run it locally.
Config File - Jenkinsfile
Jenkinsfile
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building the project'
            }
        }
    }
}

pipeline: Defines the Jenkins pipeline.

agent any: Tells Jenkins to run this pipeline on any available agent.

stages: Contains the steps to run.

stage('Build'): A step group named Build.

steps: Commands to execute inside the stage.

Commands
This command updates the Jenkins job configuration with the Jenkinsfile containing the agent directive. It tells Jenkins where to run the pipeline.
Terminal
jenkins-jobs --conf jenkins.ini update Jenkinsfile
Expected OutputExpected
Job updated successfully
Starts the Jenkins pipeline named 'my-pipeline' which uses the agent directive to select the node for running the build.
Terminal
jenkins-cli build my-pipeline
Expected OutputExpected
Started build #1
Shows the console output of the first build of 'my-pipeline' to verify the pipeline ran on the selected agent.
Terminal
jenkins-cli console my-pipeline #1
Expected OutputExpected
[Pipeline] Start of Pipeline [Pipeline] echo Building the project [Pipeline] End of Pipeline Finished: SUCCESS
Key Concept

The agent directive tells Jenkins where to run your pipeline steps, choosing the right machine or environment for your tasks.

Common Mistakes
Not specifying an agent directive in the Jenkinsfile.
Jenkins will not know where to run the pipeline and will fail with an error.
Always include an agent directive like 'agent any' or specify a particular agent.
Using 'agent none' without defining agents for individual stages.
The pipeline will have no environment to run in and will fail unless each stage has its own agent.
Use 'agent none' only if you define agents inside each stage.
Summary
The agent directive in Jenkinsfile defines where the pipeline runs.
Use 'agent any' to run on any available Jenkins node.
You can specify agents per stage or for the whole pipeline.