简体   繁体   中英

No such DSL method 'when' found among steps in Jenkinsfile

I want to execute some stage in loop. I have Jenkinsfile

pipeline {
  agent any
  tools {}
  parameters {}
  environment {}
  stages {
    stage('Execute') {
      steps {
        script {
          for (int i = 0; i < hostnameMap.size; i++) {

            hostname = hostnameMap[i]
            echo 'Executing ' + hostname

            stage('Backup previous build ' + hostname) {
              backup(hostname, env.appHome)
            }


            stage('Deploy ' + hostname) {
              when {
                expression { env.BRANCH_NAME ==~ /(dev|master)/ }
              }
              steps {
                script {
                  deploy(hostname , env.appHome, env.appName)
                }
              }
            }

            stage('Restart ' + hostname) {
              when {
                expression { env.BRANCH_NAME ==~ /(dev|master)/ }
              }
              steps {
                script {
                  restart(hostname , env.appName, env.port)
                }
              }
            }

          }
        }
      }
    }

  }
}

But got error

java.lang.NoSuchMethodError: No such DSL method 'when' found among steps

Separately all of this stage works fine. Why I got this error?

    stage('Execute') {
        steps {
            script {
                for (int i = 0; i < hostnameMap.size; i++) {
                    hostname = hostnameMap[i]
                    echo 'Executing ' + hostname

                    stage('Backup previous build ' + hostname) {
                        backup(hostname, env.appHome)
                    }

                    stage('Deploy ' + hostname) {
                        if (env.BRANCH_NAME ==~ /(dev|master)/) {
                            deploy(hostname, env.appHome, env.appName)
                        }
                    }

                    stage('Restart ' + hostname) {
                        if (env.BRANCH_NAME ==~ /(dev|master)/) {
                            restart(hostname, env.appName, env.port)
                        }
                    }

                }
            }
        }
    }

when is a directive used in the declarative pipeline definition - it won't work inside script {} block. Instead use if .

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