Jenkins 管道多行脚本命令作为变量

Jenkins pipeline multiline script command as variable

如何将命令保存在变量中并在舞台的任何位置执行

尝试了不同的方法,但仍然成功

这是我的例子

pipeline {
   agent any
   environment {
       myscript = sh '''
       echo "hello"
       echo "hello"
       echo "hello"
       '''
   }
   stages {
       stage("RUN") {
           steps {
               sh "${myscript}" 
           }          
      }
   }
}

你可以这样做。不使用 groovy 变量,但使用 groovy function/method

可以更加动态
def reusableScript(message) {
    sh """
      echo Hello World
      echo Hi ${message}
    """
}
pipeline {
    agent any;
    stages {
        stage('01') {
            steps {
                script {
                    reusableScript("From ${env.STAGE_NAME}")
                }
            }
        }
        stage('02') {
            steps {
                script {
                    reusableScript("From ${env.STAGE_NAME}")
                }
            }
        }
    }
}