I would like to be able to specify the agent based on a parameter in my shared library groovy file. I know the following example will work but it requires me to copy the pipeline twice:
// vars/selectAgent.groovy
def call(String agent) {
if (agent === "any") {
pipeline {
agent any
stages {
stage('Stage1') {
steps {
echo "ran on any agent"
}
}
}
}
} else {
pipeline {
agent {
label "$agent"
}
stages {
stage(‘Stage1') {
steps {
echo "The build ran on agent label ${agent}"
}
}
}
}
}
}
Is it possible to create an agent statement which would be rendered either as
agent any
or
agent {
label 'myLabel'
}
without having to repeat the whole pipeline? Please note that my pipeline is much more longer than this simple example. I looked into GroovyASTTransform but I have no idea how this works, if it would be possible and how to do it.
Obviously I would want my Jenkinsfile to contain either
selectAgent('any')
or
selectAgent('myLabel')
Stage level Agent Selection, and add expression as a condition. In this way you are going to execute only 1 stage for your external argument.
Note: The Pipeline is not tested but it should work.