Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
jenkins groovy get API token of a user

This is pretty simple snippet to get API Token of a user , lets say "MYUser" in jenkins.
its pretty useful when you are working with 'jenkins-job-builder' to update jobs in jenkins, and you need to get the api token which JJB needs inorder to update jobs to ..
run this code in either jenkins script console , or as i prefer, in form of init.groovy.
so when jenkins master starts, i create a user for JJb.
after that i get the token right away and pass it to my JJB jobs folder to file 'jenkins_jobs.ini' :)_ .

User u = User.get("Myuser")  
ApiTokenProperty t = u.getProperty(ApiTokenProperty.class)  
def token = t.getApiToken()
println "token is $token "

This comment has been minimized.

Copy link

@boaz0 boaz0 commented Sep 2, 2015

I might be wrong, but I had to import hudson.model.* too to resolve the "unable to resolve class User" error.


This comment has been minimized.

Copy link

@rjohnst rjohnst commented Feb 22, 2016

@ripcurld00d depends how you run it - from the script console hudson.model.* is imported for you. if you run via the CLI you have to import everything yourself


This comment has been minimized.

Copy link

@dadreggors dadreggors commented Mar 24, 2016

Sadly this returns 'Token is Hidden' (same as the Show API Token in user/config) for me.


This comment has been minimized.

Copy link
Owner Author

@hayderimran7 hayderimran7 commented Apr 21, 2016

you guys are right, this is masked in jenkins version above 1.596.2 . i was testing this with jenkins version 1.596.2


This comment has been minimized.

Copy link

@gezerk gezerk commented Oct 4, 2016

This works...def token = t.getApiTokenInsecure()

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