【问题标题】:Jenkins pipeline undefined variableJenkins管道未定义变量
【发布时间】:2017-10-18 09:11:19
【问题描述】:

我正在尝试构建一个参数为的 Jenkins 流水线 可选:

parameters {
    string(
        name:'foo',
        defaultValue:'',
        description:'foo is foo'
    )
}

我的目的是调用一个 shell 脚本并提供 foo 作为参数:

stages {
    stage('something') {
        sh "some-script.sh '${params.foo}'"
    }
}

如果提供的值为空,shell 脚本将执行 Right Thing™ 字符串。

不幸的是,我不能只得到一个空字符串。如果用户不提供 foo 的值,Jenkins 会将其设置为 null,我将得到 null (作为字符串)在我的命令中。

我找到了this related question,但唯一的答案并没有真正的帮助。

有什么建议吗?

【问题讨论】:

  • 使用 shell 的快速解决方法:sh "some-script.sh $([[ '${params.foo}' == 'null' ]] && echo '' || echo ${params.foo})"
  • 谢谢@Razvan。 为了记录,我把东西写成一个 shell 脚本只是为了发现我仍然需要为它做一些黑客和不可读的东西。总的来说,我认为可编写脚本的管道是一个好主意,但 Jenkins 确实存在问题,即使它试图变得体面……Facepalm

标签: jenkins-pipeline


【解决方案1】:

在这里,OP 意识到包装脚本可能会有所帮助……我讽刺地称它为 junkins-cmd,我这样称呼它:

stages {
    stage('something') {
        sh "junkins-cmd some-script.sh '${params.foo}'"
    }
}

代码:

#!/bin/bash

helpme() {
cat <<EOF
Usage: $0 <command> [parameters to command]

This command is a wrapper for jenkins pipeline. It tries to overcome jenkins
idiotic behaviour when calling programs without polluting the remaining part
of the toolkit.

The given command is executed with the fixed version of the given
parameters. Current fixes:

 - 'null' is replaced with ''
EOF
} >&2

trap helpme EXIT
command="${1:?Missing command}"; shift
trap - EXIT

typeset -a params
for p in "$@"; do

    # Jenkins pipeline uses 'null' when the parameter is undefined.
    [[ "$p" = 'null' ]] && p=''

    params+=("$p")
done

exec $command "${params[@]}"

注意:prams+=("$p") 似乎不能在 shell 之间移植:因此这个丑陋的脚本正在运行 #!/bin/bash

【讨论】: