jenkinsgroovyjenkins-pipelinejenkins-groovy

Dynamically select agent in Jenkinsfile


I want to be able select whether a pipeline stage is going to be executed with the dockerfile agent depending on the presence of a Dockerfile in the repository. If there's no Dockerfile, the stage should be run locally.

I tried something like

pipeline {
    stage('AwesomeStage') {
        when {
            beforeAgent true
            expression { return fileExists("Dockerfile") }
        }
        agent { dockerfile }
        steps {
           // long list of awesome steps that should be run either on Docker either locally, depending on the presence of a Dockerfile
        }
    }

}

But the result is that the whole stage is skipped when there's no Dockerfile.

Is it possible to do something like the following block?

//...
if (fileExists("Dockerfile")) {
    agent {dockerfile}
}
else {
    agent none
}
//...

Solution

  • I came up with this solution that relies on defining a function to avoid repetion and defines two different stages according to type of agent.

    If anyone has a more elegant solution, please let me know.

    def awesomeScript() {
    // long list of awesome steps that should be run either on Docker either locally, depending on the presence of a Dockerfile
    }
    pipeline {
        stage('AwesomeStageDockerfile') {
            when {
                beforeAgent true
                expression { return fileExists("Dockerfile") }
            }
            agent { dockerfile }
            steps {
               awesomeScript()
            }
        }
        stage('AwesomeStageLocal') {
            when {
                beforeAgent true
                expression { return !fileExists("Dockerfile") }
            }
            agent none
            steps {
               awesomeScript()
            }
        }
    
    }