Search code examples
jenkinsjenkins-pipelinejenkins-groovy

PAss a variable between jenkins stages


I am working in jenkins and I have a jenkins file. Here is a sample:

environment {
  var1 = "city1"
  var2 = "city2"
}
stages{
  stage('stage 1 - define a var and load a script') {
    steps {
      script {
        var = load jenkins/methods.groovy
        env.list = var.mymethod(var1)
      {
    }
  }
  stage('stage 2 - use defined stuff in stage1') {
    steps {
      script {
        var.mymethod2(env.list[1], env.list[0])
      {

    }
  }
}

In stage 1, I am loading my methods.groovy and using mymethod (from methods.groovy) to get a list (2 values) into env.list. In stage 2 I want to use env.list values ([0],[1]) and load them into another method (mymethod2). Not sure why but those values are not being passed from stage 1 to stage 2. Can I get some help on this please?


Solution

  • In cases like this, usually I define "global" variables. So for example:

    def myVar
    def myList = []
    
    pipeline {
      stages {
        stage('stage 1') {
          steps {
            script {
              myVar = 'Hello'
              myList = myLib.myMethod
            }
          }
        }
        stage('stage 2') {
          steps {
            script {
              echo "myVar --> ${myvar}"
              echo "myList --> ${myList}"
            }
          }
        }
      }
    }
    

    Not sure if this is the right way to do it, neither the best way, but it works.