adam bien's blog

Building Reusable "Cloud Components" / Constructs with AWS CDK, Java and Maven 📎

An AWS CDK construct encapsulates a reusable piece of cloud infrastructure. In our example it is the Amazon Elastic Container Registry :


import software.amazon.awscdk.services.ecr.Repository;
import software.constructs.Construct;

public class AirhacksECR extends Construct {

    private Repository repository;

    public AirhacksECR(Construct scope, String id, String repositoryName) {
        super(scope, id);
        this.repository = Repository.Builder.create(scope, id + "-ecr")
            .imageScanOnPush(true)
            .repositoryName("airhacks/" + repositoryName)
            .build();
    }
    
    public Repository getRepository() {
        return this.repository;
    }
}    

Such a construct can be compiled and deployed (mvn install) into a local or remote Maven repository, but requires the declaration of the following dependencies:


<dependency>
    <groupId>software.amazon.awscdk</groupId>
    <artifactId>aws-cdk-lib</artifactId>
    ...recent version
</dependency>
<dependency>
    <groupId>software.constructs</groupId>
    <artifactId>constructs</artifactId>
    ...recent version
</dependency>

Let's assume the construct's GAV coordinates are:


<groupId>airhacks</groupId>
<artifactId>ecr</artifactId>
<version>0.1</version>

After a successful compilation and deployment, the construct becomes available to other CDK projects via the following dependency:


<dependency>
    <groupId>airhacks</groupId>
    <artifactId>ecr</artifactId>
    <version>0.1</version>
</dependency>

Now an opinionated AWS ECR registry can be created via the AirhacksECR construct:


import software.constructs.Construct;
import airhacks.ecr.AirhacksECR;
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.StackProps;

public class CDKStack extends Stack {

    public CDKStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);

        var ecr = new AirhacksECR(this, id, "live");
        var repository = ecr.getRepository();
    }
}

See it in action - deployment included:

The template: https://github.com/adambien/aws-cdk-plain was used in both projects.