Building for different environments with Gradle

Apr 16, 2011   #build  #gradle 

Gradle is a promising build tool. It offers ease of use as well as great flexibility when designing your build process. Here is how I use Gradle to configure my build artifact for different environments such as “development” and “production”.

  • Create a directory for every environment you want to build for in src/main/environment e.g. src/main/environment/dev and src/main/environment/prod.

  • Put all of your environment dependent config files (jdbc.properties, context.xml etc.) there instead of src/main/resources.

  • Create a file tasks.gradle next to build.gradle with the following content:

    task copyConfiguration << {
        println "Target environment: $environment"
    
    
        copy {
            from "src/main/environment/$environment"
            into "src/main/resources"
            include "**/*"
        }
    }
    
  • Add these lines at the beginning of build.gradle:

    loadConfiguration()
    
    
    def loadConfiguration() {
        def environment = hasProperty('env') ? env : 'dev'
        setProperty 'environment', environment
    }
    

This will set the environment to dev if you run your build without an environment parameter. You can pass in an environment with the -P parameter like gradle -Penv=prod build.

  • Include the task file created before in your build.gradle and define a dependency that makes sure the environment configuration files are copied to src/main/resources before building:
apply from: 'tasks.gradle'

processResources.dependsOn copyConfiguration

That’s it. You can now configure your build every time you execute it by passing in the environment name as a project property (gradle -Penv=prod build).