Menu

AWS CDK: Custom Constructs

Mar 7, 2022

Having worked for a while with terraform, I always felt that learning a whole new DSL to provision infrastructure was a bit unnatural. Therefore, when I started hub, I decided to look around and check for alternatives. The AWS Cloud Development Kit or AWS CDK allows you to code your infrastructure with a regular programming language, e.g. python, and immediately felt more natural. The CDK has the following base components:

Construct

Constructs are the basic building blocks of AWS CDK apps. A construct represents a “cloud component” and encapsulates everything AWS CloudFormation needs to create the component.

Stack

The unit of deployment in the AWS CDK is called a stack. All AWS resources defined within the scope of a stack, either directly or indirectly, are provisioned as a single unit.

Higher level abstraction by combinining multiple constructs into a single one is what makes this kit a winner for me. Let’s take a look at how this website is configured and deployed:

The infra stack

The infra stack is our container for combining multiple constructs:

from aws_cdk import (
    core
)


class Infra(core.Stack):

    def __init__(self, scope: core.Construct, id: str, props, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

The custom constructs

Using directly the constructs from the kit in the stack will work, but we could take this a step further and build our own constructs that we abstract the wiring into an easy to consume custom constructs, e.g.

from aws_cdk import (
    core,
    aws_codebuild as cb,
    aws_codepipeline as cp
)


class CustomPipeline(core.Construct):
    def __init__(self, scope: core.Construct, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        cp.Artifact(...)
        cb.Source.git_hub(...)
        cb.Project(...)
        cb.PipelineProject(...)
        cp.Pipeline(...)

The app

Last, we just need to reference our new stack(s) into the core application:

from aws_cdk import core

app = core.App()
stack = Infra(app, ...)
app.synth()

Related tags:

Site menu

Back to top