Created
August 16, 2019 10:51
-
-
Save ansig/2fd7c0ba02e79c7e3bde750b516855c6 to your computer and use it in GitHub Desktop.
Create Jenkins user API token
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.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