Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

groovy - Jenkins Workflow Checkout Accessing BRANCH_NAME and GIT_COMMIT

I cannot seem to extract $GIT_COMMIT and $BRANCH_NAME from a Jenkins Workflow Checkout step.

I would like to be able to send this information through to my Gradle scripts in order to pass it onto external sources such as Static analysis etc.

Currently I try to run this:

checkout([$class: 'GitSCM', branches: [[name: '*/master']], userRemoteConfigs: [[credentialsId: '2b74a351-67d5-4d00-abd3-49842a984201', url: 'ssh://[email protected]:repo.git']]])

And I would like to achieve the following or something similar:

// Specified variables that can be reused
def branch = ${BRANCH_NAME}
def commit = ${GIT_COMMIT}

Or maybe this would work too:

print "BRANCH: ${BRANCH_NAME}, COMMIT: ${GIT_COMMIT}"
// or the following
print "BRANCH: ${env.BRANCH_NAME}, COMMIT: ${env.GIT_COMMIT}"

I did find the following issue which seems to be resolved but it doesn't work in version 1.15:

https://issues.jenkins-ci.org/browse/JENKINS-30252

Anyone have any ideas how to workaround this or if there's a variable I cannot find?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all,

def branch = ${BRANCH_NAME}

is not valid Groovy, or at least not doing what you think. Perhaps you meant

def branch = "${BRANCH_NAME}"

which would just be a silly way of writing

def branch = BRANCH_NAME

Anyway environment variables are not currently accessible directly as Groovy variables in Pipeline (there is a proposal to allow it); you need to use the env global variable:

def branch = env.BRANCH_NAME

From within an external process, such as a sh step, it is an actual environment variable, so

sh 'echo $BRANCH_NAME'

works (note that ' means Groovy is not interpolating the variable).

Now, JENKINS-30252 was referring to multibranch projects. If you created a standalone Pipeline job, this variable will not be set.

Anyway in your case your checkout step is always checking out the master branch. If you actually have a multibranch project, then your Jenkinsfile should be using

checkout scm

which will check out a commit on the correct branch (always matching the revision of Jenkinsfile itself).

As to the commit hash, pending JENKINS-26100 this is not available automatically, but you can use something like

sh 'git rev-parse HEAD > commit'
def commit = readFile('commit').trim()

to access it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...