How to dynamically switch between a docker agent and 'regular' agent in declarative pipleine

Viewed 421

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?

1 Answers

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

Related