詹金斯当子句表现不符合预期时

时间:2018-07-26 21:24:22

标签: jenkins jenkins-pipeline

问题/问题概述

因此,我们面临的问题是,即使在“ hello”块中将PERSON设置为Jenkins先生,并且将CC仅设置为PERSON(因此是Jenkins先生),所以我们期望使用“何时进行测试”块运行,因为它将引用(“全局”)环境变量CC clang,并进入阶段,然后打印“ hello clang,此步骤已运行”。相反,它打印了“你好詹金斯先生,这一步就跑了”。这令人困惑,因为要进入该阶段,CC必须是叮当响的,而在回显语句中却印有詹金斯先生的名字。

Jenkins管道代码:

pipeline{
        agent any
        environment{
            CC = 'clang'
        }
        parameters{
            string(name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')       
        }
        stages{

            stage('hello'){
                options{
                    timestamps()
                }
                steps{

                    script{
                        def output = PERSON
                        CC = output
                    }
                    echo "hello ${CC}"
                }
            }
            stage('when test'){
                when{
                    environment name: 'CC', value: 'clang'
                }
                steps{
                    echo "hello ${CC}, this step ran"
                }
            }
        }
    }

输出:

[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (hello)
[Pipeline] timestamps
[Pipeline] {
[Pipeline] script
[Pipeline] {
[Pipeline] }
[Pipeline] // script
[Pipeline] echo
17:18:09 hello Mr Jenkins
[Pipeline] }
[Pipeline] // timestamps
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (when test)
[Pipeline] echo
hello Mr Jenkins, this step ran
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS   

1 个答案:

答案 0 :(得分:0)

我想'when'块工作正常,因为它们是名称为'CC'且值为'clang'的环境变量,您只需要回显正确的变量:

stage('when test'){
    when{
        environment name: 'CC', value: 'clang'
    }
    steps{
        echo "hello ${env.CC}, this step ran"
    }
}

另一种方法: 至于在“ when test”阶段中涉及到$ {CC}的问题,您已经在前一个阶段声明了一个全局变量,这使它在这里感觉到。您也可以通过链接“ hello”阶段来完成您想做的事情:

stage('hello'){
    steps{

        script{
            output = PERSON
            //CC = output
        }
        echo "hello ${output}"
    }
}
stage('when test'){
    when{
        environment name: 'CC', value: 'clang'
    }
    steps{
        echo "hello ${CC}, this step ran"
    }
}