简体   繁体   English

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

[英]How to execute Groovy statements in a Jenkins declarative pipeline?

I want to be able to define a variable, but declarative pipelines are more restrictive than scriptive pipelines.我希望能够定义一个变量,但声明式管道比脚本式管道更具限制性。 How can I do it?我该怎么做? It doesn't matter where I put the String CMD =... statement, I get an error, which varies depending on where I put it.我将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
            }
        }
    }
}

You should wrap your code into script function https://www.jenkins.io/doc/book/pipeline/syntax/#script or declare your variable before pipeline {您应该将代码包装到script function pipeline { ://www.jenkins.io/doc/book/pipeline/syntax/#script或声明您的变量之前

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
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM