Skip to content

Jenkins REST API Usage Example

homepage-banner

Introduction

Jenkins is an open-source automation server that is widely used for building, testing, and deploying software. It provides various APIs that allow developers to interact with Jenkins programmatically. One of the most important APIs that Jenkins provides is the REST API. In this blog post, we will discuss the Jenkins REST API and demonstrate how to use it to perform various tasks.

1. Run job

a. Job with no parameter

curl -XPOST <http://IP:8080/jenkins/job/plugin%20demo/build> --user admin:admin

b. Job with parameter

  • b-1. Using default parameters
curl -XPOST <http://IP:8080/jenkins/job/commandTest/buildWithParameters> --user admin:admin
  • b-2. Set parameter method 1
curl -XPOST <http://IP:8080/jenkins/job/commandTest/buildWithParameters> -d port=80
  • b-3. Set parameter method 2
curl -XPOST <http://IP:8080/jenkins/job/commandTest/buildWithParameters> -d port=80 \
    --data-urlencode json='"{\"parameter\": [{\"name\": \"port\", \"value\": \"80\"}]}"'
  • b-4. Multiple parameters
curl -XPOST <http://IP:8080/jenkins/job/commandTest/buildWithParameters> \
     -d param1=value1&param2=value

2. Create job

a. Directory needs to be created

  1. Create job directory: ~/.jenkins/jobs/jobfromcmd
  2. Create config.xml file (can be copied from other projects)
  3. Run command
curl -XPOST <http://IP:8080/jenkins/createItem?name=jobfromcmd> --user admin:admin \
     --data-binary "@config.xml" -H "Content-Type: text/xml"

b. Directory does not need to be created

  1. Create config.xml file (can be copied from other projects)
  2. Run command (in the same directory as config.xml)
curl -XPOST <http://IP:8080/jenkins/createItem?name=jobfromcmd> --user admin:admin \
     --data-binary "@config.xml" -H "Content-Type: text/xml"

3. Delete job

curl -XPOST <http://IP:8080/jenkins/job/jobfromcmd/doDelete>

4. Check job status

curl -XGET <http://IP:8080/job/JOB_NAME/lastBuild/api/json>

5. Disable job

curl -XPOST --data disable <http://IP:8080/job/JOBNAME/disable>

6. Get job build number

curl -XGET <http://IP:8080/job/JOB_NAME/lastBuild/buildNumber>

7. Get the build number of the most recent successful build

curl -XGET <http://IP:8080/job/JOB_NAME/lastStableBuild/buildNumber>

Conclusion

In conclusion, the Jenkins REST API is a powerful tool that allows developers to interact with Jenkins programmatically. It provides various APIs that enable developers to perform various tasks, including triggering builds, retrieving build logs, creating and deleting jobs, and configuring nodes. In this blog post, we demonstrated how to use the Jenkins REST API to retrieve build logs for a particular build. We hope this blog post has provided you with a better understanding of the Jenkins REST API and how to use it in your projects.

Reference

  • https://www.jenkins.io/doc/book/using/remote-access-api/
  • https://jenkinsapi.readthedocs.io/en/latest/
Leave a message