6

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!

Gerold Broser
  • 14,080
  • 5
  • 48
  • 107
ISZ
  • 1,027
  • 2
  • 14
  • 29
  • 1
    What if you iterate over `env` with `env.each { println it }`? Are there any? What if you `export` env vars in `jenkins.sh`? Are those available in Groovy then? – Gerold Broser Jul 02 '17 at 22:16
  • So exporting didn't work (sorta expected as I think exports are scoped to the shell), but the `env.each { println it }` shows it. Why wouldn't env['CLUSTER'] work? – ISZ Jul 02 '17 at 22:35
  • Ok, I think I jumped the gun exporting works. Thanks Gerold! – ISZ Jul 02 '17 at 22:41
  • Perhaps [Access to build environment variables from a groovy script in a Jenkins build step ( Windows)](https://stackoverflow.com/q/21236268/1744774) may help, too. – Gerold Broser Jul 02 '17 at 22:43
  • I am not sure there is a 'build' concept when the init.groovy.d files run, is there? Or I wasn't sure how to construct a build object. I also got it working by using `sed -i "1s/^/CLUSTER=\"${CLUSTER}\" \n/" /usr/share/jenkins/ref/init.groovy.d/init_ecs.groovy`, but I prefer the exports. :) – ISZ Jul 02 '17 at 22:55
  • You're right. I've never used a [Post-initialization script](https://wiki.jenkins.io/display/JENKINS/Post-initialization+script), wasn't even aware of it and since you didn't link to it... ;) However, thanks for teaching me something and glad that I could be of help. – Gerold Broser Jul 02 '17 at 23:12

1 Answers1

6

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).

Gerold Broser
  • 14,080
  • 5
  • 48
  • 107