Pass variables between Jenkins stages

A problem in your code is that you are assigning version of environment variable within the sh step. This step will execute in its own isolated process, inheriting parent process environment variables.

However, the only way of passing data back to the parent is through STDOUT/STDERR or exit code. As you want a string value, it is best to echo version from the sh step and assign it to a variable within the script context.

If you reuse the node, the script context will persist, and variables will be available in the subsequent stage. A working example is below. Note that any try to put this within a parallel block can be of failure, as the version information variable can be written to by multiple processes.

#!/usr/bin/env groovy

pipeline {

    environment {
        AGENT_INFO = ''
    }

    agent {
        docker {
            image 'alpine'
            reuseNode true
        }
    }

    stages {

        stage('Collect agent info'){
            steps {
                echo "Current agent  info: ${env.AGENT_INFO}"
                script {
                    def agentInfo = sh script:'uname -a', returnStdout: true
                    println "Agent info within script: ${agentInfo}"
                    AGENT_INFO = agentInfo.replace("/n", "")
                    env.AGENT_INFO = AGENT_INFO
                }
            }
        }

        stage("Print agent info"){
            steps {
                script {
                    echo "Collected agent info: ${AGENT_INFO}"
                    echo "Environment agent info: ${env.AGENT_INFO}"
                }
            }
        }
    }
}

Another option which doesn't involve using script, but is just declarative, is to stash things in a little temporary environment file.

You can then use this stash (like a temporary cache that only lives for the run) if the workload is sprayed out across parallel or distributed nodes as needed.

Something like:

pipeline {
    agent any

    stages {
        stage('first stage') {
            steps {
                // Write out any environment variables you like to a temporary file
                sh 'echo export FOO=baz > myenv'

                // Stash away for later use
                stash 'myenv'
            }
        }

        stage ("later stage") {
            steps {

                // Unstash the temporary file and apply it
                unstash 'myenv'

                // use the unstashed vars
                sh 'source myenv && echo $FOO'

            }
        }
    }
}