Created
August 1, 2019 04:33
-
-
Save Genzer/339f4c305ddcd85172f96425c667ab77 to your computer and use it in GitHub Desktop.
Create new Jenkins user using RoleBasedStrategy and Groovy script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage via Jenkins API: