0

I have a command that retrieves my most recent git commit hash.

git rev-parse HEAD

Is it possible to pass this as an environment variable to a Jenkins pipeline stage?

I've tried to do this,

environment {
    CURRENT_COMMIT_HASH=`git rev-parse HEAD`
}

but when I echo it in a later stage

stage ('Issues Report') {
    steps {
        sh '''
        echo "${CURRENT_COMMIT_HASH}"
        '''
        }   
    }

It comes out blank.

+ echo 

torek
  • 448,244
  • 59
  • 642
  • 775
Metro
  • 873
  • 8
  • 19
  • 2
    it should return may be try adding the stage for git command then assign it to variable. https://www.jenkins.io/doc/pipeline/tour/environment/ – Vijay Daswani Aug 27 '21 at 23:29
  • Why are people so obsessed by multi-line strings in an `sh` step? I've seen them in almost every Jenkins pipeline question with a single `sh` line lately. – Gerold Broser Aug 28 '21 at 11:44
  • When looking at the accepted answer: Isn't the question about the other way round: _Assigning shell commands' output to a Jenkins environment variable_? – Gerold Broser Aug 28 '21 at 12:06

1 Answers1

4

This should work

stage ('Stage-Name') {
    environment {
        current_hash = """${sh(
        returnStdout: true,
        script: "git rev-parse HEAD"
        )}"""
    steps {
        sh '''
        echo "My current commit hash is $current_hash"
        '''
        }
      }
Hammed
  • 1,457
  • 1
  • 24
  • 37