Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 970
lvthillo Avatar asked Nov 07 '17 10:11

lvthillo


People also ask

Can we use different nodes for each stage in Jenkins?

You can also mix and match node { stage {..}} and stage { node {..}} within your pipeline codes. By design (in Jenkins, as well as in the concept of continuous delivery), stages do not execute in parallel. Only the steps within a single stage are executed in parallel.

Can we have multiple stages in Jenkins pipeline?

Jenkins Pipeline allows you to compose multiple steps in an easy way that can help you model any sort of automation process. Think of a "step" like a single command which performs a single action. When a step succeeds it moves onto the next step. When a step fails to execute correctly the Pipeline will fail.


1 Answers

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"
            }
        }
    }
}
like image 178
Ram Avatar answered Sep 19 '22 13:09

Ram