jenkinsjenkins-pipelinejenkins-shared-libraries

Passing environment variable as a pipeline parameter to Jenkins shared library


I have a shared Jenkins library that has my pipeline for Jenkinsfile. The library is structured as follows:

myPipeline.groovy file

def call(body) {
    def params= [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = params
    body()

    pipeline {
        // My entire pipeline is here
        // Demo stage
        stage("Something"){
          steps{
            script{
              projectName = params.name
            }
          }
        }

    }
}

And my Jenkinsfile is as follows:

Jenkinsfile

@Library("some-shared-lib") _
myPipeline{
    name = "Some name"
}

Now, I would like to replace "Some name" string with "env.JOB_NAME" command. Normally in Jenkinsfile, I would use name = "${env.JOB_NAME}" to get the info, but because I am using my shared library instead, it failed to work. Error message is as follows:

java.lang.NullPointerException: Cannot get property 'JOB_NAME' on null object

I tried to play around with brackets and other notation but never got it to work. I think that I incorrectly pass a parameter. I would like Jenkinsfile to assign "${env.JOB_NAME}" to projectName variable, once library runs the pipeline that I am calling (via myPipeline{} command)


Solution

  • You can do like this in myPipeline.groovy:

    def call(body) {
        def params= [:]
        body.resolveStrategy = Closure.DELEGATE_FIRST
        body.delegate = params
        body()
    
        pipeline {
            // My entire pipeline is here
            // Demo stage
            stage("Something"){
              steps{
                script{
                  projectName = "${env.JOB_NAME}"
                }
              }
            }
    
        }
    }