Out of the box Jenkins can extract the metadata from Maven build for use as environment variables in the build steps, but it doesn’t have the same support for Gradle. This can be achieved using the EnvInject plugin, and a custom task in your build.gradle file.

The first step is to setup a task in build.gradle that will print out the project name and version in a format that can be used directly in a properties file.

task projectDetails {
    doLast {
        println "PROJECT_NAME=${project.name}"
        println "PROJECT_VERSION=${project.version}"
    }
}

You can test this works by running ./gradlew -q projectDetails and you should see something like

PROJECT_NAME=MyProject
PROJECT_VERSION=0.2

Now, to get these values in the Jenkins build environment we need the EnvInject plugin. The trick here is that EnvInject plugin doesn’t allow environment variables to be set from scripts (or at least not any obvious way), so we do this in a two step process. First, select the Build Environment step called Inject environment variables to the build process. Then in its script contents place the code

./gradlew -q projectDetails > build-env.properties

Build environment

This will place the environment variables into a properties file that we’ll read in during the next step.

Next, add a Build task called Inject environment variables to the top of the build tasks, and supply the name build-env.properties as the properties file path.

Build step 1

Now you can use $PROJECT_NAME and $PROJECT_VERSION in your build steps.

Note, the reason we can’t do all this in one step in the Environment setup is that the properties file is read prior to running the script contents. And the script contents can’t affect the environment. Perhaps a Groovy script could read the value return the environment variables, but that is for someone else to figure out.