Welcome to Knowledge Base!

KB at your finger tips

This is one stop global knowledge base where you can learn about all the products, solutions and support features.

Categories
All
DevOps-Jenkins
Jenkins CLI

Jenkins CLI

Table of Contents
  • Using the CLI over SSH
    • Authentication
    • Common Commands
  • Using the CLI client
    • Comparing SSH and CLI client
    • Downloading the client
    • Using the client
    • Client connection modes
    • Common Problems with the CLI client

Jenkins has a built-in command line interface that allows users and administrators to access Jenkins from a script or shell environment. This can be convenient for scripting of routine tasks, bulk updates, troubleshooting, and more.

The command line interface can be accessed over SSH or with the Jenkins CLI client, a .jar file distributed with Jenkins.

This document assumes Jenkins 2.54 or newer. Older versions of the CLI client are considered insecure and should not be used.

WebSocket support is available when using both server and client 2.217 or newer.

Using the CLI over SSH

In a new Jenkins installation, the SSH service is disabled by default. Administrators may choose to set a specific port or ask Jenkins to pick a random port in the Configure Global Security page. In order to determine the randomly assigned SSH port, inspect the headers returned on a Jenkins URL, for example:

% curl -Lv https://JENKINS_URL/login 2>&1 | grep -i 'x-ssh-endpoint'
< X-SSH-Endpoint: localhost:53801
%

With the random SSH port ( 53801 in this example), and Authentication configured, any modern SSH client may securely execute CLI commands.

Authentication

Whichever user used for authentication with the Jenkins controller must have the Overall/Read permission in order to access the CLI. The user may require additional permissions depending on the commands executed.

Authentication in SSH mode relies on SSH-based public/private key authentication. In order to add an SSH public key for the appropriate user, navigate to JENKINS_URL/me/configure and paste an SSH public key into the appropriate text area.

Adding public SSH keys for a user

Common Commands

Jenkins has a number of built-in CLI commands which can be found in every Jenkins environment, such as build or list-jobs . Plugins may also provide CLI commands; in order to determine the full list of commands available in a given Jenkins environment, execute the CLI help command:

% ssh -l kohsuke -p 53801 localhost help

The following list of commands is not comprehensive, but it is a useful starting point for Jenkins CLI usage.

build

One of the most common and useful CLI commands is build , which allows the user to trigger any job or Pipeline for which they have permission.

The most basic invocation will simply trigger the job or Pipeline and exit, but with the additional options a user may also pass parameters, poll SCM, or even follow the console output of the triggered build or Pipeline run.

% ssh -l kohsuke -p 53801 localhost help build

java -jar jenkins-cli.jar build JOB [-c] [-f] [-p] [-r N] [-s] [-v] [-w]
Starts a build, and optionally waits for a completion.  Aside from general
scripting use, this command can be used to invoke another job from within a
build of one job.  With the -s option, this command changes the exit code based
on the outcome of the build (exit code 0 indicates a success) and interrupting
the command will interrupt the job.  With the -f option, this command changes
the exit code based on the outcome of the build (exit code 0 indicates a
success) however, unlike -s, interrupting the command will not interrupt the
job (exit code 125 indicates the command was interrupted).  With the -c option,
a build will only run if there has been an SCM change.
 JOB : Name of the job to build
 -c  : Check for SCM changes before starting the build, and if there's no
       change, exit without doing a build
 -f  : Follow the build progress. Like -s only interrupts are not passed
       through to the build.
 -p  : Specify the build parameters in the key=value format.
 -s  : Wait until the completion/abortion of the command. Interrupts are passed
       through to the build.
 -v  : Prints out the console output of the build. Use with -s
 -w  : Wait until the start of the command
% ssh -l kohsuke -p 53801 localhost build build-all-software -f -v
Started build-all-software #1
Started from command line by admin
Building in workspace /tmp/jenkins/workspace/build-all-software
[build-all-software] $ /bin/sh -xe /tmp/hudson1100603797526301795.sh
+ echo hello world
hello world
Finished: SUCCESS
Completed build-all-software #1 : SUCCESS
%

console

Similarly useful is the console command, which retrieves the console output for the specified build or Pipeline run. When no build number is provided, the console command will output the last completed build’s console output.

% ssh -l kohsuke -p 53801 localhost help console

java -jar jenkins-cli.jar console JOB [BUILD] [-f] [-n N]
Produces the console output of a specific build to stdout, as if you are doing 'cat build.log'
 JOB   : Name of the job
 BUILD : Build number or permalink to point to the build. Defaults to the last
         build
 -f    : If the build is in progress, stay around and append console output as
         it comes, like 'tail -f'
 -n N  : Display the last N lines
% ssh -l kohsuke -p 53801 localhost console build-all-software
Started from command line by kohsuke
Building in workspace /tmp/jenkins/workspace/build-all-software
[build-all-software] $ /bin/sh -xe /tmp/hudson1100603797526301795.sh
+ echo hello world
yes
Finished: SUCCESS
%

who-am-i

