jenkinsgroovycicd

Jenkins script reference parameters as params.parameterName or just parameterName?


In Jenkins, how to decide whether we need to reference parameters as params.parameterName or just parameterName on the scripting context within the pipeline?

For example in the following script:

def sonarAnalysisFn(sonarAnalysis) {
    if (sonarAnalysis == true) {  
        echo "Sonar analysis is running"
    } else {
        echo "Skipping Sonar Analysis"
    }
}

node {
    properties([
        parameters([
            string(name: 'name', defaultValue: 'World', description: 'Enter your name'),
            booleanParam(defaultValue: true, description: 'Untick if you want to skip Sonar analysis', name: 'sonarAnalysis')
        ])
    ])
    
    stage('Greet') {
        echo "Hello, ${name}"  // Explicitly using params.name
    }
    
    stage('Sonar Analysis') {
        sonarAnalysisFn(sonarAnalysis)
    }
}

I have passed both name and sonarAnalysis parameters directly, but only the name is passed from the input. sonarAnalysis always pass the True (default value).

But when I use params.sonarAnalysis, it works just fine.

So I jut need to know, when does jenkins consider whether it is a passed parameter or not?


Solution

  • In scripted pipeline the parameters should always be used as params.parameterName. Refer here.

    If variables are not referred as this, there are chances one can get incorrect/unexpected output.

    In the case in example above, if one prints the class type of the variable boolean.

    println sonarAnalysis.getClass()
    

    The output will be

    class java.lang.String
    

    Meaning the condition for the if will need to be changed. Something as follows:

        if (sonarAnalysis.toBoolean() == true) {  
            echo "Sonar analysis is running"
        } else {
            echo "Skipping Sonar Analysis"
        }
    

    This change would need to be done, to consistently get the correct results from the parameters.