18

I was wondering if I can create a new user in Jenkins using its API. I can create jobs but the API docs for Jenkins don't have anything related to user creation.

Actually, I have to create a new user followed by creating a new job for that user, all of this using an API.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
shubham
  • 547
  • 2
  • 6
  • 20

5 Answers5

19

You're right, there is no explicit CLI command for adding a user. But you could use groovy script for this (using the CLI for execution).

The details depend on how your Jenkins is configured. For example, if your Jenkins uses its own user database, then you could add a new user by the following CLI call:

echo 'jenkins.model.Jenkins.instance.securityRealm.createAccount("user1", "password123")' |
java -jar jenkins-cli.jar -s http://localhost/ groovy =

This shell command will create a new user with login "user1" and password "password123". Here echo feeds a line of groovy code to a Jenkins CLI (note that = means that CLI should receive code from STDIN).

Also groovy script allows to manage user permissions, however, the exact code depends on what authorization strategy is used. You could use this sample script as a start.

phs
  • 10,687
  • 4
  • 58
  • 84
izzekil
  • 5,781
  • 2
  • 36
  • 38
  • 2
    Make sure you're using _Jenkins’ own user database_ as authentication method (_security realm_), otherwise it won't work. – kenorb Nov 07 '17 at 12:50
9

This is how to create user after installation:

echo 'jenkins.model.Jenkins.instance.securityRealm.createAccount("user", "password")' | java -jar jenkins-cli.jar -auth admin:c3a5dcd6bc3f45ee8d6c9f0f5abc14c0 -s http://localhost:8080/ groovy =

Where c3a5dcd6bc3f45ee8d6c9f0f5abc14c0 is automatically generated password present in log or in file (for ubuntu): /var/lib/jenkins/secrets/initialAdminPassword

vitaleek
  • 91
  • 1
  • 1
  • this is a really concise and straightforward method. Do you happen to know how to use this to enable security (realm and authorization)? e.g. jenkins own database, and 'logged in users can do anything' – ffghfgh Jun 21 '17 at 16:23
6

echo and pipe didn't work on my Windows, so I ended up using a script file instead. It's also easier to add more logic in the script file. The script below will check existing user before adding a new user, and then set the user's email after account creation and give READ access using Matrix-based security. You can run it by saving the script into a file, say user-creation.groovy, and then run the following,

java -jar jenkins-cli.jar -s http://localhost/ groovy user-creation.groovy testUser testPassword testEmail@testEmail.com

import hudson.model.*
import hudson.security.*
import hudson.tasks.Mailer

def userId = args[0]
def password = args[1]
def email = args[2]
def instance = jenkins.model.Jenkins.instance
def existingUser = instance.securityRealm.allUsers.find {it.id == userId}

if (existingUser == null) {
    def user = instance.securityRealm.createAccount(userId, password)
    user.addProperty(new Mailer.UserProperty(email));

    def strategy = (GlobalMatrixAuthorizationStrategy) instance.getAuthorizationStrategy()
    strategy.add(Hudson.READ, userId)
    instance.setAuthorizationStrategy(strategy)
    instance.save()
} 
kenorb
  • 155,785
  • 88
  • 678
  • 743
barryku
  • 2,496
  • 25
  • 16
  • 1
    if i run the command `java -jar jenkins-cli.jar -s http://localhost:8080/ groovy user-creation.groovy userName userPassword testEmail@testEmail.com`, I am getting an error as `ERROR: anonymous is missing the Overall/Read permission` – Alla Sasikanth Jan 18 '17 at 18:22
  • this worked for me. java -jar jenkins-cli.jar -s http://localhost/ groovy user-creation.groovy testUser testPassword testEmail@gmail.com --username= --password= – Upen Oct 04 '17 at 23:44
4

I managed to get the following python snippet to create a user with ssh-key:

import json
import requests

def main():
    data = {
        'credentials': {
            'scope': "GLOBAL",
            'username': "jenkins",
            'privateKeySource': {
                'privateKey': "-----BEGIN RSA PRIVATE KEY-----\nX\n-----END RSA PRIVATE KEY-----",
                'stapler-class': "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource"
            },
            'stapler-class': "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey"
        }
    }

    payload = {
        'json': json.dumps(data),
        'Submit': "OK",
    }
    r = requests.post("http://%s:%d/credential-store/domain/_/createCredentials" % (HOSTNAME, 8080), data=payload)
    if r.status_code != requests.codes.ok:
        print r.text

It is sort of like a REST interface except that one has to know the internals of the code and the names of the classes that the objects are supposed to decode to.

I'm trying to configure jenkins from an ansible script (running externally to the jenkins server); since the java cli doesn't support creating the credentials the python snippet seems the way to go.

Pedro Marques
  • 2,642
  • 1
  • 10
  • 10
  • Hi Pedro, is there any way to create user using python? your above code will create credential, I am looking for user. – Nilesh Jan 19 '18 at 02:06
1

Building on @vitaleek's answer the following will grab the default admin credentials from the file and create a new user:

pass=`sudo cat /var/lib/jenkins/secrets/initialAdminPassword` && echo 'jenkins.model.Jenkins.instance.securityRealm.createAccount("user1", "password123")' | sudo java -jar jenkins-cli.jar -auth admin:$pass -s http://localhost:8080/ groovy =

If you're like me and you couldn't find the jenkins-cli.jar at first, that can be pulled from your Jenkins server as follows:

curl -O http://127.0.0.1:8080/jnlpJars/jenkins-cli.jar
Doug
  • 6,446
  • 9
  • 74
  • 107