Getting the Workspace path on controller from Jenkins Library

We are trying to read pipeline metadata, which is branch specific, when our pipelines start. We have a Jenkins Library to which we want to add a new call that will read a yaml file.

We can read that from a Stage, but it is inefficient for various reasons (our agents are ephemeral to save on AWS cost), and if we run a stage on the Controller it becomes a security risk, as anyone that can run a pipeline will have access to the controller.

Unfortunately WORKSPACE does not seem to be populated until running from a stage, and getting the actual folder does not seem to be trivial. This is especially tricky since we want to be compatible with pipelines that would run in parallel where there can be more than one workspace folder for the same pipeline.

import hudson.EnvVars

def call() {
    envVars = getContext(EnvVars)
    echo "Workspace: ${envVars.WORKSPACE}"
}

We always get null outside of an actual stage and env.WORKSPACE is not working either.

The good news is that envVars does contain data we would need such as BRANCH, BUILD_NUMBER, BUILD_ID, JENKINS_HOME, JOB_NAME, but that’s not sufficient for our needs.

After some trial and error calling readTrusted() could be an option but in our case it adds 7s or more to our pipelines launch and can cause our controllers to run out of memory due to the git processes running in parallel if too many pipelines are launched at the same time.

We decided to settle on making an http call to raw.githubusercontent.com, which was tricky since the method making the http call has to be annotated with @NonCPS in order to work.

Being able to read the file that is already present in the controller’s workspace directory would be the most efficient, but getting that information will take a lot of investigation.