Wolf
Wolf

Reputation: 116

Using declarative pipeline script., Get the name of the file from a folder and assign it to a global variable, and call that variable in another stage

I would like to get the file name from a folder and set it to a global variable in a jenkins pipeline., eg; def PS, this was placed on the top of the declarative pipeline script.

Assume that the file name is Someting.zip (it may change frequently) inside a folder (say /dev/team/*.zip) Whatever the name might be., we need to get the file name as the variable.

what we like to do is get the name of the file and assign it to a global variable, then call that variable in another stage.

def PS
pipeline{
    stages
    {
    stage (assigning variable) {
        steps
            {
                dir('dev/team/')
                {
                    script
                    {
                     PS = "<we require the zip file present inside that /dev/team/ we tried using *.zip, and yet no luck>"
                     
                    }
                }
            }
        

        }
    stage (calling variable) {
        steps
            {
                    script
                    {
                     echo $PS
                    }
                
            }
        

        }
    }
}

Upvotes: 0

Views: 1029

Answers (1)

a.ha
a.ha

Reputation: 519

Assumining your Jenkins is running on a linux machine, you could use shell commands to achieve this. The following example should work for your scenario:

pipeline{
  agent any
  environment {
    PS=""
  }
  stages {
    stage ("assigning variable") {
      steps {
        dir('dev/team/') {
          script {
            PS = sh(returnStdout: true, script: 'find . -name "*.zip" | head -n 1')
          }
        }
      }
    }
    stage ("calling variable") {
      steps {
        sh "echo ${PS}"
      }
    }
  }
}

Upvotes: 2

Related Questions