How do you handle global variables in a declarative pipeline?

淺唱寂寞╮ 提交于 2019-12-05 04:27:47

Like @mkobit says, you can define the variable to global level out of pipeline block. Have you tried that?

def my_var
pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                my_var = 'value1'
            }
        }

        stage('Example2') {
            steps {
                printl(my_var)
            }
        }

    }
}

This is working without an error,

def my_var
 pipeline {
  agent any
   environment {
     REVISION = ""
   }
   stages {
    stage('Example') {
        steps {
            script{
                my_var = 'value1'
            }
        }
    }

    stage('Example2') {
        steps {
             script{
                echo "$my_var" 
             }

        }
    }

 }
}

For strings, add it to the 'environment' block:

pipeline {
  environment {
    myGlobalValue = 'foo'
  }
}

But for non-string variables, the easiest solution I've found for declarative pipelines is to wrap the values in a method.

Example:

pipeline {
  // Now I can reference myGlobalValue() in my pipeline.
  ...
}

def myGlobalValue() {
    return ['A', 'list', 'of', 'values']

// I can also reference myGlobalValue() in other methods below
def myGlobalSet() {
    return myGlobalValue().toSet()
}

@Sameera's answer is good for most use cases. I had a problem with appending operator += though. So this did NOT work (MissingPropertyException):

def globalvar = ""
pipeline {
  stages {
    stage("whatever) {
      steps {
        script {
          globalvar += "x"
        }
      }
    }
  }
}

But this did work:

globalvar = ""
pipeline {
  stages {
    stage("whatever) {
      steps {
        script {
          globalvar += "x"
        }
      }
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!