Pietto Vasco
Pietto Vasco

Reputation: 151

Passing array as argument in Jenkins pipelie

I have a shared library that accept parameters i setup to compress files into a tar. The jenkinspipline looks like this.

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

The shared library compress_file looks like this

#!/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}" """    
}

New requirement is to use an array instead of updating the argument values. How or can we pass an arrayname in the jenkinsfile stage

Upvotes: 1

Views: 5882

Answers (1)

Samit Kumar Patel
Samit Kumar Patel

Reputation: 2098

Yes it’s possible, from Jenkinsfile you can define the array inside stage() or outside stage() and make that use of, like

In declarative pipeline :

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

In scripted pipeline:

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

And in the shared library, the method will be like

// var/compress_files.groovy

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

or

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

Upvotes: 4

Related Questions