Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins environment variables available during post build step

Tags:

jenkins

I understand that Jenkins sets certain environment variables during build execution. But my question is can I access those variables in my post-build script ?

I ran a quick test and I am unable to access PROJECT_NAME and BUILD_URL etc from a post build step python script.

Is there a way I can access these variables from a post build step python script ? Am I doing anything wrong?

like image 949
Ankur Agarwal Avatar asked Apr 29 '15 20:04

Ankur Agarwal


2 Answers

EnvInject plugin reads a properties file each time I need to export a variable.

So I implemented the needed functionality using Groovy PostBuild plugin in the first post-build step which reads all needed variables from a properties file and exports them for the next post-build steps:

/*
Inject environment variables using Groovy because EnvInject plugin is not user-friendly
*/

import hudson.model.*

def console = manager.listener.logger.&println

// read the props file
def props = new Properties()
new File("${manager.envVars['WORKSPACE']}/postbuild.props").withInputStream { 
    stream -> props.load(stream) 
}

props.each{
    key, value -> console("${key}:${value}")
    def pa = new ParametersAction([
        new StringParameterValue(key, value)
    ])
    manager.build.addAction(pa)
} 

And on each build step which needs to pass variables to post-build steps I do something like:

echo "hipchat_message=Server build succeded: <a href='https://$SERVER_NAME/'>$SERVER_NAME</a> (<a href='$BUILD_URL'>Job</a>)" > "$WORKSPACE/postbuild.props"
like image 147
warvariuc Avatar answered Oct 25 '22 14:10

warvariuc


Another solution is to use the Jenkins EnvInject Plugin to redefine the Jenkins parameters as environment variables:

enter image description here

This environment variable should be available in your post build step Python script.

On Linux and with a Shell script, I'm able to access both (Jenkins parameters and environment variables):

enter image description here

enter image description here

like image 27
Bruno Lavit Avatar answered Oct 25 '22 13:10

Bruno Lavit