Jenkins is a powerful automation server that organizations widely use to automate various tasks, such as building and deploying software. In addition, Jenkins provides an API token to authenticate a user and grant them access to the Jenkins API. Further, using the API token, we can create, manage, query, and access build artifacts.
In this tutorial, we'll learn to generate and use an API token in Jenkins.
2. Generate an API Token
In order to access the Jenkins API, users need to authenticate themselves with an API token. The API token serves as an identifier for authentication purposes with Jenkins. It is often used to allow third-party applications or scripts to interact with Jenkins, such as triggering builds or accessing build artifacts. Jenkins administrators can create and manage access tokens to grant access to specific API resources.
In order to generate an API token in Jenkins, we need to follow these steps:
- Log in to the Jenkins instance as an administrator
- Click on “Manage Jenkins” in the Jenkins dashboard
- Click on the “Manage Users“
- Select the user we want to generate an API token for and click on their name to access their user configuration page
- Generate a token using the “Add new token” section of the user configuration page
- Click on the “Copy” button to copy the token to the clipboard
- Save the configurations
The entire process is visible in GUI below:
Once we've got the API token, we can use it to authenticate requests to Jenkins. We can use the token to trigger builds or access build artifacts when accessing the Jenkins remote API. Additionally, it is important to keep the API token secure and not share it with anyone who should not have access to our Jenkins account. It is recommended to periodically rotate our API token to reduce security risks.
3. Using the API Token
So far, we've successfully generated the API token for a Jenkins user. We can use the Jenkins remote access API to trigger a job or update the configuration of jobs. This can be useful for automating the configuration process or integrating Jenkins with other systems.
To demonstrate, we'll trigger a build by sending an HTTP POST request to the /build endpoint of our Jenkins server. The request will include the API token along with the other parameters.
Let's look at the request to trigger a Jenkins job using the API token key:
$ curl -X POST http://18.104.22.168:8080/job/testJob/build --user testuser:1100a338c975eb40189c3fe2cf580b2bdf
In the above request to run a remote job, we've provided Jenkins URL, job name, and user name with an access token key.
In this article, we demonstrated how to generate and use an API token in Jenkins.
First, we learned to generate an API token for a Jenkins user. After that, we triggered a job remotely using the same token key.