'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 1:[1]

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"
            }
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1