'How to pull a private docker image from AWS ECR to use with the Testcontainers library in Java/Kotlin?

I am trying to programmatically create and spin up a Testcontainers GenericContainer from a docker image hosted in a private AWS ECR repository. This will be used for automated integration tests, will be run locally and within CICD pipelines. I know I need to authenticate to pull down the image but it is not clear to me how best to get and pass authentication information from AWS to the Testcontainers context. I've read over the Testcontainers documentation but have not found details on how to authenticate to a private docker container repository.

Code I have so far is:

import org.testcontainers.containers.GenericContainer
import org.testcontainers.utility.DockerImageName

const val imageName = "<account>.dkr.ecr.<region>.amazonaws.com/<imageName>:<version>"
val testContainer = GenericContainer(DockerImageName.parse(imageName))
testContainer.start()

Of course, this gives an error:

at org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.execute(DefaultInvocationBuilder.java:247)
    at org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.lambda$executeAndStream$1(DefaultInvocationBuilder.java:269)
    at java.base/java.lang.Thread.run(Thread.java:833)
com.github.dockerjava.api.exception.InternalServerErrorException: Status 500: {"message":"Head \"https://<account>.dkr.ecr.<region>.amazonaws.com/v2/<imageName>/manifests/<version>\": no basic auth credentials"}

So far I have found Testcontainers to be intuitive to use for all things, but this problem has got me stumped. How does one use Testcontainers with private AWS ECR repositories?



Solution 1:[1]

testContainer.getDockerClient().authCmd()
                .withAuthConfig(new AuthConfig()
                .withUsername(username)
                .withPassword(password)
                .withAuth(auth)
                .withEmail(email)
                .withIdentityToken(identityToken)
                .withRegistryAddress(registryAddress)
                .withRegistrytoken(registryToken));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1