Pranit Das
Pranit Das

Reputation: 11

Retrieve jenkins job builder credentials in groovy

I am trying to extract the username and password in jenkins groovy script who has initiated the build. I need these details to post comments on jira from my name. So for eg.. I login into jenkins and start a job, then my login credentials should be used to post the comment on jira.. I tried alot of posts but didnt find anytihng related to my requirement. Any help will be appreciated..

Upvotes: 0

Views: 708

Answers (1)

xxxvodnikxxx
xxxvodnikxxx

Reputation: 1277

after few seconds of Googling, I found this script officially published by cloudbees.

So, as follows:

Jenkins.instance.getAllItems(Job).each{

  def jobBuilds=it.getBuilds()

    //for each of such jobs we can get all the builds (or you can limit the number at your convenience)
    jobBuilds.each { build ->
      def runningSince = groovy.time.TimeCategory.minus( new Date(), build.getTime() )
      def currentStatus = build.buildStatusSummary.message
      def cause = build.getCauses()[0] //we keep the first cause
      //This is a simple case where we want to get information on the cause if the build was 
      //triggered by an user
      def user = cause instanceof Cause.UserIdCause? cause.getUserId():""
      //This is an easy way to show the information on screen but can be changed at convenience
      println "Build: ${build} | Since: ${runningSince} | Status: ${currentStatus} | Cause: ${cause} | User: ${user}" 

      // You can get all the information available for build parameters.
      def parameters = build.getAction(ParametersAction)?.parameters
      parameters.each {
        println "Type: ${it.class} Name: ${it.name}, Value: ${it.dump()}" 

        }
    }
}

You will get the user ID of the user, which start the job, for sure you will not be able to get his credentials, at least not in the plain text.

Little explanation

//to get all jobs
Jenkins.instance.getAllItems(Job)
{...}
//get builds per job
def jobBuilds=it.getBuilds()
//get build cause
def cause = build.getCauses()[0] //we keep the first cause
//if triggered by an user get id, otherwise empty string
def user = cause instanceof Cause.UserIdCause? cause.getUserId():""

Upvotes: 0

Related Questions