The who-am-i command is helpful for listing the current user’s credentials and permissions available to the user. This can be useful when debugging the absence of CLI commands due to the lack of certain permissions.

% ssh -l kohsuke -p 53801 localhost help who-am-i

java -jar jenkins-cli.jar who-am-i
Reports your credential and permissions.
% ssh -l kohsuke -p 53801 localhost who-am-i
Authenticated as: kohsuke
Authorities:
  authenticated
%

Using the CLI client

While the SSH-based CLI is fast and covers most needs, there may be situations where the CLI client distributed with Jenkins is a better fit. For example, the default transport for the CLI client is HTTP which means no additional ports need to be opened in a firewall for its use.

Comparing SSH and CLI client

Both SSH and jenkins-cli.jar provide access to a set of commands that lets you interact with Jenkins from a command line, but they have a few differences:

  • Jenkins SSH does not require any custom jar file on the client side, making it easier to access Jenkins from a variety of sources

  • SSH client was build to be a generic tool to serve several purposes. It doesn’t offer an easy way to do basic things that are common and specific to Jenkins environments. Using the jenkins-cli.jar instead of the ssh client may increase productivity and improve the development experience

Downloading the client

The CLI client can be downloaded directly from a Jenkins controller at the URL /jnlpJars/jenkins-cli.jar , in effect JENKINS_URL/jnlpJars/jenkins-cli.jar

While a CLI .jar can be used against different versions of Jenkins, should any compatibility issues arise during use, please re-download the latest .jar file from the Jenkins controller.

Using the client

The general syntax for invoking the client is as follows:

java -jar jenkins-cli.jar [-s JENKINS_URL] [global options...] command [command options...] [arguments...]

The JENKINS_URL can be specified via the environment variable $JENKINS_URL . Summaries of other general options can be displayed by running the client with no arguments at all.

Client connection modes

There are three basic modes in which the client may be used, selectable by global option: -http , -webSocket , and -ssh .

HTTP connection mode

This is the default mode, though you may pass the -http option explicitly for clarity.

Authentication is preferably with an -auth option, which takes a username:apitoken argument. Get your API token from /me/configure :

java -jar jenkins-cli.jar [-s JENKINS_URL] -auth kohsuke:abc1234ffe4a command ...

(Actual passwords are also accepted, but this is discouraged.)

You can also precede the argument with @ to load the same content from a file:

java -jar jenkins-cli.jar [-s JENKINS_URL] -auth @/home/kohsuke/.jenkins-cli command ...

For security reasons the use of a file to load the authentication credentials is the recommended authentication way.

An alternative authentication method is to configure environment variables in a similar way as the $JENKINS_URL is used. The username can be specified via the environment variable $JENKINS_USER_ID while the apitoken can be specified via the variable $JENKINS_API_TOKEN . Both variables have to be set all at once.

export JENKINS_USER_ID=kohsuke
export JENKINS_API_TOKEN=abc1234ffe4a
java -jar jenkins-cli.jar [-s JENKINS_URL] command ...

In case these environment variables are configured you could still override the authentication method using different credentials with the -auth option, which takes preference over them.

Generally no special system configuration need be done to enable HTTP-based CLI connections. If you are running Jenkins behind an HTTP(S) reverse proxy, ensure it does not buffer request or response bodies.

This mode is known to not work reliably or at all when using certain reverse proxies. Prefer WebSocket mode.

WebSocket connection mode

In Jenkins 2.217 and above, the -webSocket mode may be used as an alternative to -http . The advantage is that a more standard transport is used, avoiding problems with many reverse proxies or the need for special proxy configuration.

SSH connection mode

Authentication is via SSH keypair. You must select the Jenkins user ID as well:

java -jar jenkins-cli.jar [-s JENKINS_URL] -ssh -user kohsuke command ...

In this mode, the client acts essentially like a native ssh command.

By default the client will try to connect to an SSH port on the same host as is used in the JENKINS_URL . If Jenkins is behind an HTTP reverse proxy, this will not generally work, so run Jenkins with the system property -Dorg.jenkinsci.main.modules.sshd.SSHD.hostName=ACTUALHOST to define a hostname or IP address for the SSH endpoint.

Common Problems with the CLI client

There are a number of common problems that may be experienced when running the CLI client.

Server key did not validate

You may get the error below and find a log entry just below that concerning mismatched keys :

org.apache.sshd.common.SshException: Server key did not validate
    at org.apache.sshd.client.session.AbstractClientSession.checkKeys(AbstractClientSession.java:523)
    at org.apache.sshd.common.session.helpers.AbstractSession.handleKexMessage(AbstractSession.java:616)
    ...

This means your SSH configuration does not recognize the public key presented by the server. It’s often the case when you run Jenkins in dev mode and multiple instances of the application are run under the same SSH port over time.

In a development context, access your ~/.ssh/known_hosts (or in C:/Users/<your_name>/.ssh/known_hosts for Windows) and remove the line corresponding to your current SSH port (e.g. [localhost]:3485 ). In a production context, check with the Jenkins administrator if the public key of the server changed recently. If so, ask the administrator to do the the steps described above.

