Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle global variables in a declarative pipeline?

Previously asked a question about how to overwrite variables defined in an environment directive and it seems that's not possible.

I want to set a variable in one stage and have it accessible to other stages. In a declarative pipeline it seems the only way to do this is in a script{} block.

For example I need to set some vars after checkout. So at the end of the checkout stage I have a script{} block that sets those vars and they are accessible in other stages.

This works, but it feels wrong. And for the sake of readability I'd much prefer to declare these variables at the top of the pipeline and have them overwritten. So that would mean having a "set variables" stage at the beginning with a script{} block that just defines vars- thats ugly.

I'm pretty sure I'm missing an obvious feature here. Do declarative pipelines have a global variable feature or must I use script{}

like image 285
red888 Avatar asked Dec 08 '17 15:12

red888


People also ask

How does Jenkins Pipeline define global variable?

At the address bar of chrome, type ${YOUR_JENKINS_HOST}/env-vars. html . The ${YOUR_JENKINS_HOST} itself is an environment variable defining the Jenkins host address/Jenkins URL(that would be http://localhost:8080/ ). And env-vars.

Where do you declare variables in declarative pipeline?

The variable must be defined in a script section. pipeline { agent none stages { stage("first") { script { foo = "bar" } sh "echo ${foo}" } } }

How do you manage global variables?

To modify the details of a global variable, click the Global variable name in the table and edit the values in the Properties section. . You can copy a global variable and save it with a different name to create a new global variable.


2 Answers

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()
}
like image 160
txace Avatar answered Sep 29 '22 11:09

txace


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" 
                }
            }
        }
    }
}
like image 22
Viraj Amarasinghe Avatar answered Sep 29 '22 12:09

Viraj Amarasinghe