'Specify agent in Jenkins Pipeline Shared Library

I am trying to customize a shared Library which run a stage in a specify agent by adding the possibility to specify the agent.

def call(String agentLabel) {
  pipeline {
    agent { label "$agentLabel" }
    stages {
      stage('Hello') { steps { echo 'Hello World' } }
    }
  }
}

This is OK but now I want to customize the type of agent (IE. either use label or docker agent) ? This don't work :

def call(String agentLabel, String agentDockerImage = null) {
  Closure agentRunner = null
  if (agentDockerImage) {
    agentRunner = {
      docker {
        label "$agentLabel"
        image "$agentDockerImage"
      }
    }
  } else {
    agentRunner = {
      label "$agentLabel"
    }
  }
  pipeline {
    agent { agentRunner.call() }
    stages {
      stage('Hello') { steps { echo 'Hello World' } }
    }
  }
}

WorkflowScript: 15: Invalid agent type "call" specified. Must be one of [any, docker, dockerfile, label, none] @ line 15, column 29.
agent { agentRunner.call() }
^



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source