Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables extracted from shell in Jenkinsfile

I am trying to pass variables extracted in a stage in Jenkinsfile between stages. For example:

   stage('Dummy Stage') {
    sh '''#!/bin/bash -l
        export abc=`output of some command`
        .....
        .....
       '''

Now, how can I pass the variable abc to a subsequent stage? I have tried setting the variable by adding a def section at the top of the file but looks like it doesnt work. In the absence of a neater way, I am having to retype the commands

like image 401
devops84uk Avatar asked Jul 05 '18 09:07

devops84uk


3 Answers

Here is what I do to get the number of commits on master as a global environment variable:

pipeline {

    agent any

    environment {
        COMMITS_ON_MASTER = sh(script: "git rev-list HEAD --count", returnStdout: true).trim()
    }

    stages {

        stage("Print commits") {
            steps {
                echo "There are ${env.COMMITS_ON_MASTER} commits on master"
            }
        }
    }
}
like image 109
Michael Avatar answered Sep 20 '22 07:09

Michael


You can use the longer form of the sh step and return the output (see Pipeline document). Your variable should be defined outside the stages.

like image 40
Bernhard Cygan Avatar answered Sep 21 '22 07:09

Bernhard Cygan


You can use an imperatively created environment variable inside a script block in you stage steps, for example:

stage("Stage 1") {
    steps {
        script {
            env.RESULT_ON_STAGE_1 = sh (
                script: 'echo "Output of some command"',
                returnStdout: true
            )
        }
        echo "In stage 1: ${env.RESULT_ON_STAGE_1}"
    }
}
stage("Stage 2") {
    steps {
        echo "In stage 2: ${env.RESULT_ON_STAGE_1}"
    }
}

This guide explains use of environment variables in pipelines with examples.

like image 25
pablo.bueti Avatar answered Sep 19 '22 07:09

pablo.bueti