在 Jenkins 管道中将数组作为参数传递

Passing array as argument in Jenkins pipelie

我有一个共享库,它接受我设置的参数以将文件压缩到 tar。 jenkinspipline 看起来像这样。

  stage("Package"){
            steps{
                compress_files("arg1", "arg2")
            }          
        } 

共享库 compress_file 看起来像这样

#!/usr/bin/env groovy

// Process any number of arguments.
def call(String... args) {
    sh label: 'Create Directory to store tar files.', returnStdout: true,
        script: """ mkdir -p "$WORKSPACE/${env.PROJECT_NAME}" """
    args.each {
        sh label: 'Creating project directory.', returnStdout: true,
            script: """ mkdir -p "$WORKSPACE/${env.PROJECT_NAME}" """
        sh label: 'Coping contents to project directory.', returnStdout: true,
            script: """ cp -rv ${it} "$WORKSPACE/${env.PROJECT_NAME}/." """
    }
    sh label: 'Compressing project directory to a tar file.', returnStdout: true,
    script: """ tar -czf "${env.PROJECT_NAME}.tar.gz" "${env.PROJECT_NAME}" """
    sh label: 'Remove the Project directory..', returnStdout: true,
    script: """ rm -rf "$WORKSPACE/${env.PROJECT_NAME}" """    
}

新要求是使用数组而不是更新参数值。我们如何或可以在 jenkinsfile 阶段传递数组名

是的,这是可能的,从 Jenkinsfile 中,您可以在 stage() 内部或外部 stage() 中定义数组并加以利用,例如

在声明性管道中:

def files = ["arg1", "arg2"] as String[]
pipeline {
  agent any 
  stages {
     stage("Package") {
         steps {
           // script is optional 
           script {
             // you can manipulate the variable value of files here
           }
           compress_files(files)
         }
     }
  }
}

在脚本管道中:

node() {
   //You can define the value here as well
   // def files = ["arg1", "arg2"] as String[]
   stage("Package"){
      def files = ["arg1", "arg2"] as String[]
      compress_files(files)       
   } 
}

而在共享库中,方法会像

// var/compress_files.groovy

def call(String[] args) {
   args.each { 
      // retrive the value from ${it} and proceed with your logic
   }
}

def call(String... args) {
   args.each { 
      // retrive the value from ${it} and proceed with your logic
   }
}