Search code examples
jenkinsgroovyjenkins-pipelinejenkins-pluginsjenkins-groovy

How do you handle global variables in a declarative pipeline?


I 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: that's 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{}?


Solution

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