Making a Hudson /Jenkins build number available to a Grails application

It’s a quick note on how to make a Hudson / Jenkins build number available to a Grails app.

  • Jenkins / Hudson make the current build number available through the environment variable “BUILD_NUMBER”.
  • Grails exposes at runtime the application meta-data from the file “application.properties”
  • Grails fires a pre-WAR-creation event called “CreateWarStart” that can be utilized to make the running Jenkins/Hudson build number available through Grails application level meta-data.

Below is the Grails event handler that connects the dots above when you build your Grails app’s WAR (scripts/_Events.groovy):

eventCreateWarStart = { warName, stagingDir ->
    def buildNumber = System.getenv('BUILD_NUMBER')
    if(buildNumber) {
        ant.propertyfile(file:"${stagingDir}/WEB-INF/classes/application.properties") {
            entry(key:'build.number', value: buildNumber)
        }
    }
}

This build number can be retrieved at run-time using any of the following:

  • In GSP pages
  • <g:meta name="build.number"/>
    
  • In Groovy code
  • def buildNumber = grailsApplication.metadata['build.number']
    

You can learn more about hooking into Grails events here.

Advertisements