How to overwrite global variable in jenkins groovy - jenkins

I was working on a jenkins groovy script. I have defined one global variable at the start of the script, That is being used all over the groovy.
Users using that groovy can modify the value for global variable as per their requirement.
Now the issue is that I want to set a default value to the global variable in case a user left the global variable blank, How can I achieve this scenerio in Groovy ?
Thanks in advance.
below is how my groovy looks like
String var1 = " "
String var2 = " "
pipeline {
agent any
stages {
stage('Stage 1') {
steps {
script {
if(var1 == " ") {
var1 = <default value>
}
}
}
}
stage('Stage 2') {
steps {
script {
docker login <here i want to use default var1>
}
}
}
}
}

if(!MY_GLOBAL_VAR){
MY_GLOBAL_VAR = <default value>
}
or more explicit
if(MY_GLOBAL_VAR == null){
MY_GLOBAL_VAR = <default value>
}

if(!MY_GLOBAL_VAR){
MY_GLOBAL_VAR = <default value>
}
or more explicit
if(MY_GLOBAL_VAR){
MY_GLOBAL_VAR = <default value>
}
If you run this in a declarative pipeline you need to surround it in a script{} block.

Related

How to assign a user defined variable with environment variable with jenkin pipeline

I need to assign the BUILD_NUMBER environment variable to user defined variable.
I tried various options like def, environment block and did not work.
I want to assign variable like def a = ${BUILD_NUMBER} and your input to work this code part will be highly appreciated
pipeline{
agent any
environment {
jenkinbuild=echoRestartedInfo()
}
stages {
stage('Stage 1') {
steps {
echo "stage 1"
echo "${BUILD_NUMBER}"
echoRestartedInfo()
echo "${jenkinbuild}"
}
}
}
}
def echoRestartedInfo() {
def a = ${BUILD_NUMBER}
return a
}
The output - echo "${jenkinbuild}"
is expected same as echo "${BUILD_NUMBER}" but this shows multiple compilation error .
I do not want to code this with script{} as it should be added to each stage
Check the following.
def echoRestartedInfo() {
return env.BUILD_NUMBER
}
Or
def echoRestartedInfo() {
return "${BUILD_NUMBER}"
}
I just tried to optimize your function. You can simply replace the return with an assignment if you want to assign to a variable.
def a = env.BUILD_NUMBER

Jenkinsfile define variable based on environment variable

