11
votes

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?

5

5 Answers

13
votes

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

6
votes

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"
2
votes

I'm not sure about python but at least shell scripts can take parameters from Jenkins

/code/workspace/myscript.sh ${BUILD_NUMBER}

You just need to add it to the post steps

Jenkins post step screen

0
votes

Yes, environment variables that are generated by Jenkins itself are available in post-build steps (for your own environment variables, you will need EnvInject plugin)

You can run post-build "execute shell" or "execute batch command" step and just type set. Everything you see there is accessible.

0
votes

I had the same problem for a Freestyle project, too. I solved it now by moving the post build step into the build part itself (as last step there).