Ricardo Maia
Ricardo Maia

Reputation: 31

Share variables between Jenkins pipeline stages

I have this script:

pipeline {
    environment {
        MYNAME = "BAR"
        MYIP = "FOO"
    }
    agent none
    stages {
        stage('STAGE 1') {
            agent { 
                label 'node1'
            }
            steps {
                script {
                    $MYNAME = sh(returnStdout: true, script: 'uname -a').trim()
                    $MYIP = sh(returnStdout: true, script: 'ec2metadata --local-ipv4').trim()
                    sh "echo $MYNAME" //show BAR
                }
            }
            
        }
        stage('STAGE 2') {
            agent { 
                label 'node2'
            }
            steps {
                sh 'echo "pinging $MYNAME with ip $MYIP..."' //pinging BAR with ip FOO
            }
        }

    }
}

What I want is to update MYNAME and MYIP with the information from STAGE 1 to use in STAGE 2. This script is not working, because it keeps the FOO BAR from the definition in the first lines.

Upvotes: 2

Views: 3331

Answers (1)

Michael Kemmerzell
Michael Kemmerzell

Reputation: 5256

You can define the variable outside of your pipeline which makes them global and accessible in every stage.

// Global variables
def myname = "bar"
def myip = "foo"

pipeline {
    agent none
    stages {
        stage('STAGE 1') {
            agent { 
                label 'node1'
            }
            steps {
                script {
                    myname = sh(returnStdout: true, script: 'uname -a').trim()
                    myip = sh(returnStdout: true, script: 'ec2metadata --local-ipv4').trim()
                    echo "Name: ${myname}, IP: ${myip}" //show BAR
                }
            }
            
        }
        stage('STAGE 2') {
            agent { 
                label 'node2'
            }
            steps {
                echo "pinging $MYNAME with ip $MYIP..." //pinging BAR with ip FOO
            }
        }

    }
}

Upvotes: 3

Related Questions