2

I have a jenkinsfile that sometimes needs to run on a node, and sometimes on a docker agent, depending on certain parameters. I'd like to have the jenkins pipeline dynamically switch between using a docker agent declaration and a more normal agent declaration. The only thing I'm missing is how to parameterize the agent declaration. I'm trying to start simple with passing an agent declaration through a variableSo far I have:

def agentDeclaration = {
    docker {
        label '...'
        image "..."
        args "..."
    }
}

...
pipeline { 
    agent agentDeclaration
    ...
}

But this fails with the error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 117: Only "agent none", "agent any" or "agent {...}" are allowed. @ line 117, column 13.
           agent agentDeclaration
           ^

WorkflowScript: 117: No agent type specified. Must be one of [any, docker, dockerfile, kubernetes, label, none] @ line 117, column 13.
           agent agentDeclaration

I see that similar questions have been asked before here and here. Is this possible?

Clayton Keleher
  • 165
  • 1
  • 2
  • 7
  • It seems this is not possible. I have been searching for a solution for a long time now, but there seems no trivial way. What you can do it build pipeline stages dynamically in a groovy function, See https://stackoverflow.com/questions/55340071 – Axel Heider Feb 14 '23 at 12:07

2 Answers2

0

you could to parameterize the agents in jenkinsfile like that:

def dockerfile(filename, node_label) {
    [
        label: "${node_label}",
        filename: "#{filename}",
        args: "//some args"
    ]
}
...
pipeline {
    agent {
        dockerfile(dockerfile("/Path/To/Dockerfile", "node-label"))
    }
...

for all the agents type do the same way.

-1

Try passing the docker agent declaration as a string like def agentDeclaration = “{ docker { ... } }“ and dont forget to escape the double quotes within.

ben5556
  • 2,915
  • 2
  • 11
  • 16