Gradle Builds with Private Maven Repositories on Bitbucket Pipelines

Gradle Builds with Private Maven Repositories on Bitbucket Pipelines

It's common to use private Maven repositories to host internal artifacts. These repositories usually require authentication when accessing. The username and password for these repositories are stored in the ~/.m2/settings.xml. This post shows how can we configure Gradle to publish to private repositories and integrate with Bitbucket Pipelines or other CI services.

Configure Gradle to use Maven settings.xml

The Maven settings.xml already contains user authentication information, so we can use it when publishing. We'll use the plugin maven-publish for publishing and maven-publish-auth for retrieving the authentication information.

In the build.gradle file below, gradle-maven-publish-auth is the plugin to retrieve authentication information. The repository snapshots is the private repository for publishing.

buildscript {
    repositories {
        mavenCentral()
        maven {
            url "http://repository.jboss.org/nexus/content/groups/public/"
        }
    }
    dependencies {
        classpath 'org.hibernate.build.gradle:gradle-maven-publish-auth:2.0.1'
    }
}

group 'com.mycompany'
version '1.0.0-SNAPSHOT'

apply plugin: 'maven-publish'
apply plugin: 'maven-publish-auth'

repositories {
    mavenCentral()
}

dependencies {
    testCompile "junit:junit:4.12"
}

publishing {
    repositories {
        maven {
            name "snapshots"
            url "http://local.maven"
        }
    }
    publications {
        mavenJava(MavenPublication) {
            from components.java
        }
    }
}

When we run gradle publish, the built artifact is published to the Maven repository.

Integrate with CI services

To integrate with CI services, we need to configure the build environment for using the private Maven repository. For Bitbucket Pipelines, it's possible to use mvn -s to specify the path of settings.xml. However, this doesn't work for Gradle builds. For Gradle builds, it's also possible to use the environment variable maven.settings to specify the path of settings.xml. But this requires each repository to have its own copy of settings.xml file.

A better choice is to use a custom Maven Docker image that includes the settings.xml.

FROM maven:3.5.2-jdk-8-alpine

COPY settings.xml ${MAVEN_CONFIG}/

Bitbucket Pipelines supports using Amazon ECS.

Below is the bitbucket-pipelines.yml file.

image:
  name: <aws_account_id>.dkr.ecr.<region>.amazonaws.com/maven
  aws: 
    access-key: $AWS_ACCESS_KEY
    secret-key: $AWS_SECRET_KEY

pipelines:
  default:
    - step:
        caches:
          - gradle
        script: 
          - bash ./gradlew publish    
© 2023 VividCode