UsernameNotFoundException

If your client displays a stacktrace that looks like:

org.acegisecurity.userdetails.UsernameNotFoundException: <name_you_used>
    ...

This means your SSH keys were recognized and validated against the stored users but the username is not valid for the security realm your application is using at the moment. This could occur when you were using the Jenkins database initially, configured your users, and then switched to another security realm (like LDAP, etc.) where the defined users do not exist yet.

To solve the problem, ensure your users exist in your configured security realm.

Troubleshooting logs

To get more information about the authentication process:

  1. Go into Manage Jenkins > System Log > Add new log recorder .

  2. Enter any name you want and click on Ok .

  3. Click on Add

  4. Type org.jenkinsci.main.modules.sshd.PublicKeyAuthenticatorImpl (or type PublicKeyAuth and then select the full name)

  5. Set the level to ALL .

  6. Repeat the previous three steps for hudson.model.User

  7. Click on Save

When you try to authenticate, you can then refresh the page and see what happen internally.



Was this page helpful?

Please submit your feedback about this page through this quick form.

Alternatively, if you don't wish to complete the quick form, you can simply indicate if you found this page helpful?


See existing feedback here.

Groovy Hook Scripts

Groovy Hook Scripts

This section is a work in progress. Want to help? Check out the jenkinsci-docs mailing list. For other ways to contribute to the Jenkins project, see this page about participating and contributing.

Table of Contents
  • Post initialization script (init hook)
  • Boot failure hook

In several places inside Jenkins, a series of "hook scripts" get executed to allow some actions to take place in reaction to some key events.

