Jenkins plugin - how to get currently executing job?

Viewed 1035

I am building a jenkins pipeline plugin (methods to be invoked from a pipeline) and need to get retrieve information about the currently running job, which invoked my methods.

There are a couple of questions I found talking about it, for example here - Jenkins Plugin How to get Job information.

Yet I can't figure out how to use this information. I do have access to the Jenkins instance, but don't have any info about the current project, job, build, etc. How can I get hold of that info?

Note, this is a pipeline steps plugin, there is no perform method in it.

1 Answers

Ok, after search, I finally found the answer in the most obvious of all places - documentation for writing pipeline steps plugins and the corresponding API documentation.

The way to do it is from the Execution class. Inside it, just call getContext(), which returns StepContext, which then has .get method to get the rest of the things you need:

public class MyExecution extends SynchronousNonBlockingStepExecution<ReturnType> {
    ...

    @Override
    protected ReturnType run() throws Exception {
        try {
            StepContext context = getContex();

            // get currently used workspace path
            FilePath path = context.get(FilePath.class);

            //get current run
            Run run = context.get(Run.class);

            // ... and so on ...
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    ...
}
Related