Triggering Jenkins Jobs using REST calls

prakash vadrevu
3 min readSep 7, 2017

--

Source: Google

In one of the projects I worked upon, there was a requirement of building a binary file with inputs from the user.

We couldn’t do this on our regular API servers because of two main reasons

  • One - It had some tool-chain dependencies
  • Two - It consumed good number of resources

One more thing was that it wasn’t a frequent task to be executed.

This led us to consider Jenkins (which was already setup as our CI)to build it for us. The idea was to setup a local PC with the required toolchains and add it as a slave to our Jenkins master machine. Then, trigger the job to be built on that machine. Sounded easy and interesting!

We knew that Jenkins jobs can be triggered via REST calls, but we never really explored that path before. So, I rolled up my sleeves and jumped onto work this out. This post is a collection of my experiments and findings during working on this task.

Setting up a new user

Using our regular Jenkins Admin user’s credentials (which has full set of permissions) to trigger a job via URL is not a good security practice. So, I have created a new user with a very restricted set of permissions. After some experiments and trials, I concluded that only one permission wasenough for it to work and that was

  • Job — Build

This worked for me because, I want my API server to just trigger the build with the user’s input as build parameters.

Enabling the Job trigger via REST

Now the user to trigger the build was setup, I had to configure the Jenkins Job to be triggered via a REST call.

For this, I have enabled the option “Trigger builds remotely (e.g., from scripts)” under
JOB -> configure -> Source Code Management -> Build Triggers
and used a random String as authentication token as shown here

Configuring Build Triggers to invoke a Jenkins Job via REST

Using the URL shown in the image above, we can now make the REST calls to trigger the build, like

http://<JENKINS_USER>:<PASSWORD>@<JENKINS_HOST>/view/All/job/Init-By-Rest-Test/build?token=KOq2nWmzbIjfbh2p3tTKEn0cgsi9Tzop

Passing Build Parameters

The only pending part now was to pass the build params to the Job. For this, I have enabled the option “This project is parameterized” under
JOB -> configure -> General

Configuration to enable Build Params for a Jenkins Job

Once this is configured, Jenkins build accepts the specified config params and sets them as the environment variables in the build environment.

Wrapping up

Since I got all the pieces figured out, my final URL to trigger this Job was

http://<JENKINS_USER>:<PASSWORD>@<JENKINS_HOST>/view/All/job/Init-By-Rest-Test/build?token=KOq2nWmzbIjfbh2p3tTKEn0cgsi9Tzop&VERSION=123

Thats it! Mission Accomplished!

--

--