Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
K

kubernetes-plugin

> 云原生
Open source

Jenkins plugin to run dynamic agents in a Kubernetes/Docker environment

2.3K stars0 likes7 views
WebsiteGitHub

About

Jenkins plugin to run dynamic agents in a Kubernetes/Docker environment

Kubernetes plugin for Jenkins

Jenkins plugin to run dynamic agents in a Kubernetes cluster.

Based on the Scaling Docker with Kubernetes article, automates the scaling of Jenkins agents running in Kubernetes.

The plugin creates a Kubernetes Pod for each agent started, and stops it after each build.

Agents are launched as inbound agents, so it is expected that the container connects automatically to the Jenkins controller. For that some environment variables are automatically injected:

  • JENKINS_URL : Jenkins web interface url
  • JENKINS_SECRET : the secret key for authentication
  • JENKINS_AGENT_NAME : the name of the Jenkins agent
  • JENKINS_NAME : the name of the Jenkins agent (Deprecated. Only here for backwards compatibility)

Tested with jenkins/inbound-agent, see the Docker image source code.

It is not required to run the Jenkins controller inside Kubernetes.

Table of Contents

  • Generic setup
  • Usage
  • Configuration reference
  • Inheritance
  • Declarative Pipeline
  • Misc.
  • Running on OpenShift
  • Features controlled using system properties
  • Windows support
  • Security considerations
  • Configuration on minikube
  • Configuration on Google Container Engine
  • Troubleshooting
  • Building and Testing
  • Docker image
  • Running in Kubernetes
  • Related Projects

Generic Setup

Prerequisites

  • A running Kubernetes cluster 1.14 or later. For OpenShift users, this means OpenShift Container Platform 4.x.
  • A Jenkins instance installed
  • The Jenkins Kubernetes plugin installed
  • A ServiceAccount with sufficient privileges (example)

Configuration

Fill in the Kubernetes plugin configuration. In order to do that, you will open the Jenkins UI and navigate to Manage Jenkins -> Manage Nodes and Clouds -> Configure Clouds -> Add a new cloud -> Kubernetes and enter the Kubernetes URL and Jenkins URL appropriately, unless Jenkins is running in Kubernetes in which case the defaults work.

Supported credentials include:

  • Username/password
  • Secret File (kubeconfig file)
  • Secret text (Token-based authentication) (OpenShift)
  • Google Service Account from private key (GKE authentication)
  • X.509 Client Certificate

If you check WebSocket then agents will connect over HTTP(S) rather than the Jenkins service TCP port. This is unnecessary when the Jenkins controller runs in the same Kubernetes cluster, but can greatly simplify setup when agents are in an external cluster and the Jenkins controller is not directly accessible (for example, it is behind a reverse proxy or a ingress resource). See JEP-222 for more.

To test this connection is successful you can use the Test Connection button to ensure there is adequate communication from Jenkins to the Kubernetes cluster, as seen below

Garbage collection

In some exceptional cases, agent pods can be left behind, with no declared Jenkins agent in the controller. They will try to reconnect over and over, until something deletes them.

The plugin provides a garbage collection mechanism to clean up these pods. As it may generate extra load on the Kubernetes API server, it is disabled by default.

Static pod templates

In addition to that, in the Kubernetes Pod Template section, we need to configure the image that will be used to spin up the agent pod. The Jenkins agent runs by default in a container named jnlp (historical name, kept for backward compatibility).

You may use it, use a different agent container name and/or provide your own container image.

To avoid drift between the Jenkins controller and your agent, we recommend not to include the agent JAR in your image, but instead use the Inject Jenkins agent in agent container checkbox.

The provided container image must have a JRE installed that is compatible with the Java version required by the Jenkins controller.

In the ‘Kubernetes Pod Template’ section you need to specify the following (the rest of the configuration is up to you): Kubernetes Pod Template Name - can be any and will be shown as a prefix for unique generated agent’ names, which will be run automatically during builds Docker image - the docker image name that will be used as a reference to spin up a new Jenkins agent, as seen below

Note: If your Jenkins controller is outside the cluster and uses a self-signed HTTPS certificate, you will need some additional configuration.

Restricting what jobs can use your configured cloud

Clouds can be configured to only allow certain jobs to use them.

To enable this, in your cloud's advanced configuration check the Restrict pipeline support to authorized folders box. For a job to then use this cloud configuration you will need to add it in the jobs folder's configuration.

Usage

Overview

The Kubernetes plugin allocates Jenkins agents in Kubernetes pods.

Within these pods, there is always one special container that is running the Jenkins agent.

Its name defaults to jnlp, but you can override the name with one of your choosing in pod template configuration.

Other containers can run arbitrary processes of your choosing, and it is possible to run commands dynamically in any container in the agent pod using the container step (pipeline only).

Using a label

Pod templates defined using the user interface declare a label. When a freestyle job or a pipeline job using node('some-label') uses a label declared by a pod template, the Kubernetes Cloud allocates a new pod to run the Jenkins agent.

