Skip to content

Instantly share code, notes, and snippets.

@Genzer
Created August 1, 2019 04:33
Show Gist options
  • Save Genzer/339f4c305ddcd85172f96425c667ab77 to your computer and use it in GitHub Desktop.
Save Genzer/339f4c305ddcd85172f96425c667ab77 to your computer and use it in GitHub Desktop.
Create new Jenkins user using RoleBasedStrategy and Groovy script
import hudson.model.*
import hudson.security.*
import hudson.tasks.Mailer
import com.michelin.cio.hudson.plugins.rolestrategy.*
/*
* This snippet is inspired from a StackOverflow question and answer.
* https://stackoverflow.com/questions/17716242/creating-user-in-jenkins-via-api
*/
def userId = args[0]
def role = args[2]
def password = args[3]
def email = args[4]
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 = (RoleBasedAuthorizationStrategy) instance.getAuthorizationStrategy()
// See doAssignRole method in here
// https://github.com/jenkinsci/role-strategy-plugin/blob/master/src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleBasedAuthorizationStrategy.java
strategy.doAssignRole("globalRoles", "developers", userId)
instance.setAuthorizationStrategy(strategy)
instance.save()
println "saved!"
}
@Genzer
Copy link
Author

Genzer commented Mar 1, 2022

Usage via Jenkins API:

$ curl -u "$JENKINS_USERNAME:$JENKINS_API_TOKEN" https://jenkins.example.org/scriptText -d "script=$(< CreateJenkinsUser.groovy)"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment