简体   繁体   中英

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.

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 {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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