Adding the Git Revision to a Docker Image

Spring Boot makes it quite easy to find the Git revision of a running application. You add a Gradle plugin and the revision is added to the Actuator’s info endpoint. What it doesn’t do though is publish the Git revision as part of the SBOM or OCI metadata. That requires some manual work.

The basic idea is using the data that the gradle-git-properties plugin makes available and pass it in an environment variable to the Paketo Image Labels Buildpack.

First of all, you need the mentioned Gradle plugin, which puts a git.properties file on the classpath:

plugins {
    // ...
    id 'com.gorylenko.gradle-git-properties' version '2.4.0'
}

That file is picked up and exposed as a GitProperties bean to the Spring Boot application – this is how the Actuator picks it up and adds it to its info endpoint.

Several attempts with Groovy’s string interpolation failed, but this is how it finally worked:

gitProperties {
    extProperty = 'gitProps'
}

generateGitProperties.outputs.upToDateWhen { false }

task addRevision(dependsOn: 'generateGitProperties') {
    doLast {
        bootBuildImage.environment['BP_OCI_REVISION'] = gitProps['git.commit.id']
    }
}

bootBuildImage {
    imageName = "registry.mafr.de/mafr/${project.name}"
    environment = [
        "BP_OCI_VENDOR": "mafr.de",
        "BP_OCI_VERSION": version,
    ]
}

bootBuildImage.dependsOn addRevision

You build the image as usual:

$ ./gradlew bootBuildImage

The labels are visible when inspecting the image.

If anyone finds an easier way to do this with Gradle, please let me know.

This entry was posted in java and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s