Srijani Ghosh
Srijani Ghosh

Reputation: 4216

How to access User API Token in Jenkins using groovy?

I need to access user details in Jenkins using groovy. This is how I am doing it.

cause = build.getCause(hudson.model.Cause.UserIdCause.class);
username = cause.getUserName()
User id = User.get(cause.getUserId())


println("user id :: "+ cause.getUserId())
println("user name :: "+ username)
println("email :: "+ id.getProperty(Mailer.UserProperty.class).getAddress())

But, I need the API token and password too which manually I can access in user -> configuration page. Is there any way to do it? Does Jenkins at all allow this?

Thanks!

Upvotes: 1

Views: 3119

Answers (1)

Srijani Ghosh
Srijani Ghosh

Reputation: 4216

I found a solution for this -

import hudson.model.*
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import hudson.model.AbstractProject
import hudson.tasks.Mailer
import hudson.model.User


cause = build.getCause(hudson.model.Cause.UserIdCause.class);
username = cause.getUserName()
User id = User.get(cause.getUserId())


println("user id :: "+ cause.getUserId())

println("user name :: "+ username)

println("email :: "+ id.getProperty(Mailer.UserProperty.class).getAddress())

println("API Token :: "+ id.getProperty(jenkins.security.ApiTokenProperty.class).getApiToken())

Upvotes: 2

Related Questions