0

besically my groovy file jenkins-build-paramters.groovy is as below

Cotaining_WAR_Deployment='true'
Cotaining_JAR_Deployment='false'

Below is my environment variable

    environment {
        Cotaining_WAR_Deployment= "true"    
        Cotaining_JAR_Deployment= "false"
    }

My question how can i load the build paramters based on respective value. For instance, in environment Cotaining_WAR_Deployment should take from the groovy file value

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
valene
  • 5
  • 4
  • Just to clarify: you want your pipeline to read a groovy file which contains variables and those should be accessible as environment variables in the pipeline? – smelm Sep 27 '20 at 16:35

3 Answers3

0

You can use the [load step][1] to load a groovy script.

Modify your jenkins-build-paramters.groovy as follows:

Cotaining_WAR_Deployment='true'
Cotaining_JAR_Deployment='false'

return this

Then you can load it like so:

stage('load params'){
    script {
        def parameters = load "${workspace}/jenkins-build-paramters.groovy"
        Cotaining_WAR_Deployment = parameters.Cotaining_WAR_Deployment
        Cotaining_JAR_Deployment = parameters.Cotaining_JAR_Deployment
    }
}

By the way, you don't need to store boolean variables as string ("true") you can use them as booleans as well (true) [1]: https://www.jenkins.io/doc/pipeline/steps/workflow-cps/#load-evaluate-a-groovy-source-file-into-the-pipeline-script

smelm
  • 1,253
  • 7
  • 14
  • I wish to use it in environment rather than steps. Environment for individual stage. My script is as below stage -> environment -> when -> steps – valene Sep 30 '20 at 08:25
  • I don't think that is possible. But you can limit the scope of the variables to the current stage – smelm Sep 30 '20 at 09:05
0

You can create a jenkins-build-paramters.groovy with the following content:

env.Cotaining_WAR_Deployment='true'
env.Cotaining_JAR_Deployment='false'

Then load this wile with the following step:

pipeline {
  <...>
  stages {
    stage('Checkout repo') {
      steps {
        load 'jenkins-build-paramters.groovy'
        echo "${env.Cotaining_WAR_Deployment}
      }
    }
  }
}

It should be accessible same as other environment variables set with

environment {
  Cotaining_WAR_Deployment= "true"    
  Cotaining_JAR_Deployment= "false"
}
Dziki_Jam
  • 170
  • 2
  • 10
0

Different alternative you load it from properties file instead of Groovy:

props = readProperties(file: FilePath)

and then read all the values from props. The main advantage of using readProperties instead of loading from a Groovy file for me, was I can loop through all the fetched key-value pairs easily and even declare them as environment variables if I want. I couldn't find any way to do same with groovy file

readProperties(file: FilePath).each {key, value -> env[key] = value }

Rovshan Musayev
  • 144
  • 3
  • 15