Programmatically retrieve Jenkins REST API Token
tl;dr: Programmatically retrieve REST API Token that can authenticate the other Jenkins API’s.
Jenkins has become the open source standard automation server for managing the dev side of Devops, from source code management to delivering code to production. Jenkins provides hundreds of plugins to support building, deploying and automating any project.
Similar to other popular services, Jenkins also provides REST API that can be used to perform various functions.
The API’s allow two modes of authentication, namely,
1. Add the Jenkins username and password as parameters.
2. Authenticate using API Token
In this article, we will look as to how we can retrieve the Jenkins REST API Token programmatically. We can then use this token can for authenticating to the other Jenkins API’s.
Jenkins API does not have an endpoint for retrieving the API Token. The API token is available when a user logs in to Jenkins & then navigates to “http://<your-jenkins-url>/me/configure”.
To retrieve the token programmatically, first, we have to call the configure API (HTTP://<your-jenkins-url>/me/configure) and then parse the HTML response. Below is an example of how we can achieve the same in Typescript.
I have used the request npm package for making the request (with SSL certificate if required), and cheerio for parsing the HTML response.
The same can also be achieved using curl, as shown below.
In the upcoming stories, we will use this token to invoke certain Jenkins functionalities.
As always, you are more than welcome to ask me questions or give me feedback.
Thanks for reading 💙