Answer a question

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

Answers

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')
    }
}
Logo

CI/CD社区为您提供最前沿的新闻资讯和知识内容

更多推荐