Files
thpeetz-notes/Quellen/IT/Publishing Credentials Sample.md
T

2.9 KiB
Raw Blame History

title, source, tags
title source tags
Publishing Credentials Sample https://docs.gradle.org/current/samples/sample_publishing_credentials.html
IT/Development/Gradle
IT/Development/Maven
IT/Development/Java
IT/Development/Groovy
IT/Development/Kotlin

This sample shows how credentials can be used when publishing artifacts to a Maven repository using project properties. This approach allows you to keep sensitive configuration out of your projects source code and inject it only when needed.

The code in the maven-repository-stub directory builds a plugin used to stub the Maven repository in order to demonstrate the authentication flow. It expects the following hardcoded credentials on the server stub:

In a real project, your build would point to a private repository for your organization.

The published project has some sample Java code to be compiled and distributed as a Java library. Gradle build file registers a publication to a Maven repository using provided credentials:

build.gradle

publishing {
    publications {
        library(MavenPublication)  {
            from components.java
        }
    }
    repositories {
        maven {
            name =  'mySecureRepository'
            credentials(PasswordCredentials)
            // url = uri(<<some repository url>>)
        }
    }
}

Credentials will be required by the build only if the task requiring them is to be executed - in this case the task publishing to the secure repository. This allows to build the project without worrying about the credentials. Try running ./gradlew jar and it will succeed. Run ./gradlew publish and it will tell you what is missing right away, without executing the build. Credentials can and should be kept externally from the project sources and be known only by those having to publish artifacts, perhaps injected by a CI server.

Credential values are provided using Gradle properties and can be passed to the publish task in multiple ways:

  • via command-line properties:
$ ./gradlew publish -PmySecureRepositoryUsername=secret-user -PmySecureRepositoryPassword=secret-password
  • via environment variables:
$ ORG\_GRADLE\_PROJECT\_mySecureRepositoryUsername=secret-user ORG\_GRADLE\_PROJECT\_mySecureRepositoryPassword=secret-password ./gradlew publish
  • by setting the properties in gradle.properties file:
mySecureRepositoryUsername=secret-user
mySecureRepositoryPassword=secret-password

and running

The sensitive data is kept outside of the project sources since the gradle.properties file can reside in the users ~/.gradle directory.