如何在 Jenkins 声明式管道中执行 Groovy 语句?

时间:2021-01-10 03:15:17

标签: jenkins jenkins-pipeline

我希望能够定义一个变量,但声明式管道比脚本式管道更具限制性。我该怎么做?不管我把 String CMD = ... 语句放在哪里,我都会收到一个错误,这取决于我把它放在哪里。

pipeline {
    agent any
    environment {
        PATH = "/usr/local/bin:$PATH"
    }
    stages {
        // The pipeline will fail it can't find terraform
        stage("Check terraform") {
            steps {
                String CMD = (env.DESTROY.toBoolean ? "destroy" : "apply")
                // other steps
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您应该将代码包装到 script 函数中 https://www.jenkins.io/doc/book/pipeline/syntax/#script 或在 pipeline {

之前声明您的变量
pipeline {
    agent any
    environment {
        PATH = "/usr/local/bin:$PATH"
    }
    stages {
        // The pipeline will fail it can't find terraform
        stage("Check terraform") {
            steps {
               script {        
                  String CMD = (env.DESTROY.toBoolean ? "destroy" : "apply")
               }
                  // other steps
            }
        }
    }
}