Gawain
Gawain

Reputation: 1092

Can I access current stage id in Jenkins pipeline?

I'm using shared library to build CI/CD pipelines in Jenkins. And in my case, some of the stages need to send the execute info through web apis. In this case, we need to add stage id for current stage to api calls.

How can I access the stage id similar with ${STAGE_NAME}?

Upvotes: 0

Views: 1713

Answers (2)

GloomyDay
GloomyDay

Reputation: 33

Questiion is old but i found the solution: use some code from pipeline-stage-view-plugin( looks like it is already installed in jenkins by default)

we can take current job ( workflowrun ) and pass it as an argument to

com.cloudbees.workflow.rest.external.RunExt.create , and whoala: we have object that contains info about steps and time spent on it's execution.

Full code will looks like this:

import com.cloudbees.workflow.rest.external.RunExt
import com.cloudbees.workflow.rest.external.StageNodeExt

def getCurrentBuildStagesDuration(){
  LinkedHashMap stagesInfo = [:]
  def buildObject = com.cloudbees.workflow.rest.external.RunExt.create(currentBuild.getRawBuild())
  for (StageNodeExt stage : buildObject.getStages()) {
    stagesInfo.put(stage.getName(), stage.getDurationMillis())
  }
  return stagesInfo
}

Function will return {SomeStage1=7, SomeStage2=1243, SomeStage3=5}

Tested with jenkins shared library and Jenkins 2.303.1

Hope it helps someone )

Upvotes: 0

Marat
Marat

Reputation: 161

I use Pipeline REST API Plugin as well as HTTP Request Plugin

Your methods in Jenkinsfile can look like:

@NonCPS
def getJsonObjects(String data){
    return new groovy.json.JsonSlurperClassic().parseText(data)
}

def getStageFlowLogUrl(){
    def buildDescriptionResponse = httpRequest httpMode: 'GET', url: "${env.BUILD_URL}wfapi/describe", authentication: 'mtuktarov-creds'
    def buildDescriptionJson = getJsonObjects(buildDescriptionResponse.content)
    def stageDescriptionId = false

    buildDescriptionJson.stages.each{ it ->
        if (it.name == env.STAGE_NAME){
            stageDescriptionId = stageDescription.id
        }
    }
return stageDescriptionId
}

Upvotes: 1

Related Questions