Jenkins: "${env.SVN_REVISION}" variable returns null - jenkins

I would like to read the revision number from Jenkins job when the job fails
Revision number:
Job script:
failure {
echo 'JENKINS PIPELINE FAILED'
notifyBitbucket
commitSha1: "${env.SVN_REVISION}",
considerUnstableAsSuccess: false,
credentialsId: 'UFCBitbucket',
disableInprogressNotification: true,
ignoreUnverifiedSSLPeer: true,
includeBuildNumberInKey: false,
prependParentProjectKey: false,
projectKey: '',
stashServerBaseUrl: 'https://bitbucket.url.local:8080'
}
I have trouble with Jenkins environment variable - "${env.SVN_REVISION}". This variable returns null value.
I can not solve this problem. Please help to solve this problem
Thanks in advance

I don't think the env-variable SVN_REVISION does even exist.
All available Git-plugin env-variables can be seen here (and the Jenkins' ones here).
I would suggest you use the following environment-variable to get the revision:
GIT_COMMIT - SHA1 of the commit used in this build
On the other hand you can get the revision also by executing the git command directly per sh / bash:
git rev-parse HEAD

Related

In Jenkins pipeline, how to set a value for an environment variable when loading a shared library?

I have a multi-branch pipeline that uses a Jenkinsfile to load a shared library defined in my system configuration.
#Library("my-shared-library") _
import com.company.exa.builders.BaseBuilder
import com.company.exa.builders.EdiBuilder
import hudson.model.*
buildNumbers = getBuildNumbers() // Function not shown, but it works
properties ([
disableConcurrentBuilds(),
[$class: 'jenkins.model.BuildDiscarderProperty',
strategy: [$class: 'LogRotator',
numToKeepStr: '50',
artifactNumToKeepStr: '20']],
parameters ([
choiceParam(name: "VERSION_CHOICE",
choices: buildNumbers,
description: "Version from Builds"),
stringParam(name: "VERSION_PASSEDIN",
defaultValue: env.BRANCH_NAME,
description: "Passed-in version. Note this will override VERSION_CHOICE."),
booleanParam(name: "UPLOAD_ARTIFACTS",
defaultValue: false,
description: "Upload artifacts to file servers?"),
choiceParam(name: "DEBUG_LEVEL",
choices: ["0", "1", "2", "3"],
description: "Debug level; 0=less verbose, 3=most verbose")
])
])
When I run it clicking Scan Multibranch Pipeline Now, I get
00:00:01.018 Loading library my-shared-library
00:00:01.019 Attempting to resolve maser from remote references...
00:00:01.019 > git --version # timeout=10
00:00:01.023 > git --version # 'git version 2.17.1'
00:00:01.023 using GIT_SSH to set credentials Jenkins Master SSH
00:00:01.028 > git ls-remote -h -- git#bitbucket.org:cfouts-kmha/kmha-infrastructure.git # timeout=10
00:00:01.546 Found match: refs/heads//master revision a1bc1e273b41c4e892d7c25814d0f2a1c261f7e5
00:00:01.546 ERROR: Checkout failed
00:00:01.546 java.lang.IllegalArgumentException: Null value not allowed as an environment variable: VERSION_PASSEDIN
00:00:01.546 at hudson.EnvVars.put(EnvVars.java:379)
00:00:01.546 at hudson.model.StringParameterValue.buildEnvironment(StringParameterValue.java:59)
...complaining that variable VERSION_PASSEDIN is null. I've tried setting the VERSION_PASSEDINvariable to just "" in the following locations to no avail...
The multi-branch pipeline's Folder properties
The multi-branch pipeline's parent folder properties
In the Jenkinsfile itself
In the System configuration global properties
Any clues on how to fix this? I have a feeling it's something obvious that I'm not seeing.
Note that if I run the job with a branch's "Build with parameters" link, the job runs fine.
You have a chicken-and-egg problem when trying to set default value for parameters, e.g. here:
stringParam(name: "VERSION_PASSEDIN",
defaultValue: env.BRANCH_NAME,
To run your pipeline, Jenkins needs to figure out the value of the parameters. However, to figure out the value of the parameters, Jenkins needs to run your pipeline. See the problem?
To overcome this problem, here's what happens: Jenkins assumes the value of nothing for both VERSION_CHOICE and VERSION_PASSEDIN. In the first case, it's an empty choice; in the second, it's null.

Getting Jenkins Warning - "A secret was passed to sh using Groovy String interpolation"

After running jenkins job, in console I am facing warning message as,
"Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure"
My code looks like,
steps. withCredentials([
steps.string(
credentialsld: 'git-oauth-token-read',
variable: 'GitOauthToken'
)
})
{
steps.sh(returnStdout: false,
script:
"git remote add mainline https://xxx:${new Jobs().getToken()}#github.com/;"
)
}
Here,
new Jobs().getToken() - returns the env.GitOauthToken
I tried using different combinations of single and double quotes to the script, but I am not able to remove this warning.
Any help would be appreciated.
Thank you!

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?
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}"
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

FindBugs warnings not displayed in Jenkins Dashboard

I am using a Multibranch Pipeline job to trigger my build. One of the steps of the build is to run Sonar. After the Sonar is run, findbugs-result.xml file is created the target/sonar directory.
I publish the results using the below commands in Groovy. The build shows that there is 1 warning for FindBugs. But I do not see in the Jenkins Dashboard (FindBugs Warning portlet).
If I create a normal Freestyle job and try to do the same thing using a Post-build action, the results are visible on the Jenkins Dashboard.
bat "${env.M2_HOME}/bin/mvn sonar:sonar --settings ../HudsonSettings/settings.xml -B -U -P reporting-plugins"
step([$class: 'FindBugsPublisher', canComputeNew: false, canRunOnFailed: true, defaultEncoding: '', excludePattern: '', healthy: '', includePattern: '', isRankActivated: true, pattern: '**/target/sonar/findbugs-result.xml', unHealthy: ''])
Can anyone help ?
Thanks and Regards
Saroj Gharat
By default, the Jenkins-Findbugs will look for files with the name findbugsXml.xml.
If your integration is dropping a report with a report filename, you need to add the filename findbugs-result.xml (Under Post-build action > Publish FindBugs analysis result > Findbugs results).

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://git#corporate.com: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?
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.
I have two Jenkins instances.
In both instances, GIT_COMMIT and BRANCH_NAME environment variables are not defined.
When I try to get them from the return value of checkout() call, each instance behaves differently.
Jenkins Instance 1
Jenkins version: 2.46.1
"Pipeline: SCM Step" plugin version: 2.5
Trying to access the environment variable as explained in the checkout documentation fails.
def scmVars = checkout([$class: 'GitSCM', branches: [[name: '*/master']],
userRemoteConfigs: [[credentialsId: '2b74a351-67d5-4d00-abd3-
49842a984201', url: 'ssh://git#corporate.com:repo.git']]])
def commitHash = scmVars.GIT_COMMIT
scmVars returns NULL, and accessing scmVars.GIT_BRANCH fails with exception java.lang.NullPointerException: Cannot get property 'GIT_BRANCH' on null object.
So I had to do the following in order to get the branch:
sh 'git name-rev --name-only HEAD > GIT_BRANCH'
sh 'cat GIT_BRANCH'
git_branch = readFile('GIT_BRANCH').trim()
env.GIT_BRANCH = git_branch
Jenkins Instance 2
Jenkins version: 2.60.2
"Pipeline: SCM Step" plugin version: 2.6
In this instance, I could do the following with success:
def scmVars = checkout([$class: 'GitSCM', branches: [[name: '*/master']],
userRemoteConfigs: [[credentialsId: '2b74a351-67d5-4d00-abd3-
49842a984201', url: 'ssh://git#corporate.com:repo.git']]])
env.GIT_COMMIT = scmVars.GIT_COMMIT
env.GIT_BRANCH = scmVars.GIT_BRANCH
So please check which approach works for your Jenkins instance and use it.
If you want to access the BRANCH_NAME from Jenkins environment variable as a shell script, use the below snippet.
sh 'echo Branch Name: $BRANCH_NAME'
The response should be as below:
Branch Name: the_checkedout_branch

Resources