Switch between Kubernetes and classic agents in declarative Pipelines

Hi all.

We have a large set of declarative pipelines using agent / label directive to select the on-prem Jenkins agents to run on. The label value is provided by an env property. These Jenkinsfiles are merged into customer projects, and they use their own values for this env property, matching their Jenkins infrastructure.

Now we want to gradually move Jenkins to Kubernetes, without forcing all customers to setup Kubernetes cluster at the moment when upgrading the Jenkinsfiles. Thus, we need a way to dynamically switch between agent { label “…” } and agent { kubernetes {…} } directives, e.g. depending on the value of the label env property. However, it’s declarative, so we can’t use any logic or shared library function at this place.

Any ideas how this can be accomplished? Any plugin maybe?


The ci.jenkins.io agents for the buildPlugin script are allocated from a Kubernetes cluster (when the useContainerAgent argument is true). That script might provide some pointers to help you configure your Jenkins controller so that you can use labels to reference agents started in Kubernetes rather than embedding the Kubernetes agent definition in each Pipeline job.

Thanks Mark for this pointer, we’ll check that out in detail. However, it seems we cannot really do similar things because we are using declarative pipeline, and want to continue to do so. The build should either run on (ephemeral) kubernetes agents started for that particular build, or on classic (permanent) build machines – but we found no way to include some kind of logic inside of the agent directive…