2

I would like to know if it's possible to configure the global agent dynamically.

I need to run my pipeline in different Jenkins environments running on Kubernetes or VMs.

When I have to run pipeline in VMs, I need to use the docker agent while it's running on Kubernetes, I need to use the kubernetes agent.

I tried to have a reference to the agent and use this reference but it doesn't work.

Some examples of my tried:

def myAgent = {
    return {
        kubernetes {
            containerTemplate {
                name 'maven-container'
                image 'maven:3.0.6'
                ttyEnabled true
                command 'cat'
            }
            defaultContainer 'maven-container'
        }
    }
}

pipeline {
  agent myAgent()
  //...
}

/////////////////

kube = {
    containerTemplate {
        name 'maven-container'
        image 'maven:3.0.6'
        ttyEnabled true
        command 'cat'
    }
    defaultContainer 'maven-container'
}

pipeline {

  agent {
    kubernetes kube
  }
}

Any help will be appreciated.

Thanks Senol

shenobi
  • 103
  • 1
  • 2
  • 7

1 Answers1

2

The problem is that the agent values are evaluated before the pipeline starts running, and not when the stage is about to run. This is somewhat counterintuitive, but here we are.

You can "cheat the system" by running a scripted pipeline before declarative, like outlined in this answer.

MaratC
  • 6,418
  • 2
  • 20
  • 27