Triggering Jenkins jobs from the command line

  Thursday, February 25, 2021

It occurred to me that many people do not know that it is possible to trigger Jenkins jobs from the command line. But it is possible and all you need is a SSH client. Here is a short introduction on how to get it working.

Enable the Jenkins SSH daemon

Jenkins includes a implementation of a SSH daemon. This isn’t a alternative to OpenSSH to allow users to gain shell access to a host, but rather it allows people to use their SSH client to interact with Jenkins.

To enable the daemon, head to Manage Jenkins → Configure Global Security (or https://<yourjenkins>/configureSecurity) and find the SSH Server option. There choose Fixed with a port number, for example 2020.

Configure your public SSH key

Your SSH client will need to authenticate itself with the Jenkins server. The recommended option for that is to use public key authentication. Head over to your user configuration page in Jenkins (https://<yourjenkins>/user/<userName>/configure) and add your public key in the text area under SSH Public Keys.

Now you’re all set.

Using the SSH client

If you followed the previous steps you should now be able to connect to your Jenkins server using an ssh client:

ssh -l <jenkinsUserName> -p 2020 <jenkinsHost> <command>

To test this you can use help as <command>. This will print a list of supported commands.

To make this easier to use, you may want to create a jenkins bash file in your $PATH with contents like this:

#!/usr/bin/env bash

JENKINS_USER=adapt_me
JENKINS_PORT=2020
JENKINS_HOST=your.jenkins.hostname

ssh -l $JENKINS_USER -p $JENKINS_PORT $JENKINS_HOST "$@"

This will then allow you to invoke commands by using jenkins <arguments>.

Common use cases

I frequently use this to trigger certain builds. For example, for CrateDB we have a job that can build CrateDB from source and deploys it to a cluster which has monitoring and everything setup. To build the current branch I’m working on I’d push it and then run:

jenkins build crate_dev_release_and_deploy -f -v -p GIT_REVISION=$(git branch --show-current)

Another job that we have lets us compare the performance between two git revisions. I can trigger that like this:

jenkins build CrateDB/compare_version_performance_cluster -f -v -p CRATE_OLD=4.1.x -p CRATE_NEW="latest-nightly" -p SPEC=specs/order_by_no_limit.toml