0

Are there any REST APIs exposed by Jenkins to create and delete a user?

Andrew Gray
  • 3,593
  • 3
  • 35
  • 62
Madhu Avinash
  • 933
  • 2
  • 8
  • 27

2 Answers2

3

As Andrew said in his answer there's no way to easily do it via REST API. I'm currently facing the same problem and came up with some kind of web scraping. This is required as Jenkins eventually expects a Jenkins-Crumb to be supplied via the user deletion POST request.

Whenever you want to People > Click on User Id > Delete a user, you have to confirm that you really want to delete that user. Besides that obvious Yes button there are some hidden form fields where one of those is named Jenkins-Crumb. When you click the Yes button the value of that field is sent with the /doDelete POST request.

The solution I came up with is reading the Jenkins-Crumb after GETting https://<your-jenkins-url>/user/<username-to-delete>/delete and then do a POST request to https://<your-jenkins-url>/user/<username-to-delete>/doDelete with the Jenkins-Crumb supplied as form data. While the Jenkins-Crumb form field is populated via JavaScript, there's no need to execute the JavaScript as the script is directly included as <script>crumb.init("Jenkins-Crumb", "jenkins-crumb-value");</script> into the HTML source where it can be matched via RegEx.

In Python this could look like

import re, requests, sys

with requests.Session() as s:
    s.auth = (ADMIN_USERNAME, ADMIN_APIKEY_OR_PASSWORD)
    url = "https://YOUR_JENKINS_URL/user/USER_TO_DELETE/delete"
    response = s.get(url)

    if not response.ok:
        sys.exit("HTTP error {} while accessing Jenkins at {}. Exiting.".format(response.status_code, url))

    re_match = re.search(r'<script>crumb\.init\("Jenkins-Crumb", "(\w+)"\);<\/script>', response.text)
    if not re_match:
        sys.exit("Couldn't get required Jenkins-Crumb. Exiting.")

    jenkins_crumb = re_match.group(1)

    url = "https://YOUR_JENKINS_URL/user/USER_TO_DELETE/doDelete"
    data = { "Jenkins-Crumb": jenkins_crumb }
    response = s.post(url, params=data)

    if not response.ok:
        sys.exit("Couldn't delete user")

    s.close()
marcelbrueckner
  • 367
  • 1
  • 3
  • 14
0

Currently no. Many pages, but not all pages in Jenkins expose json (that can be consumed) by adding api/json to the end of the Jenkins URL.

The Security related pages in Jenkins are not currently part of the REST API.

That said yesterday (as I write this answer) the Role Strategy Plugin has released version 2.90 that adds some REST API capability.

Maybe this is the start of more.

Andrew Gray
  • 3,593
  • 3
  • 35
  • 62