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

时间:2021-02-18 10:04:06

标签: bash jenkins jenkins-pipeline jenkins-groovy

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

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

这是我的例子

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

1 个答案:

答案 0 :(得分:1)

你可以这样做。不是使用 groovy 变量,而是使用 groovy 函数/方法可以更加动态

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