Jenkins plugin to run dynamic agents in a Kubernetes/Docker environment
Jenkins plugin to run dynamic agents in a Kubernetes/Docker environment
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 urlJENKINS_SECRET : the secret key for authenticationJENKINS_AGENT_NAME : the name of the Jenkins agentJENKINS_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.
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:
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
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.
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.
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.
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).
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.
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.
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:
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
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.
apiVersion: v1
kind: Pod
spec:
containers:
- name: jnlp
image: 'jenkins/inbound-agent'
args: ['\$(JENKINS_SECRET)', '\$(JENKINS_NAME)']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
containerstep does not scale well. Consider selecting the Use active containers option in cloud configuration for a more efficient mode.
…or
…POD_CONTAINER variableThe variable POD_CONTAINER contains the name of the container in the current context.
It is defined only within a container block.
podTemplate(containers: […]) {
node(POD_LABEL) {
stage('Run shell') {
container('mycontainer') {
sh "echo hello from $POD_CONTAINER" // displays 'hello from mycontainer'
}
}
}
}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.)
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.
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:
kubernetesnode 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.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).NORMAL or EXCLUSIVE, this controls whether Jenkins only schedules jobs with label expressions matching or use theNo open issues yet, or sync has not completed.