How to access $GIT_COMMIT in Jenkins declarative pipeline's post phase and emailext?

Genki picture Genki · Mar 13, 2018 · Viewed 23.8k times · Source

I want to send email when builds succeeds/fails along with some useful Git info such as commit SHA, previous successful SHA, commit message, etc. I was able to do this in the old UI way but now I've created declarative pipeline and now I'm getting GIT_BRANCH is not supported in this context in the received email. I'm using Jenkins ver. 2.89.3. My script:

pipeline {
    agent { 
        ...
    }
    stages {
        stage('Checkout') {
            steps {
                sh 'printenv'
                checkout scm: [$class: 'GitSCM', branches: [[[name: '*/development']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [url: 'https://github.com/myrepo/']]]
                sh 'git submodule foreach --recursive \'git submodule sync\''
                sh 'git submodule update --init --recursive'
            }
        }
        stage('Build') {
            steps {
               ...         
            }
        }
    }
    post {
        success {
            sh 'printenv'
            emailext body: '$PROJECT_DEFAULT_CONTENT Commit message: ${FILE, path="commit_message.txt"}\nThis commit: ${GIT_COMMIT}Build URL: ${BUILD_URL}',
            recipientProviders: [[$class: 'DevelopersRecipientProvider'], [$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider']],
            subject: 'Some subject'
        }
    }
}

The printenv will print everything I expect including the GIT_COMMIT both in 'Checkout' stage and post success. Because I will be reusing this script for more than 10 Jenkins jobs, I want to avoid adding manual UI work to pass in parameters and things.

I tried declaring environment before the stages but could not use it from the context of emailext:

agent {
    ...
}
environment {
    MY_GIT_COMMIT = "${GIT_COMMIT}"
}
stages {
    ...
}

Any help is appreciated. Thanks in advance.

Answer

David van Laatum picture David van Laatum · Mar 13, 2018

JENKINS-26100 suggests

node {
    withCheckout(scm) {
         echo "GIT_COMMIT is ${env.GIT_COMMIT}"
    }
}