Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 931
Genki Avatar asked Mar 13 '18 06:03

Genki


1 Answers

JENKINS-26100 suggests

node {
    withCheckout(scm) {
         echo "GIT_COMMIT is ${env.GIT_COMMIT}"
    }
}
like image 159
David van Laatum Avatar answered Sep 19 '22 19:09

David van Laatum