Skip to content

Instantly share code, notes, and snippets.

@ansig
Created August 16, 2019 10:51
Show Gist options
  • Save ansig/2fd7c0ba02e79c7e3bde750b516855c6 to your computer and use it in GitHub Desktop.
Save ansig/2fd7c0ba02e79c7e3bde750b516855c6 to your computer and use it in GitHub Desktop.
Create Jenkins user API token
import hudson.model.User
import jenkins.security.ApiTokenProperty
def username = 'my-username'
def tokens = ['my-api-token']
user = User.get(username, false, Collections.emptyMap())
if (user == null) {
println "Did not find existing user '${username}', creating it..."
user = User.get(username, true, Collections.emptyMap())
} else {
println "Got existing user: ${user}"
}
def apiTokenProperty = user.getProperty(ApiTokenProperty.class)
def existingTokens = apiTokenProperty.getTokenList().collect { it.name }
tokens.each { tokenName ->
if (!(tokenName in existingTokens)) {
def newToken = apiTokenProperty.tokenStore.generateNewToken(tokenName)
println "Created new token named '${tokenName}': ${newToken.plainValue} (copy now because you cannot retrieve this any other way after this)"
} else {
println "Token named '${tokenName}' already exists"
}
}
user.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment