groovy 无法进入Jenkinsfile中If Else条件的“else”块

u3r8eeie  于 2022-11-01  发布在  Jenkins
关注(0)|答案(1)|浏览(262)

在运行下面的代码时,我将进入字符串比较部分的else块。
但无法进入else块的布尔比较部分。

pipeline {
    agent any

    parameters{

        string(
                name: "s_Project_Branch_Name", defaultValue: "master",
                description: "Enter Brnach Name")
    }

    stages {
        stage('Example') {
            input {
                message "Proceed to Prod Deployment with ${params.s_Project_Branch_Name} branch?"
                ok "Yes"
                parameters {
                    string(name: 'PERSON', defaultValue: 'master', description: 'Who should I say hello to?')
                    booleanParam(name: "TOGGLE", defaultValue: false, description: "Check this box to Proceed.")
                }
            }
            steps {
                // echo "Hello, ${PERSON}, nice to meet you."

                script{
                    echo 'String'
                    if ("${PERSON}" == "${params.s_Project_Branch_Name}") {
                        echo 'I only execute on the master branch'
                    } else {
                        echo 'I execute elsewhere'
                        currentBuild.result = "FAILURE"
                    }
                }

                script{
                    echo 'Boolean'
                    echo "${TOGGLE}"
                    if ("${TOGGLE}") {
                        echo 'I only execute if boolean true'
                    } else {
                        error('I only execute if boolean false')
                        currentBuild.result = "FAILURE"
                    }
                }
            }
        }
    }
}
bjp0bcyl

bjp0bcyl1#

当你执行字符串插值"${TOGGLE}"时,你将得到一个字符串,而不是布尔值。如果你想得到布尔值,你可以通过params.TOGGLE直接访问变量。所以像下面这样改变条件。

if (params.TOGGLE) {
    echo 'I only execute if boolean true'
} else {
    error('I only execute if boolean false')
    currentBuild.result = "FAILURE"
}

if ("${TOGGLE}" == "true") {
    echo 'I only execute if boolean true'
} else {
    error('I only execute if boolean false')
    currentBuild.result = "FAILURE"
}

相关问题