[Java] Automate profile-based authentication of Code Artifact with Gradle

1 minute read

Introduction

It’s going to be very convenient because the repository is managed. However, when you read official document, load the token in the environment variable, Do you do such troublesome things every time? do not want to!

That’s why I wrote to read from the profile that will be set with AWS CLI.

Assumption

A profile of AWS CLI that can access any Code Artifact has been set

How to use

Copy the following in whole *If you want to drop the file directly, click here

build.gradle


buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath'com.amazonaws:aws-java-sdk-codeartifact:1.11.801'
}
}

import com.amazonaws.services.codeartifact.AWSCodeArtifactClient;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.codeartifact.model.GetAuthorizationTokenRequest;
def setAuthorizationToken = (mavenArtifactRepository, profile ->
def domainLevels = mavenArtifactRepository.url.getHost().split('\\.')
def artifactDomain = domainLevels[0].substring(0,domainLevels[0].lastIndexOf("-"))
def artifactOwner = domainLevels[0].substring(domainLevels[0].lastIndexOf("-")+1)
def region = domainLevels[domainLevels.length -3]

def client = AWSCodeArtifactClient.builder()
.withCredentials(new ProfileCredentialsProvider(profile))
.withRegion(region)
.build();

def result = client.getAuthorizationToken(new GetAuthorizationTokenRequest()
.withDomain(artifactDomain)
.withDomainOwner(artifactOwner)
);

mavenArtifactRepository.credentials {
username "aws"
password result.authorizationToken
}
}


apply plugin:'java'
apply plugin:'eclipse'

repositories {
maven {
url'https://trial-558497472117.d.codeartifact.us-west-2.amazonaws.com/maven/trial/'
setAuthorizationToken(owner, "profileName")
}
}

dependencies {
implementation platform('com.amazonaws:aws-java-sdk-bom:1.11.801')
implementation'com.amazonaws:aws-java-sdk-codeartifact'
}


Replace the following ```here

with your profile name.



```groovy
setAuthorizationToken(owner, "here") // ← profile name

Reference

Aside

If it’s s3, I don’t need to pull it from buildscript from the gradle wrapper (```lib\plugins\aws-java-sdk-s3-1.11.xxx.jar

)...

```

Since aws-java-sdk-codeartifact of buildscript cannot be drawn at first, it cannot be a standalone with only complete CodeArtifact. I can go after I cache it locally, but… There wasn’t a ```AWSCodeArtifactReadOnlyAccess

like AWS management policy yet. (Can you do it in the future?

``` (Can you do it in the future?

Note that CodeArtifact is not enough and sts:GetServiceBearerToken is also required!