0

I have an external file with variables that I would like to access in my groovy script.

myfile.conf:

variable1=Value1
export variable2=Value2

I want to do something like the following in my groovy script:

System.getenv("variable1")
System.getenv("variable2")

I have tried running "source myfile.conf".execute().waitFor() but I am unable to access these variables.

Trevor
  • 6,659
  • 5
  • 35
  • 68
  • Are you using it in jenkins? If so, refer http://stackoverflow.com/questions/21236268/access-to-build-environment-variables-from-a-groovy-script-in-a-jenkins-build-st. By the way, `export` should be there before `variable1` – Rao Mar 31 '17 at 00:09
  • You can't. The environment is a snapshot of the environment when the app started up, not a dynamic thing. – tim_yates Mar 31 '17 at 08:30

1 Answers1

1

As others have said, strictly speaking you cannot alter environment variables of the running processs.

However, assuming you want to "do something like getenv" in order to get the values of certain variables following execution of your script, you can do something like this:

def map = [:]
def envAsText = ['sh', '-c', 'source myfile.conf 2>&1 >/dev/null && env'].execute().text
envAsText.eachLine { (key,value) = it.split('=', 2); map[key] = value }

This creates an empty map, then executes child process to "source" your file, filter out all output while sourcing, then print environment with "env" command. (also assuming unix-like system, which is implied from your "myfile.conf"). Finally, output is collected and stored to "map".

After this, "map" contains all environment of your child process (now finished), including "variable2":

map['variable2'] // this contains "Value2"
Hugues M.
  • 19,846
  • 6
  • 37
  • 65
  • This is not ideal because the second part after '=' can contain quotes – kivagant Jun 12 '19 at 19:34
  • Sure, this is not bullet proof. I think quotes would be preserved correctly, but newline characters would be a problem. – Hugues M. Jun 12 '19 at 19:40
  • Sorry, my comment was wrong. I messed up this with a Jenkins bug when it can't set empty variables in withEnv(). So just ignore me. – kivagant Jun 12 '19 at 19:53