jenkinsgroovyjenkins-groovyjenkins-declarative-pipeline

How to add a timeout to selecting the agent in a Jenkins declarative pipeline


In Jenkins I am using declarative pipelines to select an agent based on a user input parameter. The issue is, when the agent is offline, the pipeline stays forever in the build queue. I would like to add some sort of timeout to selecting the agent.

How do I properly add a timeout? Any help would be greatly appreciated.

This is my pipeline:

pipeline {
    agent { node { label "${params.AGENT}" } }
    parameters {
        choice(
            name: 'AGENT',
            description: 'Host where the pipeline will be run.',
            choices: [ 'foo', 'bar' ],
        )
    }
    stages {
        stage('Rest of the pipeline') {
            steps {
                echo "the rest of my pipeline..."
            }
        }
    }
}

I have tried adding a timeout option:

    options {
        timeout(time: 5, unit: 'MINUTES', activity: true)
    }

But that did not work for selecting the agent (which I assume happens before any of the stages).


Solution

  • My solution was to have no agent until I checked my desired agent was online as a separate stage, and then I specified the agent at the stage level instead of the top level.

    pipeline {
        agent none
        parameters {
            choice(
                name: 'AGENT',
                description: 'Host where the pipeline will be run.',
                choices: [ 'foo', 'bar' ],
            )
        }
        stages {
            stage('Check Node Status') {
                steps {
                    script {
                        if (!Jenkins.instance.getNode(params.AGENT).toComputer().isOnline()) {
                            error "Node ${params.AGENT} is offline"
                        }
                    }
                }
            }
            stage('Rest of the pipeline') {
                agent { label params.DESTINATION_HOST }
                steps {
                    echo "the rest of my pipeline..."
                }
            }
        }
    }
    

    The disadvantage of this is if I have many stages I have to specify the agent over and over again.

    Docs: