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.

social