Wojtas.Zet
Wojtas.Zet

Reputation: 816

jenkins pipeline - parameter from function - Required context class hudson.FilePath is missing

I am trying to pass return value of a function as parameter.

@NonCPS
def getLastRelease() {
    def RES = sh(script: '''cat version''', returnStdout: true).trim()
    return RES
}
pipeline{
    parameters {
            choice(name: 'RELEASE_VERSION', choices: '${getLastRelease()}', description: 'desc')
        }
}

But for some reason it does not work - if i try:

'${getLastRelease()}'

I am getting error:

durable-73075a87/script.sh: line 1: ${getLastRelease()}: bad substitution

if i use:

"${getLastRelease()}"

I am getting error:

[Pipeline] Start of Pipeline [Pipeline] sh [Pipeline] End of Pipeline org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing Perhaps you forgot to surround the code with a step that provides this, such as: node, dockerNode

Upvotes: 1

Views: 9080

Answers (1)

Dibakar Aditya
Dibakar Aditya

Reputation: 4203

You need this:

  1. Remove the annotation @NonCPS, since NonCPS functions should not use Pipeline steps internally.
  2. Since you execute shell scripts, wrap the expressions in your function in a node {...} block.
  3. Simply invoke the function getLastRelease() inside the choice the parameter without the quotes or the curly braces.

Working sample:

def getLastRelease() {
    node {
        def RES = sh (script: 'cat version', returnStdout: true).trim()
        return RES
    }
}
pipeline {
    agent any
    parameters {
        choice(name: 'RELEASE_VERSION', choices: [getLastRelease(), <more choices, ...>], description: 'desc')
    }
}

Upvotes: 2

Related Questions