Not able to access variable declared in environment block in stage block in jenkinsfile - jenkins-pipeline

I have jenkins file as follows
pipeline{agent{node{label ...}}
environment{
var1=""
var2=""
}
stages{
stage{
steps{
script{
var1="some string"
var2="another string"
}
}
}
stage{
echo "${var1}"
echo "${var2}"
}
}
}
After running this I get null values for var1 and var2.
I tried solution provided here link1 and link2
What is missing in my script?

the answer is in your link2. You should:
get rid of environment section
use env variables if you want to reference them in next stages:
stage('assign values'){
steps{
script{
env.VAR1="some string"
env.VAR2="another string"
}
}
}
use capital letters for better clarity
fix error in last stage and add steps section:
stage('print'){
steps{
echo env.VAR1
echo env.VAR2
}
}

Related

How can I echo the value of a windows system variable inside Jenkins pipeline?

For example: when I echo %APPDATA% on cmd line is expected to print the path to appdata folder, like this: "C:\Users\User\AppData". How can I do the same in a jenkins pipeline?
def app1 = "%APPDATA%"
pipeline {
agent any
stages {
stage('Test') {
steps {
echo ¨\¨${app1}\¨"
}
}
}
}
The following methods should work.
echo "${APPDATA}"
echo "${env.APPDATA}"
echo "$APPDATA"

Jenkins Declarative Pipeline is not supporting shell/bash syntax