These scripts are written in Groovy, and get executed inside the same JVM as Jenkins, allowing full access to the domain model of Jenkins. For given hook HOOK , the following locations are searched:

  • WEB-INF/HOOK.groovy in jenkins.war

  • WEB-INF/HOOK.groovy.d/*.groovy in the lexical order in jenkins.war

  • $JENKINS_HOME/HOOK.groovy

  • $JENKINS_HOME/HOOK.groovy.d/*.groovy in the lexical order

HOOK.groovy.d is suitable to avoid conflicts — multiple entities can insert stuff into the hook without worrying about overwriting each other’s code.

The following events use this mechanism by replacing HOOK in HOOK.groovy.d or HOOK.groovy by one of the below mentioned types:

  • init : Post-initialization script

  • boot-failure : Boot failure hook

Post initialization script (init hook)

You can create a Groovy script file $JENKINS_HOME/init.groovy , or any .groovy file in the directory $JENKINS_HOME/init.groovy.d/ , to run some additional things right after Jenkins starts up. The groovy scripts are executed at the end of Jenkins initialization. This script can access classes in Jenkins and all the plugins. So for example, you can write something like:

import jenkins.model.Jenkins;

// start in the state that doesn't do any build.
Jenkins.instance.doQuietDown();

Output is logged to the Jenkins log file. For Debian based users, this is /var/log/jenkins/jenkins.log

Boot failure hook

When Jenkins encounters a fatal problem during boot, it’ll invoke "boot-failure" hook script to allow automatic corrective actions to be taken (such as notifying somebody, raising alerts, restarting, and so on.)

These scripts get the cause of the problem as the "exception" variable when run.



Was this page helpful?

Please submit your feedback about this page through this quick form.

Alternatively, if you don't wish to complete the quick form, you can simply indicate if you found this page helpful?


See existing feedback here.

Read article
Managing Jenkins

Managing Jenkins

Table of Contents
  • System Configuration group
  • Security group
  • Status Information group
  • Troubleshooting group
  • Tools and Actions group
  • Uncategorized group

Most standard administrative tasks can be performed from the screens in the Manage Jenkins section of the dashboard. In this chapter, we look at these screens and explain how to use them.

The tiles displayed on the Manage Jenkins page are grouped logically. Here we discuss the pages that are part of the standard installation. Plugins may add pages to this screen.

The top of the Manage Jenkins screen may contain "Monitors" that alert you when a new version of the Jenkins software or a security update is available. Each monitor includes a description of the issue it is reporting and links to additional information about the issue

Inline help is available on most Manage Jenkins pages:

  • To access the help, select the ? icon to the right of each field.

  • Click the ? icon again to hide the help text.

The Manage Jenkins screens were modernized in 2020 to provide a more attractive user interface for all users and a much better experience for users on narrow devices such as tablets and phones. The main changes made were:

  • Configuration screens now use HTML div tags rather than the HTML table tags that were used in older releases.

  • The screens linked from this page are grouped somewhat logically, whereas older versions presented a long list of tasks in somewhat random order.

  • Some configuration fields were moved or added.

For more information about these and other changes that have been implemented, see:

  • 2.277.1 LTS Changelog

  • Jenkins 2.264+: Major changes in the weekly release line

  • Jenkins LTS Upgrade Guide

Other system administration topics are discussed in Jenkins System Administration.

System Configuration group

Screens for configuring resources for your Jenkins instance.

Configure System

Configure global settings and paths for the Jenkins instance

Global Tool Configuration

Configure tools, their locations, and automatic installers

Manage Plugins

Add, update, remove, disable/enable plugins that extend the functionality of Jenkins.

Manage Nodes and Clouds

Add, remove, control, and monitor the nodes used for the agents on which build jobs run.

Configuration as Code

Configure your Jenkins instance using a human-readable YAML file rather than the UI. This is an optional feature that appears in this group only when the plugin is installed on your controller.

Security group

Screens for configuring security features for your Jenkins instance. See Securing Jenkins for general information about managing Jenkins security.

Configure Global Security

Set configuration parameters that secure your Jenkins instance.

Manage Credentials

Configure the credentials that provide secure access to third-party sites and applications that interact with Jenkins.

Configure Credential Providers

Configure credential providers and types

Manage Users

Manage users defined in the Jenkins user database. This is not used if you use a different security realm such as LDAP or AD.

Status Information group

System Information

Displays information about the Jenkins environment.

System Log

Jenkins log that contains all java.uil.logging output related to Jenkins.

Load Statistics

Displays information about resource utilization on you Jenkins instance.

About Jenkins

Provides version and license information for your Jenkins instance.

Troubleshooting group

Manage Old Data

Remove configuration information related to plugins that have been removed from the instance.

Tools and Actions group

Screens for common management tasks and management tools that enable you to do administrative tasks without using the UI.

Reload Configuration from Disk

Discard all data that is loaded in memory and reload everything from the file system. This is useful when you modify configuration files directly on disk.

Jenkins CLI

How to use the Jenkins CLI from a shell or script.

Script Console

Execute an Apache Groovy script for administration, troubleshooting, and diagnostics.

Prepare for Shutdown

Prevents new builds from starting so that the system can be shut down safely. Displays a red banner with a custom message so that users know what is about to happen.

Red headband with a custom message

This does not ask Jenkins to stop; this action will just prevent new builds from starting. If you need to stop or restart Jenkins, you should use the command line or the /restart and /safeRestart end points. There is also a plugin called Safe Restart that will add a Restart Safely link in the UI.

Uncategorized group

Screens for plugins that have not yet declared the category of their page.



Was this page helpful?

Please submit your feedback about this page through this quick form.

Alternatively, if you don't wish to complete the quick form, you can simply indicate if you found this page helpful?


See existing feedback here.

Read article
Managing Nodes

Managing Nodes

Table of Contents
  • Components of Distributed Builds
  • Creating Agents
  • Launch inbound agent via Windows Scheduler
  • Installing a Jenkins agent on Windows
  • Creating a macOS agent for Jenkins

Components of Distributed Builds

Builds in a Distributed Builds Architecture use nodes, agents, and executors which are distinct from the Jenkins controller itself. Understanding what each of these components are is useful when managing nodes:

Jenkins controller

The Jenkins controller is the Jenkins service itself and is where Jenkins is installed. It is a webserver that also acts as a "brain" for deciding how, when and where to run tasks. Management tasks (configuration, authorization, and authentication) are executed on the controller, which serves HTTP requests. Files written when a Pipeline executes are written to the filesystem on the controller unless they are off-loaded to an artifact repository such as Nexus or Artifactory.

Nodes

Nodes are the "machines" on which build agents run. Jenkins monitors each attached node for disk space, free temp space, free swap, clock time/sync and response time. A node is taken offline if any of these values go outside the configured threshold.

The Jenkins controller itself runs on a special built-in node . It is possible to run agents and executors on this built-in node although this can degrade performance, reduce scalability of the Jenkins instance, and create serious security problems and is strongly discouraged, especially for production environments.

Agents

Agents manage the task execution on behalf of the Jenkins controller by using executors. An agent is actually a small (170KB single jar) Java client process that connects to a Jenkins controller and is assumed to be unreliable. An agent can use any operating system that supports Java. Tools required for builds and tests are installed on the node where the agent runs; they can be installed directly or in a container (Docker or Kubernetes). Each agent is effectively a process with its own PID (Process Identifier) on the host machine.

In practice, nodes and agents are essentially the same but it is good to remember that they are conceptually distinct.

Executors

An executor is a slot for execution of tasks; effectively, it is a thread in the agent. The number of executors on a node defines the number of concurrent tasks that can be executed on that node at one time. In other words, this determines the number of concurrent Pipeline stages that can execute on that node at one time.

The proper number of executors per build node must be determined based on the resources available on the node and the resources required for the workload. When determining how many executors to run on a node, consider CPU and memory requirements as well as the amount of I/O and network activity:

  • One executor per node is the safest configuration.

  • One executor per CPU core may work well if the tasks being run are small.

  • Monitor I/O performance, CPU load, memory usage, and I/O throughput carefully when running multiple executors on a node.

Creating Agents

Jenkins agents are the "workers" that perform operations requested by the Jenkins controller. The Jenkins controller administers the agents and can manage the tooling on the agents. Jenkins agents may be statically allocated or they can be dynamically allocated through systems like Kubernetes, OpenShift, Amazon EC2, Azure, Google Cloud, IBM Cloud, Oracle Cloud, and other cloud providers.

This 30 minute tutorial from Darin Pope creates a Jenkins agent and connects it to a controller.

How to create an agent node in Jenkins

Launch inbound agent via Windows Scheduler

If you are having trouble getting the inbound agent installed as a Windows service (i.e., you followed the instructions on installing the agent as a service here but it didn’t work), an alternative method of starting the service automatically when Windows starts is to use the Windows Scheduler.Â

We take advantage of the Windows Scheduler’s ability to run command at system startup

  1. Configure your node to use the "Launch agents by connecting it to the master" launch method

    • Click Save

  2. Note the command required to launch the agent

    • On the new agent node’s Jenkins page, note the agent command line shown.Â

      • It will be like:

java -jar agent.jar \
-jnlpUrl http://<JenkinsHostName>:8080/computer/<nodeName>/slave-agent.jnlp \
-secret <some_long_hex_string>
  1. Obtain the agent.jar file and copy it to your new Windows agent node

    • In the command line noted in the last step, the "agent.jar" is a hyperlink. Click it to download the agent.jar file.

    • Copy the agent.jar file to a permanent location on your agent machine

  2. Ensure that you have a java version available on your agent machine

    • If not, obtain and install a supported version of Java

  3. Run the command manually from a CMD window on your agent to confirm that it works

    • Open the CMD window

    • Run the command the one like

java -jar agent.jar -jnlpUrl \
http://<JenkinsHostName>:8080/computer/<nodeName>/slave-agent.jnlp -secret <some_long_hex_string>
  • Go back to the node’s web page in Jenkins.  If everything works then page should say "Agent is connected"

  • Stop the command (control-c)

    1. Register a new scheduled job to run the same command

  • Open "Task Scheduler" on your windows machine

    • Start → Run: task Scheduler

  • Create a basic task (Menu: Action → Create Basic Task)

    • First page of the wizard:

      • Name: Jenkins Agent

      • Description (optional)

      • Click Next

    • Next page of the wizard

      • When do you want the task to start: select "When the computer starts"

      • Click Next

    • Next page of the wizard

      • What action do you want the task to perform: select "Start a program"

      • Click Next

    • Next page of the wizard

      • Program/Script: enter "java.exe" (or the full path to your java.exe)

      • Add arguments: enter the rest of the command, like

-jar agent.jar -jnlpUrl http://<JenkinsHostName>:8080/computer/<nodeName>/slave-agent.jnlp \
-secret <some_long_hex_string>
  • eg:

-jar D:\Scripts\jenkins\agent.jar \
-jnlpUrl http://jenkinshost.example.com:8080/computer/buildNode1/slave-agent.jnlp -secret \
d6a84df1fc4f45ddc9c6ab34b08f13391983ffffffffffb3488b7d5ac77fbc7
  • Click Next

    • Next page of the wizard

  • Click the check box "Open the Properties dialog for this task when I click Finish

  • Click Finish

    • Update the task’s properties

      • On the General tab

  • Select the user to run the task as

  • Select "Run whether user is logged on or not"

    • On the settings tab

  • Uncheck "Stop the task if it runs longer than"

  • Check "Run the task as soon as possible after a scheduled start is missed"

  • Check "If the task failed, restart every: 10 minutes", and "Attempt to restart up to: 3 times"

    • Click OK

      1. Start the scheduled task and again check that the agent is connected

        • Go back to the node’s web page in Jenkins.  If everything works then page should say "Agent is connected"

Installing a Jenkins agent on Windows

You can install a Jenkins agent on Windows using the command line. In this video, Darin reviews setting up and installing the Jenkins agent, including how to create any necessary files.

How to install a Jenkins agent on Windows

Creating a macOS agent for Jenkins

This video reviews the process of creating a macOS agent for Jenkins using Java 11.



Was this page helpful?

Please submit your feedback about this page through this quick form.

Alternatively, if you don't wish to complete the quick form, you can simply indicate if you found this page helpful?


See existing feedback here.

Read article
Managing Plugins

Managing Plugins

Table of Contents
  • Installing a plugin
    • From the web UI
    • Using the Jenkins CLI
    • Advanced installation
  • Updating a plugin
  • Removing a plugin
    • Uninstalling a plugin
    • Disabling a plugin
  • Pinned plugins

Plugins are the primary means of enhancing the functionality of a Jenkins environment to suit organization- or user-specific needs. There are over a thousand different plugins which can be installed on a Jenkins controller and to integrate various build tools, cloud providers, analysis tools, and much more.

Plugins can be automatically downloaded, with their dependencies, from the Update Center. The Update Center is a service operated by the Jenkins project which provides an inventory of open source plugins which have been developed and maintained by various members of the Jenkins community.

This section covers everything from the basics of managing plugins within the Jenkins web UI, to making changes on the controller’s file system.

Installing a plugin

Jenkins provides two methods for installing plugins on the controller:

  1. Using the "Plugin Manager" in the web UI.

  2. Using the Jenkins CLI install-plugin command.

Each approach will result in the plugin being loaded by Jenkins but may require different levels of access and trade-offs in order to use.

The two approaches require that the Jenkins controller be able to download meta-data from an Update Center, whether the primary Update Center operated by the Jenkins project [1] , or a custom Update Center.

The plugins are packaged as self-contained .hpi files, which have all the necessary code, images, and other resources which the plugin needs to operate successfully.

From the web UI

The simplest and most common way of installing plugins is through the Manage Jenkins > Manage Plugins view, available to administrators of a Jenkins environment.

Under the Available tab, plugins available for download from the configured Update Center can be searched and considered:

Available tab in the Plugin Manager

Most plugins can be installed and used immediately by checking the box adjacent to the plugin and clicking Install without restart .

If the list of available plugins is empty, the controller may be incorrectly configured or has not yet downloaded plugin meta-data from the Update Center. Clicking the Check now button forces Jenkins to attempt to contact its configured Update Center.

Using the Jenkins CLI

Installing Jenkins plugins using Jenkins CLI

Administrators may also use the Jenkins CLI which provides a command to install plugins. Scripts to manage Jenkins environments, or configuration management code, may need to install plugins without direct user interaction in the web UI. The Jenkins CLI allows a command line user or automation tool to download a plugin and its dependencies.

java -jar jenkins-cli.jar -s http://localhost:8080/ install-plugin SOURCE ... [-deploy] [-name VAL] [-restart]

Installs a plugin either from a file, an URL, or from update center.

 SOURCE    : If this points to a local file, that file will be installed. If
             this is an URL, Jenkins downloads the URL and installs that as a
             plugin.Otherwise the name is assumed to be the short name of the
             plugin in the existing update center (like "findbugs"),and the
             plugin will be installed from the update center.
 -deploy   : Deploy plugins right away without postponing them until the reboot.
 -name VAL : If specified, the plugin will be installed as this short name
             (whereas normally the name is inferred from the source name
             automatically).
 -restart  : Restart Jenkins upon successful installation.

Advanced installation

The Update Center only allows the installation of the most recently released version of a plugin. In cases where an older release of the plugin is desired, a Jenkins administrator can download an older .hpi archive and manually install that on the Jenkins controller.

Jenkins stores plugins it has downloaded in the plugins directory with a .jpi suffix, whether the plugins originally had a .jpi or an .hpi suffix.

If an administrator manually copies a plugin archive into the plugins directory, it should be named with a .jpi suffix to match the file names used by plugins installed from the update center.

From the web UI

Assuming a .hpi file has been downloaded, a logged-in Jenkins administrator may upload the file from within the web UI:

  1. Navigate to the Manage Jenkins > Manage Plugins page in the web UI.

  2. Click on the Advanced tab.

  3. Choose the .hpi file from your system or enter a URL to the archive file under the Deploy Plugin section.

  4. Deploy the plugin file.

Advanced tab in the Plugin Manager

Once a plugin file has been uploaded, the Jenkins controller must be manually restarted in order for the changes to take effect.

On the controller

Assuming a .hpi file has been explicitly downloaded by a system administrator, the administrator can manually place the file in a specific location on the file system.

Copy the downloaded .hpi` file into the JENKINS_HOME/plugins directory on the Jenkins controller (for example, on Debian systems JENKINS_HOME is generally /var/lib/jenkins ). If an administrator manually copies a plugin archive into the plugins directory, it should be named with a .jpi suffix to match the file names used by plugins installed from the update center.

The controller must be restarted before the plugin is loaded and made available in the Jenkins environment.

The names of the plugin directories in the Update Site [1] are not always the same as the plugin’s display name. Searching plugins.jenkins.io for the desired plugin will provide the appropriate link to the archive file.

Updating a plugin

Updates are listed in the Updates tab of the Manage Plugins page and can be installed by checking the checkboxes of the desired plugin updates and clicking the Download now and install after restart button.

Updates tab in the Plugin Manager

By default, the Jenkins controller will check for updates from the Update Center once every 24 hours. To manually trigger a check for updates, simply click on the Check now button in the Updates tab.

Removing a plugin

When a plugin is no longer used in a Jenkins environment, it is prudent to remove the plugin from the Jenkins controller. This provides a number of benefits such as reducing memory overhead at boot or runtime, reducing configuration options in the web UI, and removing the potential for future conflicts with new plugin updates.

Uninstalling a plugin

This video reviews the process of uninstalling a plugin from Jenkins.

The simplest way to uninstall a plugin is to navigate to the Installed tab on the Manage Plugins page. From there, Jenkins will automatically determine which plugins are safe to uninstall, those which are not dependencies of other plugins, and present a button for doing so.

Installed tab in the Plugin Manager

A plugin may also be uninstalled by removing the corresponding .jpi file from the JENKINS_HOME/plugins directory on the controller. The plugin will continue to function until the controller has been restarted.

If a plugin file is removed but required by other plugins, the Jenkins controller may fail to boot correctly.

Uninstalling a plugin does not remove the configuration that the plugin may have created. If there are existing jobs/nodes/views/builds/etc configurations that reference data created by the plugin, during boot Jenkins will warn that some configurations could not be fully loaded and ignore the unrecognized data.

Since the configuration(s) will be preserved until they are overwritten, re-installing the plugin will result in those configuration values reappearing.

Removing old data

Jenkins provides a facility for purging configuration left behind by uninstalled plugins. Navigate to Manage Jenkins and then click on Manage Old Data to review and remove old data.

Disabling a plugin

Disabling a plugin is a softer way to retire a plugin. Jenkins will continue to recognize that the plugin is installed, but it will not start the plugin, and no extensions contributed from this plugin will be visible.

A Jenkins administrator may disable a plugin by unchecking the box on the Installed tab of the Manage Plugins page (see below).

Installed tab in the Plugin Manager

A systems administrator may also disable a plugin by creating a file on the Jenkins controller, such as: JENKINS_HOME/plugins/PLUGIN_NAME.jpi.disabled .

The configuration(s) created by the disabled plugin behave as if the plugin were uninstalled, insofar that they result in warnings on boot but are otherwise ignored.

Using the Jenkins CLI

It is also possible to enable or disable plugins via the Jenkins CLI using the enable-plugin or disable-plugin commands.

The enable-plugin command was added to Jenkins in v2.136. The disable-plugin command was added to Jenkins in v2.151.

The enable-plugin command receives a list of plugins to be enabled. Any plugins which a selected plugin depends on will also be enabled by this command.

java -jar jenkins-cli.jar -s http://localhost:8080/ enable-plugin PLUGIN ... [-restart]

Enables one or more installed plugins transitively.

 PLUGIN   : Enables the plugins with the given short names and their
            dependencies.
 -restart : Restart Jenkins after enabling plugins.

The disable-plugin command receives a list of plugins to be disabled. The output will display messages for both successful and failed operations. If you only want to see error messages, the -quiet option can be specified. The -strategy option controls what action will be taken when one of the specified plugins is listed as an optional or mandatory dependency of another enabled plugin.

java -jar jenkins-cli.jar -s http://localhost:8080/ disable-plugin PLUGIN ... [-quiet (-q)]
[-restart (-r)] [-strategy (-s) strategy]

Disable one or more installed plugins.
Disable the plugins with the given short names. You can define how to proceed with the
dependant plugins and if a restart after should be done. You can also set the quiet mode
to avoid extra info in the console.

 PLUGIN                  : Plugins to be disabled.
 -quiet (-q)             : Be quiet, print only the error messages
 -restart (-r)           : Restart Jenkins after disabling plugins.
 -strategy (-s) strategy : How to process the dependant plugins.
                           - none: if a mandatory dependant plugin exists and
                           it is enabled, the plugin cannot be disabled
                           (default value).
                           - mandatory: all mandatory dependant plugins are
                           also disabled, optional dependant plugins remain
                           enabled.
                           - all: all dependant plugins are also disabled, no
                           matter if its dependency is optional or mandatory.

In the same way than enabling and disabling plugins from the UI requires a restart to complete the process, the changes made with the CLI commands will take effect once Jenkins is restarted. The -restart option forces a safe restart of the instance once the command has successfully finished, so the changes will be immediately applied.

Pinned plugins

Pinned plugins feature was removed in Jenkins 2.0. Versions later than Jenkins 2.0 do not bundle plugins, instead providing a wizard to install the most useful plugins.

The notion of pinned plugins applies to plugins that are bundled with Jenkins 1.x, such as the Matrix Authorization plugin .

By default, whenever Jenkins is upgraded, its bundled plugins overwrite the versions of the plugins that are currently installed in JENKINS_HOME .

However, when a bundled plugin has been manually updated, Jenkins will mark that plugin as pinned to the particular version. On the file system, Jenkins creates an empty file called JENKINS_HOME/plugins/PLUGIN_NAME.jpi.pinned to indicate the pinning.

Pinned plugins will never be overwritten by bundled plugins during Jenkins startup. (Newer versions of Jenkins do warn you if a pinned plugin is older than what is currently bundled.)

It is safe to update a bundled plugin to a version offered by the Update Center. This is often necessary to pick up the newest features and fixes. The bundled version is occasionally updated, but not consistently.

The Plugin Manager allows plugins to be explicitly unpinned. The JENKINS_HOME/plugins/PLUGIN_NAME.hpi.pinned file can also be manually created/deleted to control the pinning behavior. If the pinned file is present, Jenkins will use whatever plugin version the user has specified. If the file is absent, Jenkins will restore the plugin to the default version on startup.


1. updates.jenkins.io


Was this page helpful?

Please submit your feedback about this page through this quick form.

Alternatively, if you don't wish to complete the quick form, you can simply indicate if you found this page helpful?


See existing feedback here.

Read article
In-process Script Approval

In-process Script Approval

Table of Contents
  • Getting Started
  • Groovy Sandbox
  • Script Approval
    • Approve assuming permissions check

Jenkins, and a number of plugins, allow users to execute Groovy scripts in Jenkins. These scripting capabilities are provided by:

  • Script Console.

  • Jenkins Pipeline.

  • The Extended Email plugin.

  • The Groovy plugin - when using the "Execute system Groovy script" step.

  • The JobDSL plugin as of version 1.60 and later.

To protect Jenkins from execution of malicious scripts, these plugins execute user-provided scripts in a Groovy Sandbox that limits the internal APIs that are accessible. This protection is provided by the Script Security plugin. As soon as an unsafe method is used in any of the scripts, the administrator can use the "In-process Script Approval" action appears in Manage Jenkins to allow the unsafe method. Unsafe methods should not be enabled without careful consideration of the impact.

Entering the In-process Script Approval configuration

Getting Started

The Script Security plugin is installed automatically by the Post-install Setup Wizard, although initially no additional scripts or operations are approved for use.

Older versions of this plugin may not be safe to use. Please review the security warnings listed on the Script Security plugin page in order to ensure that the Script Security plugin is up to date.

Security for in-process scripting is provided by two different mechanisms: the Groovy Sandbox and Script Approval. The first, the Groovy Sandbox, is enabled by default for Jenkins Pipeline allowing user-supplied Scripted and Declarative Pipeline to execute without prior Administrator intervention. The second, Script Approval, allows Administrators to approve or deny unsandboxed scripts, or allow sandboxed scripts to execute additional methods.

For most instances, the combination of the Groovy Sandbox and the Script Security’s built-in list of approved method signatures, will be sufficient. It is strongly recommended that Administrators only deviate from these defaults if absolutely necessary.

Groovy Sandbox

To reduce manual interventions by Administrators, most scripts will run in a Groovy Sandbox by default, including all Jenkins Pipelines. The sandbox only allows a subset of Groovy’s methods deemed sufficiently safe for "untrusted" access to be executed without prior approval. Scripts using the Groovy Sandbox are all subject to the same restrictions, therefore a Pipeline authored by an Administrator is subject to the restrictions as one authorized by a non-administrative user.

When a script attempts to use features or methods unauthorized by the sandbox, a script is halted immediately, as shown below with Jenkins Pipeline

Sandbox method rejection
Figure 1. Unauthorized method signature rejected at runtime via Blue Ocean

The Pipeline above will not execute until an Administrator approves the method signature via the In-process Script Approval page.

In addition to adding approved method signatures, users may also disable the Groovy Sandbox entirely as shown below. Disabling the Groovy Sandbox requires that the entire script must be reviewed and manually approved by an administrator.

Creating a Scripted Pipeline and unchecking 'Use Groovy Sandbox'
Figure 2. Disabling the Groovy Sandbox for a Pipeline

Script Approval

Manual approval of entire scripts, or method signatures, by an administrator provides Administrators with additional flexibility to support more advanced usages of in-process scripting. When the Groovy Sandbox is disabled, or a method outside of the built-in list is invoked, the Script Security plugin will check the Administrator-managed list of approved scripts and methods.

When a script is approved, it is approved for use in any Jenkins feature or plugin that integrates with script approval. Script approval is not tied to a specific job or to any other specific use of the script. Due to this, care must be taken when approving a script to ensure that any user supplied parameters can not be used to exploit the instance.

For scripts which wish to execute outside of the Groovy Sandbox, the Administrator must approve the entire script in the In-process Script Approval page:

Approving an unsandboxed Scripted Pipeline
Figure 3. Approving an unsandboxed Scripted Pipeline

For scripts which use the Groovy Sandbox, but wish to execute an currently unapproved method signature will also be halted by Jenkins, and require an Administrator to approve the specific method signature before the script is allowed to execute:

Approving a new method signature
Figure 4. Approving a new method signature

Approve assuming permissions check

Script approval provides three options: Approve, Deny, and "Approve assuming permissions check." While the purpose of the first two are self-evident, the third requires some additional understanding of what internal data scripts are able to access and how permissions checks inside of Jenkins function.

Consider a script which accesses the method hudson.model.AbstractItem.getParent() , which by itself is harmless and will return an object containing either the folder or root item which contains the currently executing Pipeline or Job. Following that method invocation, executing hudson.model.ItemGroup.getItems() , which will list items in the folder or root item, requires the Job/Read permission.

This could mean that approving the hudson.model.ItemGroup.getItems() method signature would allow a script to bypass built-in permissions checks.

Instead, it is usually more desirable to click Approve assuming permissions check which will cause the Script Approval engine to allow the method signature assuming the user running the script has the permissions to execute the method, such as the Job/Read permission in this example.



Was this page helpful?

Please submit your feedback about this page through this quick form.

Alternatively, if you don't wish to complete the quick form, you can simply indicate if you found this page helpful?


See existing feedback here.

Read article