Created
February 7, 2019 10:38
-
-
Save gentoomaniac/90d089860b5f83139e0fba85d72d4eeb to your computer and use it in GitHub Desktop.
Create new style api tokens in jenkins via 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 jenkins.model.User | |
import jenkins.security.ApiTokenProperty | |
import jenkins.security.apitoken.ApiTokenStore | |
def env = System.getenv() | |
// get the user object | |
User jjbUser = User.get(env.JENKINS_USER_NAME) | |
// Verify that it has a ApiTokenProperty and create one if not (not sure if required, playing save here) | |
ApiTokenProperty tokenprop = jjbUser.getProperty(ApiTokenProperty.class) | |
if (!tokenprop){ | |
tokenprop = new ApiTokenProperty() | |
jjbUser.addProperty(tokenprop) | |
} | |
// generate the actual new token (not a legacy one), the only parameter is the description that shows in jenkins | |
// the returned object has only two properties, tokenUuid and plainValue | |
ApiTokenStore.TokenUuidAndPlainValue token = tokenprop.tokenStore.generateNewToken(env.JENKINS_USER_NAME + "-token") | |
// save everything (again not sure if required) | |
jjbUser.save() | |
// do whatever you must with the token. | |
// keep in mind that you won't be able to recover it if lost. | |
// Jenkins only saves hashes of new style tokens | |
println token.plainValue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This piece of poop took me way too much time to figure out. So I hope others might find it here and it'll help you to save time.
All code I encountered while searching is using legacy tokens. The jenkins code for it is deprecated.