It should be noted that the main reason to use the global pod template definition is to migrate a huge corpus of existing projects (including freestyle) to run on Kubernetes without changing job definitions. New users setting up new Kubernetes builds should use the podTemplate step as shown in the example snippets here.

Using the pipeline step

The podTemplate step defines an ephemeral pod template. It is created while the pipeline execution is within the podTemplate block. It is immediately deleted afterwards. Such pod templates are not intended to be shared with other builds or projects in the Jenkins instance.

The following idiom creates a pod template with a generated unique label (available as POD_LABEL) and runs commands inside it.

groovy
podTemplate {
    node(POD_LABEL) {
        // pipeline steps...
    }
}

Commands will be executed by default in the designated agent container, where the Jenkins agent is running.

This will run in the agent container:

groovy
podTemplate {
    node(POD_LABEL) {
        stage('Run shell') {
            sh 'echo hello world'
        }
    }
}

Find more examples in the examples dir.

The default agent image used can be customized by adding it to the template

groovy
containerTemplate(name: 'jnlp', image: 'jenkins/inbound-agent', args: '${computer.jnlpmac} ${computer.name}'),

or with the yaml syntax. Pretty much any field from the pod model can be specified through the yaml syntax.

yaml
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: jnlp
    image: 'jenkins/inbound-agent'
    args: ['\$(JENKINS_SECRET)', '\$(JENKINS_NAME)']

Multiple containers support

Multiple containers can be defined for the agent pod, with shared resources, like mounts. Ports in each container can be accessed as in any Kubernetes pod, by using localhost.

One container must run the Jenkins agent. If unspecified, a container named jnlp will be created with the inbound-agent image. The Jenkins agent requires a JRE to run, so you can avoid the extra container by providing a name using the agentContainer. To get the Jenkins agent injected, you will also need to set agentInjection to true, and leave the command and argument fields empty for this container. The container specified by agentContainer will be the one where shell steps (or any other step running remote commands on the agent) will run on.

To execute commands in another container part of the pod (different from the one running the Jenkins agent), you can use the container step.

[!NOTE] Due to implementation constraints, there can be issues when executing commands in different containers if they run using different uids. It is recommended to use the same uid across the different containers part of the same pod to avoid any issue.

[!NOTE] The default implementation of the container step does not scale well. Consider selecting the Use active containers option in cloud configuration for a more efficient mode.

…

or

…

POD_CONTAINER variable

The variable POD_CONTAINER contains the name of the container in the current context. It is defined only within a container block.

groovy
podTemplate(containers: […]) {
  node(POD_LABEL) {
    stage('Run shell') {
      container('mycontainer') {
        sh "echo hello from $POD_CONTAINER" // displays 'hello from mycontainer'
      }
    }
  }
}

Retrying after infrastructure outages

You can use the retry step to automatically try the whole build stage again with a fresh pod in case of fatal infrastructure problems. (For example: cluster backup & restore; node pool used for agents drained and upgraded.)

groovy
podTemplate(…) {
  retry(count: 2, conditions: [kubernetesAgent(), nonresumable()]) {
    node(POD_LABEL) {
      sh 'your-build-process'
    }
  }
}

will rerun the whole node block (using the same pod definition) in case the first attempt fails for a qualifying reason traceable to loss of the pod (not routine problems such as compilation errors or OutOfMemoryError).

For Declarative Pipeline, just add the retries option, as shown below.

Configuration reference

Pod template

Pod templates are used to create agents. They can be either configured via the user interface, or in a pipeline, using the podTemplate step. Either way it provides access to the following fields:

  • cloud The name of the cloud as defined in Jenkins settings. Defaults to kubernetes
  • name The name of the pod. This is only used for inheritance.
  • namespace The namespace of the pod.
  • label The node label. This is how the pod template can be referred to when asking for an agent through the node step. In a pipeline, it is recommended to omit this field and rely on the generated label that can be referred to using the POD_LABEL variable defined within the podTemplate block.
  • yaml yaml representation of the Pod, to allow setting any values not supported as fields
  • yamlMergeStrategy merge() or override(). Controls whether the yaml definition overrides or is merged with the yaml definition inherited from pod templates declared with inheritFrom. Defaults to override() (for backward compatibility reasons).
  • containers The container templates part of the pod (see below for details).
  • serviceAccount The service account of the pod.
  • nodeSelector The node selector of the pod.
  • nodeUsageMode Either NORMAL or EXCLUSIVE, this controls whether Jenkins only schedules jobs with label expressions matching or use the

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Javaagentcloudkubernetes

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category云原生
PricingOpen source

> Related tools

K
Kubernetes
容器编排事实标准
H
Helm
Kubernetes 包管理器
S
seaweedfs
SeaweedFS is a distributed storage system for object storage (S3), file systems, and Iceberg tables,