Search

Dark theme | Light theme

November 17, 2009

Gradle Goodness: Using Properties for Multiple Environments or Profiles

A Gradle build script is a Groovy script, and this means we can use all classes available to Groovy in our Gradle build scripts. In this post we use the ConfigSlurper to read in properties for our project. The ConfigSlurper supports environments where we can define values for properties per environment. Suppose we have a dev, test and prod environment than we can define different values for the same property per environment. We can also override a default value in the environments section.

In our Gradle build script we look for a property env. We can pass a value for the env property to the build with the -P or --project-prop argument when we run Gradle. If the property is available we use the value to read in the properties for that environment. If the env property is not available we assume the default dev environment. Finally we assign the Config object (with all properties) returned by the ConfigSlurper to the project property config. In the Gradle build script we can access the properties with dotted notation: config.propName.

// File: build.gradle
loadConfiguration()

task printProps << {
    println "serverName:  $config.serverName"
    println "mail.server: $config.mail.server"
    println "mail.port:   $config.mail.port"
}

def loadConfiguration() {
    def environment = hasProperty('env') ? env : 'dev'
    setProperty 'environment', environment
    println "Environment is set to $environment"
    
    def configFile = file('config.groovy')
    def config = new ConfigSlurper(environment).parse(configFile.toURL())
    setProperty 'config', config
}
// File: config.groovy
mail {
    server = 'localhost'
    port = 25
}

environments {
    dev {
        serverName = 'http://localhost:9090'        
    }
    
    test {
        serverName = 'http://testserver'
        mail {
            server = 'mail.testserver'
        }
    }
    
    prod {
        serverName = 'http://www.mrhaki.com'
        mail {
            port = 552
            server = 'mail.host.com'
        }
    }
}

We run Gradle with different values for the env property to see the values of the properties:

$ gradle -q printProps
Environment is set to dev
serverName:  http://localhost:9090
mail.server: localhost
mail.port:   25

$ gradle -q -Penv=dev printProps
Environment is set to dev
serverName:  http://localhost:9090
mail.server: localhost
mail.port:   25

$ gradle -q -Penv=test printProps
Environment is set to test
serverName:  http://testserver
mail.server: mail.testserver
mail.port:   25

$ gradle -q -Penv=prod printProps
Environment is set to prod
serverName:  http://www.mrhaki.com
mail.server: mail.host.com
mail.port:   552

Written with Gradle 0.8.