Jenkins declarative pipeline configuring the agent using shared library

1.4k Views Asked by At

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')
1

There are 1 best solutions below

1
On

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.

def call(String agent) {
    pipeline {
    agent none
    stages {
        stage('Even Stage') {
            when {
                expression { ${params.agent} == 'any' }
            }
            agent {label 'agent1'} 
            steps {
                echo "The build number is even"
            }
        }
        stage('Odd Stage') {
            when {
                expression { !${params.agent} == 'any' }
            }
            agent {label 'agent2'} 
            steps {
                echo "The build number is odd"
            }
        }
    }
}
}

Note: The Pipeline is not tested but it should work.