I would like to set a boolean variable to true if one of my environment variables equals a string. I only want to run my test stage if this RUN_TESTS var is true.
pipeline{
environment {
RUN_TESTS = expression { "${env.JOB_BASE_NAME}" == 'Test Pipeline' }
}
stages{
stage('test'){
when {
expression { RUN_TESTS }
}
steps{
// run my tests.......
}
}
}
The above is not working though.
How can I set a boolean variable based on the value of an environment variable that I can then use to conditionally run a pipeline stage?
It looks like you do not have to set environment variable in this case. You can evaluate expression directly in your stage:
pipeline{
stages{
stage('test'){
when {
expression { "${env.JOB_BASE_NAME}" == 'Test Pipeline' }
}
steps{
// run my tests.......
}
}
}
On the other hand if you still have to set the environment variable there are few ways to do it. Jenkins says:
Environment variable values must either be single quoted, double quoted, or function calls.
Wrap it in double quoted expression:
environment {
RUN_TESTS = "${env.JOB_BASE_NAME == 'Test Pipeline'}"
}
Wrap this expression in the function call, something like this:
def run_tests() {
return "${env.JOB_BASE_NAME}" == 'Test Pipeline'
}
pipeline{
environment {
RUN_TESTS = run_tests()
}
stages{
stage('test'){
when {
expression { RUN_TESTS }
}
steps{
// run my tests.......
}
}
}
But in general I would go for first approach

How to set Jenkins Declarative Pipeline environments with Global Variables?

I am trying to do this
pipeline {
agent any
environment {
LOCAL_BUILD_PATH=env.WORKSPACE+'/build/'
}
stages {
stage('Stuff'){
steps{
echo LOCAL_BUILD_PATH
}
}
}
}
Result:
null/build/
How can I use Global Environments to create my environments?
So this is method that I ended up using
pipeline {
agent {
label 'master'
}
stages {
stage ("Setting Variables"){
steps {
script{
LOCAL_BUILD_PATH = "$env.WORKSPACE/build"
}
}
}
stage('Print Varliabe'){
steps{
echo LOCAL_BUILD_PATH
}
}
}
}
You can use something like this...
LOCAL_BUILD_PATH="${env.WORKSPACE}/build/"
Remember: use "(double quote) for variable in string
I think you should use:
steps {
echo "${env.LOCAL_BUILD_PATH}"
}
as in "environment" step you're defining environmental variables which are later accessible by env.your-variable-name
This a scope issue. Declare the variable, at the top and set it to null. Something like
def var = null
You should be able to set the value in a block/closure/stage and access it in another

How do I pass variables between stages in a declarative Jenkins pipeline?

How do I pass variables between stages in a declarative pipeline?
In a scripted pipeline, I gather the procedure is to write to a temporary file, then read the file into a variable.
How do I do this in a declarative pipeline?
E.g. I want to trigger a build of a different job, based on a variable created by a shell action.
stage("stage 1") {
steps {
sh "do_something > var.txt"
// I want to get var.txt into VAR
}
}
stage("stage 2") {
steps {
build job: "job2", parameters[string(name: "var", value: "${VAR})]
}
}
If you want to use a file (since a script is the thing generating the value you need), you could use readFile as seen below. If not, use sh with the script option as seen below:
// Define a groovy local variable, myVar.
// A global variable without the def, like myVar = 'initial_value',
// was required for me in older versions of jenkins. Your mileage
// may vary. Defining the variable here maybe adds a bit of clarity,
// showing that it is intended to be used across multiple stages.
def myVar = 'initial_value'
pipeline {
agent { label 'docker' }
stages {
stage('one') {
steps {
echo "1.1. ${myVar}" // prints '1.1. initial_value'
sh 'echo hotness > myfile.txt'
script {
// OPTION 1: set variable by reading from file.
// FYI, trim removes leading and trailing whitespace from the string
myVar = readFile('myfile.txt').trim()
}
echo "1.2. ${myVar}" // prints '1.2. hotness'
}
}
stage('two') {
steps {
echo "2.1 ${myVar}" // prints '2.1. hotness'
sh "echo 2.2. sh ${myVar}, Sergio" // prints '2.2. sh hotness, Sergio'
}
}
// this stage is skipped due to the when expression, so nothing is printed
stage('three') {
when {
expression { myVar != 'hotness' }
}
steps {
echo "three: ${myVar}"
}
}
}
}
Simply:
pipeline {
parameters {
string(name: 'custom_var', defaultValue: '')
}
stage("make param global") {
steps {
tmp_param = sh (script: 'most amazing shell command', returnStdout: true).trim()
env.custom_var = tmp_param
}
}
stage("test if param was saved") {
steps {
echo "${env.custom_var}"
}
}
}
I had a similar problem as I wanted one specific pipeline to provide variables and many other ones using it to get this variables.
I created a my-set-env-variables pipeline
script
{
env.my_dev_version = "0.0.4-SNAPSHOT"
env.my_qa_version = "0.0.4-SNAPSHOT"
env.my_pp_version = "0.0.2"
env.my_prd_version = "0.0.2"
echo " My versions [DEV:${env.my_dev_version}] [QA:${env.my_qa_version}] [PP:${env.my_pp_version}] [PRD:${env.my_prd_version}]"
}
I can reuse these variables in a another pipeline my-set-env-variables-test
script
{
env.dev_version = "NOT DEFINED DEV"
env.qa_version = "NOT DEFINED QA"
env.pp_version = "NOT DEFINED PP"
env.prd_version = "NOT DEFINED PRD"
}
stage('inject variables') {
echo "PRE DEV version = ${env.dev_version}"
script
{
def variables = build job: 'my-set-env-variables'
def vars = variables.getBuildVariables()
//println "found variables" + vars
env.dev_version = vars.my_dev_version
env.qa_version = vars.my_qa_version
env.pp_version = vars.my_pp_version
env.prd_version = vars.my_prd_version
}
}
stage('next job') {
echo "NEXT JOB DEV version = ${env.dev_version}"
echo "NEXT JOB QA version = ${env.qa_version}"
echo "NEXT JOB PP version = ${env.pp_version}"
echo "NEXT JOB PRD version = ${env.prd_version}"
}
there is no need for (hidden plugin) parameter definitions or temp-file access. Sharing varibles across stages can be acomplished by using global Groovy variables in a Jenkinsfile like so:
#!/usr/bin/env groovy
def MYVAR
def outputOf(cmd) { return sh(returnStdout:true,script:cmd).trim(); }
pipeline {
agent any
stage("stage 1") {
steps {
MYVAR = outputOf('echo do_something')
sh "echo MYVAR has been set to: '${MYVAR}'"
}
}
stage("stage 2") {
steps {
sh '''echo "...in multiline quotes: "''' + MYVAR + '''" ... '''
build job: "job2", parameters[string(name: "var", value: MYVAR)]
}
}
}
I have enhanced the existing solution by correcting syntax .Also used hidden parameter plugin so that it does not show up as an extra parameter in Jenkins UI. Works well :)
properties([parameters([[$class: 'WHideParameterDefinition', defaultValue: 'yoyo', name: 'hidden_var']])])
pipeline {
agent any
stages{
stage("make param global") {
steps {
script{
env.hidden_var = "Hello"
}
}
}
stage("test if param was saved") {
steps {
echo"About to check result"
echo "${env.hidden_var}"
}
}
}
}

How to set a dynamic variable as global variable in jenkins?

I need to set a global variable with the value build_{BUILD_NUMBER}(jenkins global variable), which is dynamic. How can I set this in jenkins global properties?
How can it recognize the build number I'm referring to ?
using a declarative pipeline, you can set an environment variable based on this other environment variable (BUILD_NUMBER) like this:
pipeline {
agent { label 'docker' }
environment {
MY_BUILD_IDENTIFIER = "build_${env.BUILD_NUMBER}"
}
stages {
stage('hot_stage') {
steps {
echo "MY_BUILD_IDENTIFIER: ${env.MY_BUILD_IDENTIFIER}"
}
}
}
}
produces output like this:
[Pipeline] echo
MY_BUILD_IDENTIFIER: build_153
Here is an example script, how to alter global environment variables:
nodes = Jenkins.instance.globalNodeProperties
nodes.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)
if ( nodes.size() != 1 ) {
println("error: unexpected number of environment variable containers: ${nodes.size()}, expected: 1")
} else {
envVars = nodes[0].envVars
envVars[args[0]] = args[1]
Jenkins.instance.save()
println("okay")
}
reference:
https://gist.github.com/johnyzed/2af71090419af2b20c5a

Resources