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

3

18

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.

Feel answered 13/3, 2018 at 6:16 Comment(0)
Y
14

JENKINS-26100 suggests

node {
    withCheckout(scm) {
         echo "GIT_COMMIT is ${env.GIT_COMMIT}"
    }
}
Yeisk answered 13/3, 2018 at 8:32 Comment(4)
Thanks for the reply. I want to specify which branch I want to build from the pipeline script, can I do that with this setup? Updated my question to reflect that. Or is there a good way to define which branches to build in one place so I don't have to update 10+ jobs?Feel
Personally I use the multi branch pipeline to build all branches. But you could add a job parameter for the branch name. don't know how to do that off the top of my head but should be plenty of examplesYeisk
Yeah I have parameterized variables I’m using for other purposes, but this isn’t scalable. Maybe I can look into building any branch like you said.Feel
how do you get the short form of this?Traditional
C
2

You could do it in the following way—although this may not be for the declarative pipeline, maybe it will give you something to go on—from a multibranch pipeline setup…

node("my-node") {

    withCredentials([string(credentialsId: 'my-credential-id', variable: 'MY_CREDENTIAL')]) {

    def commitHash = checkout(scm).GIT_COMMIT

    stage ("stage 1") {
        // …
    }

}

or within a stage (works better for me),

node("my-node") {
    def scmVars

    stage("stage-1") {
        scmVars = git branch: env.BRANCH_NAME, credentialsId: 'my-git-credentials', url: 'https://myrepo.git'

        commitHash = scmVars.GIT_COMMIT
    }
}

I prefer it in a stage because checkout(scm).GIT_COMMIT will get the merge commit of the target branch rather than the latest commit from the PR

Combustible answered 31/7, 2018 at 18:7 Comment(1)
Thanks for pointing out the GIT_COMMIT difference between "checkout scm" and "git branch: ...."Maretz
F
1

Another way to do it is with command substitution, this work for us:

post {
        success {
        sh  '''    
            echo "Commit $(git rev-parse HEAD)" | mail -s "Deployment completed successfully" [email protected]
            '''                  
        }
    }
Formicary answered 16/8, 2019 at 9:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.