Saturday, November 28, 2015

Export environment variables for post-build steps in Jenkins

I needed a way to pass environment variables to post-build steps in Jenkins. HipChat notification plugin allows to use environment variables in its templates, but I cannot use commands there, so the template flexibility is quite limited.

So I wanted to make the message text in a build step and then pass it to the post-build HipChat notifications step.

There is EnvInject Plugin to accomplish this, but I found it to be not user-friendly -- I had to use two steps: 1) echo values to a properties file; 2) then use EnvInject to read the values from the file and export them.

I found a solution that suits me better. In build steps I only create/update the properties file:

echo "hipchat_message=Server build succeded: <a href='https://$SERVER_NAME/'>$SERVER_NAME</a> (<a href='$BUILD_URL'>Job</a>)" > "$WORKSPACE/postbuild.props"

and then in the first post-build step use this Groovy script:

/*
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)
} 

1 comment:

  1. Thank you, THANK YOU, THANK YOU!
    This is such a broken "feature" in Jenkins, this script did _EXACTLY_ what I needed!

    ReplyDelete