Jenkins Pipeline Cookbook

Jenkins Declarative Pipeline with the dynamic agent - how to configure it?

In some cases, you would like to use Jenkins declarative pipeline with the dynamic agent. For instance, you want to provide a list of available agent nodes as a parameter for the pipeline job. In this blog post, I will explain how you can configure such a behavior in just a few steps.

Jenkins Pipeline agent label from the parameter

Listing 1. Jenkinsfile
pipeline {
    agent {
        label params.AGENT == "any" ? "" : params.AGENT (1)
    }

    parameters {
        choice(name: "AGENT", choices: ["any", "docker", "windows", "linux"]) (2)
    }

    stages {
        stage("Build") {
            steps {
                echo "Hello, World!"
            }
        }
    }
}

There is one thing worth explaining. You can see that in the line , we check if params.AGENT is equal to "any". If this is the case, we put an empty string instead. (An empty string in this case is an equivalent of agent any - source.) Otherwise, Jenkins would search for the node with label "any" instead.

In the line , we define a list of available nodes. When you start the job and choose any from the dropdown, any available node will be used to run the job. If you choose docker, windows, or linux (or any other label you will define in your pipeline), the node with that exact label will be used to run the job. And that’s it.

Did you like this article?

Consider buying me a coffee

0 Comments