treeNinja
treeNinja

Reputation: 185

Referencing variable in declarative jenkins pipeline

I am using the groovy below to call a bat command, that no matter how i reference the LOCAL_WORKSPACE within the bat command it does not evaluate it. What am i missing?

Error

nuget restore $env.LOCAL_WORKSPACE "Input file does not exist: $env.LOCAL_WORKSPACE"

Script

pipeline {
agent any
stages {
    stage('Clone repo') {
        steps {
            deleteDir()
            git branch: 'myBranch', changelog: false, credentialsId: 'myCreds', poll: false, url: 'http://myRepoURL'
        }
    }
    stage ("Set any variables") {
        steps{
            script{
                LOCAL_BUILD_PATH = "$env.WORKSPACE"
            }
        }
    }
    stage('Build It, yes we can') {
        parallel {
            stage("Build one") {
                steps {
                    echo LOCAL_BUILD_PATH
                    bat 'nuget restore %LOCAL_WORKSPACE%'
                }
            }
        }
    }
}

}

Upvotes: 2

Views: 3101

Answers (2)

ParthaSarathi
ParthaSarathi

Reputation: 69

You can use environment variables to store and access to/from stages. For example, if you define LOCAL_ENVR as Jenkins parameter, you can manipulate the variable from stages:

stage('Stage1') {
       steps {
           script{
                env.LOCAL_ENVR = '2'
           }
       }
    }
    stage('Stage2') {
         steps {
             echo "${env.LOCAL_ENVR}"
         }
    }

Upvotes: 1

Michael
Michael

Reputation: 2683

You cannot set variables to share data between stages. Basically each script has its own namespace.

What you can do is use an environment directive as described in the pipeline syntax docs. Those constants are globally available, but they are constants, so you cannot change them in any stage.

You can calculate the values though. For example I use an sh step to get the current number of commits on master like this:

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

Upvotes: 4

Related Questions