Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins Environment Variables in Groovy Init

I am building a Docker image of Jenkins, and have passed ENV variables to the jenkins.sh initialization file:

Dockerfile

...

COPY ./jenkins.sh /usr/local/bin/jenkins.sh 

jenkins.sh

echo ENV: "$ENV"
echo CLUSTER: "$CLUSTER"
echo REGION: "$REGION"

When I run the image, these values print out perfectly, but I would like to use them in Groovy scripts during the initialization of Jenkins.

The following throws an error during start:

import java.util.Arrays
import java.util.logging.Logger
Logger logger = Logger.getLogger("ecs-cluster")

logger.info("Loading Archeus-Midwayer...")
import jenkins.model.*
instance = Jenkins.getInstance()

def env = System.getenv()
println(env['CLUSTER'])

Error

WARNING: Failed to run script file:/var/jenkins_home/init.groovy.d/init_ecs.groovy groovy.lang.MissingPropertyException: No such property: CLUSTER for class: init_ecs at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53) at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307)

How can I capture the environment variables present in jenkins.sh?

Thanks!

like image 828
ISZ Avatar asked Jul 02 '17 21:07

ISZ


People also ask

How do I get environment variables in Groovy Jenkins?

In "Manage Jenkins" -> "Configure System" -> "Global Properties" -> "Environment Variables" I added "ALL_NODES_ENVVAR".

How do I set environment variables in Groovy?

Download a binary distribution of Groovy and unpack it into some folder on your local file system. Set your GROOVY_HOME environment variable to the directory where you unpacked the distribution. Add GROOVY_HOME/bin to your PATH environment variable. Set your JAVA_HOME environment variable to point to your JDK.

How do I declare a variable in Jenkins groovy?

Variables in a Jenkinsfile can be defined by using the def keyword. Such variables should be defined before the pipeline block starts. When variable is defined, it can be called from the Jenkins declarative pipeline using ${...} syntax.


1 Answers

Check the env vars with:

def env = System.getenv()
env.each { 
  println it
}

Export the env vars in jenkins.sh.

See also Access to build environment variables from a groovy script in a Jenkins build step ( Windows).

like image 121
Gerold Broser Avatar answered Oct 10 '22 00:10

Gerold Broser