Idan Adar
Idan Adar

Reputation: 44516

CHANGE_AUTHOR_EMAIL and CHANGE_ID environment variables return "No such property: ..."

Given the following pipeline:

stages {
    stage ("Checkout SCM") {
        steps {
            checkout scm

            sh "echo ${CHANGE_AUTHOR_EMAIL}"
            sh "echo ${CHANGE_ID}"
        }
    }
}

Why do these variables fail to resolve and provide a value?

Eventually I want to use these environment variables to send an email and merge a pull request:

post {
    failure {
        emailext (
        attachLog: true,
        subject: '[Jenkins] $PROJECT_NAME :: Build #$BUILD_NUMBER :: build failure',
        to: '$CHANGE_AUTHOR_EMAIL',
        replyTo: 'iadar@...',
        body: '''<p>You are receiving this email because your pull request was involved in a failed build. Check the attached log file, or the console output at: $BUILD_URL to view the build results.</p>'''
     )
    }
}

and

sh "curl -X PUT -d '{\'commit_title\': \'Merge pull request\'}'  <git url>/pulls/${CHANGE_ID}/merge?access_token=<token>"

Oddly enough, $PROJECT_NAME, $BUILD_NUMBER, $BUILD_URL do work...


Update: this may be an open bug... https://issues.jenkins-ci.org/browse/JENKINS-40486 :-(
Is there any workaround to get these values?

Upvotes: 2

Views: 8850

Answers (2)

stigsb
stigsb

Reputation: 321

You need to be careful about how you refer to environment variables depending on whether it is shell or Groovy code, and how you are quoting.

When you do sh "echo ${CHANGE_ID}", what actually happens is that Groovy will interpolate the string first, by replacing ${CHANGE_ID} with the Groovy property CHANGE_ID, and that's where your error message is from. In Groovy, the environment variables are wrapped in env.

If you want to refer to the environment variables directly from your shell script, you either have to interpolate with env, use single quotes, or escape the dollar sign. All of the following should work:

sh 'echo $CHANGE_ID'
sh "echo \$CHANGE_ID"
sh "echo ${env.CHANGE_ID}"

Upvotes: 5

Idan Adar
Idan Adar

Reputation: 44516

For anyone who may come across this, these variables are available only if the checkbox for Build origin PRs (merged with base branch) was checked (this is in a multi-branch job).

See more in this other Jenkins issue: https://issues.jenkins-ci.org/browse/JENKINS-39838

Upvotes: 2

Related Questions