Passing -P Parameters From One Gradle Script To Another

This post explains how to call one Gradle build from another while propagating `-P` project properties through `GradleBuild` tasks. It focuses on the configuration needed to preserve parameterized behavior across chained scripts.

Coveros Staff

July 26, 2015

In Gradle, you can pass properties to a build script in many different ways. You could pass it via gradle.properties, you could pass through the -D (jvm params) options, or you could pass through the -P option (project properties).

I was facing a situation where I needed to call one Gradle build script from my current build script.

For example, I had my build script (build script #1) which displayed “This is $first $second first build script”, and from that build script, I wanted to call a different build script (build script #2) which displayed “This is $first $last second build script”. However, I did not define these three parameters in my gradle.properties, and I wanted to define them using Gradle’s -P option.

The end goal would be for me to be in the root directory of the first build script and type: “gradle build -Pfirst=marco -Plast-coronas” and the console would print: “This is marco coronas first build script. This is marco coronas second build script”.

In order to call one build script from a another build script, you need to define a task with the type “GradleBuild”:
task CallOtherBuildScript(type: GradleBuild){ buildFile = "${PathToTheBuildFile}" tasks = ['clean','build'] startParameter.projectProperties = project.getGradle().getStartParameter().getProjectProperties() }
Within a GradleBuild typed task, you can define many things; one essential variable to set is the build file, which corresponds to the other ‘gradle.build’ you are trying to call. Another essential variable to set is the tasks, which correspond to which tasks you want to run from this build script. Finally we get to the point of this blog, we want to propagate our -P parameters to the other build script. This is done by setting the startParameter’s project properties, which is shown on the last line of code.

Coveros Staff

Coveros Staff

This post represents the collective insights of the Coveros team. Our staff consists of software experts who bring deep experience in secure agile development, DevOps, testing, and software quality. Over the past 20 years, Coveros has trained more than 30,000 professionals and worked with half of the Fortune 100 companies on mission-critical software development challenges. We draw on this extensive experience to share practical insights, proven strategies, and real-world solutions that help organizations build better software faster and more securely.