Search code examples
mavenjenkinsgroovyjenkins-pipelineartifactory

Reuse object/property in different stages of a declerative pipeline in Jenkins


We create a new maven build:

def rtMaven = Artifactory.newMavenBuild()

Now we want to reuse this rtMaven in a different stage than the current one; like in the code below:

pipeline {
agent any

...
stages {

    stage('stage1') {
        steps {
            script {
                def rtMaven = Artifactory.newMavenBuild()
            }
    }

    stage('stage2') {
         steps {
            script {
                //REUSE rtMaven (now it's unknown)
            }
         }

     }
}

Is it possible to reuse the rtMaven without redefining it again in the second stage?

Now we have an error like:

groovy.lang.MissingPropertyException: No such property: rtMaven for class: groovy.lang.Binding

Solution

  • Define the var in global scope

    def rtMaven = ''
    pipeline {
        agent any
        stages {
            stage('stage1') {
                steps {
                    script {
                        rtMaven = Artifactory.newMavenBuild()
                    }
                }
            }
        stage('stage2') {
            steps {
                script {
                    echo "$rtMaven"
                }
            }
        }
    }