I have a shell script inside my jenkins pipeline which will call mvn. For that i have to pass variable value to mvn. The variable is not passing inside the Jenkins pipeline's shell. But when trying from local machine shell it is working fine as expected.
ARTIFACT_NAME="Sample_Artifact"
pipeline{
agent {
node{
label "${AGENT}"
}
}
stages{
stage("Setting MultiJob Properties"){
steps{
sh '''set +x
export VERSION=$(mvn -B -q -Dexec.executable=echo -Dexec.args=\${${ARTIFACT_NAME}} )
echo $VERSION
'''
}
}
}
}
Expected Process: export VERSION=$(mvn -B -q -Dexec.executable=echo -Dexec.args=${Sample_Artifact} )
Expected Output: 1.0001
ARTIFACT_NAME - I am passing it from Jenkins UI.
${${ARTIFACT_NAME}} - This variable is perfectly replace value in Freestyle jobs and it is throwing error in the Pipeline jobs.
Error Message: script.sh: 3: Bad substitution
Can Anyone please help me to resolve the issue?
As Ian wrote, you're passing the whole script as a literal (''') instead of an interpolated string ("""), so the variable name doesn't get substituted with its value:
pipeline{
agent {
node {
label AGENT
}
}
stages {
stage("Setting MultiJob Properties") {
steps {
sh """set +x
export VERSION=\$(mvn -B -q -Dexec.executable=echo -Dexec.args=\${$ARTIFACT_NAME})
echo \$VERSION"""
}
}
}
}

jenkins pipline get latest successful commit id and pass in another pipeline

I am struggle to get
1.latest successful commit id of github proj (this won't help: echo GIT_PREVIOUS_SUCCESSFUL_COMMIT %GIT_PREVIOUS_SUCCESSFUL_COMMIT%)
2.get this id from one job pipeline and pass to the other jenkins job pipeline
actually at step 2 I have issue
I have tried to save the id in temp file using
rm logfile.txt
echo $commitID | tee logfile.txt
and but jenkins gives an err
getting err
groovy.lang.MissingPropertyException: No such property: logfile for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
It won't allow to create temp file
also I have checked https://plugins.jenkins.io/parameterized-trigger but unable to use it in multiline or maven proj ( can't understand how to use it )
also tried to inject variable that is commit id I want to store as env.commitID but still unable to save this id anywhere at temp location or as env variable
further after save want to pass to another pipeline
pipeline {
agent any
options {
timeout(time: 1, unit: 'HOURS')
}
environment {
def myVariable = "foo"
py2Ana="DEFAULT"
SOURCE_CODE_URL = 'https://github.com/himanshukgit/hardwareInventory.git'
RELEASE_BRANCH = 'master'
}
stages {
stage('Git') {
agent any
steps {
sleep(5)
// Clean dir
deleteDir()
}
}
stage('transfer'){
steps{
bat """
#echo off
echo GIT_COMMIT %GIT_COMMIT%
echo GIT_BRANCH %GIT_BRANCH%
echo GIT_LOCAL_BRANCH %GIT_LOCAL_BRANCH%
echo GIT_PREVIOUS_COMMIT %GIT_PREVIOUS_COMMIT%
echo GIT_PREVIOUS_SUCCESSFUL_COMMIT %GIT_PREVIOUS_SUCCESSFUL_COMMIT%
echo GIT_URL %GIT_URL%
echo GIT_URL_N - %GIT_URL_N%
echo GIT_AUTHOR_NAME %GIT_AUTHOR_NAME%
echo GIT_COMMITTER_EMAIL %GIT_COMMITTER_EMAIL%
"""
// Checkout branch
script{
git branch: "$RELEASE_BRANCH", url: "$SOURCE_CODE_URL"
echo "============================================================"
echo GIT_PREVIOUS_SUCCESSFUL_COMMIT %GIT_PREVIOUS_SUCCESSFUL_COMMIT%
echo "============================================================"
echo "remove temp logfile"
sh rm logfile.txt
echo "adding GIT_PREVIOUS_SUCCESSFUL_COMMIT into the file"
echo "============================================================"
echo GIT_PREVIOUS_SUCCESSFUL_COMMIT %GIT_PREVIOUS_SUCCESSFUL_COMMIT% | tee logFile.txt
echo "============================================================"
}
}
}
}
}
For the first part, the git (or checkout) keywords return the relevant parameters as a dictionary, so you can just keep the returned value of the git keyword and through it access the relevant parameters you need. Something like:
node {
def gitVars = git branch: "$RELEASE_BRANCH", url: "$SOURCE_CODE_URL"
// gitVars will contain the following keys: GIT_BRANCH, GIT_COMMIT, GIT_LOCAL_BRANCH, GIT_PREVIOUS_COMMIT, GIT_PREVIOUS_SUCCESSFUL_COMMIT, GIT_URL
println gitVars
println "Previous successful commit is : ${gitVars.GIT_PREVIOUS_SUCCESSFUL_COMMIT}"
}
For the second part you can use the built in build keyword for triggering another job (of any type) you have Multiple Options for controlling the execution.
Here is a simple example:
node {
...
build job: 'My_Downstream_Job', wait: true, propagate: true, parameters: [string(name: 'CommitSha1', value: gitVars.GIT_PREVIOUS_SUCCESSFUL_COMMIT)]
}

jenkins pipelines: shell script cannot get the updated environment variable

In Jenkins, I want to get a user input and pass to a shell script for further use.
I tried to set as environment variable, but the shell script failed to get the latest value and the old value is echo.
pipeline {
agent none
environment{
myVar='something_default'
}
stages {
stage('First stage') {
agent none
steps{
echo "update myVar by user input"
script {
test = input message: 'Hello',
ok: 'Proceed?',
parameters: [
string(name: 'input', defaultValue: 'update it!', description: '')
]
myVar = "${test['input']}"
}
echo "${myVar}" // value is updated
}
}
stage('stage 2') {
agent any
steps{
echo "${myVar}" // try to see can myVar pass between stage and it output expected value
sh("./someShell.sh") // the script just contain a echo e.g. echo "myVar is ${myVar}"
// it echo the old value. i.e.something_default
}
}
}
}
The environment variables that we set in the pipeline Script will be accessible only within the script. So, even if you declare your variable as global, it will not work inside a shell script.
Only option I can think off is, pass as it as argument to the shell script
sh("./someShell.sh ${myVar}")
EDIT:
Updated Answer based on OP's query on Shell script for parsing input
LINE="[fristPara:100, secondPaa:abc]"
LINE=$(echo $LINE | sed 's/\[//g')
LINE=$(echo $LINE | sed 's/\]//g')
while read -d, -r pair; do
IFS=':' read -r key val <<<"$pair"
echo "$key = $val"
done <<<"$LINE,
"
You need to pass the variables between your stages as environment variables, e.g. like this:
stage("As user for input") {
steps {
env.DO_SOMETING = input (...)
env.MY_VAR = ...
}
}
stage("Do something") {
when { environment name: 'DO_SOMETING', value: 'yes' }
steps {
echo "DO_SOMETING has the value ${env.DO_SOMETHING}"
echo "MY_VAR has the value ${env.MY_VAR}"
}
}
You have to declare the variable on a global scope so that both places refer to the same instance.
def myVal
pipeline { ... }

Accessing Shell variable from within Jenkins Pipeline

I am trying the below line in my Jenkins Pipeline. In the below set of lines, I am assigning the variable IMAGE_NAME in a shell, and trying to access that in the Jenkins Pipeline script, but not able to do that. Any idea on how to do that?
stage('Build: Get Image') {
steps {
echo 'Getting docker image'
sh "IMAGE_NAME=`grep -ri \"Successfully built\"
$BUILD_FILE_NAME | awk \'{print \$3}\'`"
echo "Image Name is:$IMAGE_NAME"
}
}
You can define it as env variable:
env.some_var = 'AAAA'
And print with:
sh 'echo ${env.some_var}'
proxy_host = 'abc.com'
stage('Docker Up') {
steps{
script{
sh("""
echo ${http_proxy}
""")
}
}
Catch here is to use double quotes " to execute the shell script. I tested it and it works fine.

Resources