logo

AWS Exam GuidesNewsletterBlogContact

👋 Hey! My name is Wojciech Gawroński, but others call me AWS Maniac.

My goal is to safely guide you through the cloudy and foggy space of the AWS portfolio.

Our first Construct in AWS CDK

6 min read, last updated on 2020-12-22

Constructs are one of the foundational things available in the AWS CDK. Outside of being a key element, they require a significant shift in thinking, especially in stacks composition and reusability.

In this article, we will address that difference in practice, returning to our example related to preparing workshop environments for our participants.

What is a Construct in AWS CDK?

Let’s start with the official definition:

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.

A construct can represent a single resource, such as an Amazon Simple Storage Service (Amazon S3) bucket, or it can mean a higher-level component consisting of multiple AWS CDK resources. Examples of such features include a worker queue with its associated compute capacity, a cron job with monitoring resources and a dashboard, or even an entire app spanning multiple AWS accounts and regions.

Definition of the CDK Construct from the official documentation.

Well, that is a start, although I had some questions initially: what the hell is a cloud component? Here lies the thing which, in my opinion, leads to the biggest culprit related to the AWS CDK.

This tool is advertised as a compiler high-level programming language (imperative) code to the cloud assembly represented by the CloudFormation templates. That association points to think that our experience with CF can be helpful, and that’s why we are projecting those experiences into a new tool. And it may sound counterintuitive, but that is a mistake.

We are grouping resources into CloudFormation stacks and templates using totally different reasons than we should apply here, e.g., with CF, we were directed by convenience (maintaining the lesser number of stacks in the end) and a common reason to change.

First thing first: we should not mix Construct with a Stack. Secondly: this tool tries to resolve both concerns by introducing automation around stacks and their management, plus introducing Construct as a way to abstract certain reusable parts without using the Stack concept.

Let’s talk about hierarchies and layers!

There are different levels of constructs available in the AWS CDK.

  1. Low-level constructs, which we call CFN Resources. These constructs represent all of the AWS resources that are available in AWS CloudFormation. They are crude and directly transferable to CloudFormation templates, so you need to configure and provide everything available in the CloudFormation.
  2. The next level of constructs also represents AWS resources, but with a higher-level, intent-based API. They provide the same functionality but handle much of the details, boilerplate, and glue logic required by CFN constructs. Remember the intent-based term because it will reappear soon, and it is essential.
  3. Last but not least - higher-level constructs, which we call patterns. These constructs are designed to help you complete everyday tasks in AWS, often involving multiple kinds of resources, e.g., one of aws-ecs-patterns: ALBFargateService Construct, which represents (as the name suggests) an architecture that includes an AWS Fargate container cluster employing an Application Load Balancer (ALB).

If you are a programmer, you see the pattern here: we employ the most powerful technique available to us (and no, I’m not talking about bugs 😂) - composition.

As you can see above, we are defining higher-level abstractions through constructs. Such a high-level construct can be composed of any number of lower-level constructs, and in turn, those could be formed from even lower-level constructs. Here comes the game-changer: you are not optimizing your resource graph for a tool and convenience, but you should and can think about its purpose/intent.

To support that, constructs are always defined within the scope of another construct. This scoping pattern results in a hierarchy of constructs known as a construct tree. In the AWS CDK, the tree’s root is always represented by AWS CDK App. Inside it, you typically define one or more Stacks, which are the unit of deployment, analogous to AWS CloudFormation stacks. Inside stacks, you create resources or other constructs that will eventually contain resources.

Now here comes the real power! Thanks to the composition of constructs, we can define reusable components and share them like any other code. And that refers to all pros and cons of that approach - sharing commons between people and teams is excellent but requires tools and attention when it comes to updates, bug fixes, and improvements. Luckily, as this is a regular code, you can apply all battle-tested workflows you already have.

The talk is cheap. Show me the code.

So, how can it look like a real-world example? Thankfully AWS documentation has a great example in the form of NotifyingBucket:

import { Construct } as cdk from '@aws-cdk/core';

import * as s3 from '@aws-cdk/aws-s3';
import * as sns from '@aws-cdk/aws-sns';

export interface NotifyingBucketProps {
  prefix?: string;
}

export class NotifyingBucket extends Construct {
  public readonly topic: sns.Topic;

  constructor(scope: Construct,
              id: string,
              props: NotifyingBucketProps) {
    super(scope, id);

    const bucket = new s3.Bucket(this, 'bucket');

    this.topic = new sns.Topic(this, 'topic');

    bucket.addObjectCreatedNotification(this.topic, {
      prefix: props.prefix
    });
  }
}

And then in another file, we can import construct presented above and use it in the following way:

const queue = new sqs.Queue(this, 'NewImagesQueue');
const images = new NotifyingBucket(this, 'Images');

images.topic.addSubscription(new sns_sub.SqsSubscription(queue));

Let’s return to our example: we need to provide a working workshop environment with shared infrastructure and a dedicated set of resources for each participant, including his IAM user.

How we solved that in our code?

We basically created 4 constructs:

  1. First is a stack for the shared resources used by everybody,
  2. Second is a stack for the participant’s resources.
    • There, we have used constructs for representing:
      1. Participant’s VPC,
      2. IAM account for the participant, including other resources (e.g., a private bucket).

Below you can find an excerpt from the whole project - a definition of the VPC construct (you can find complete sources on my Github account):

import * as cdk from '@aws-cdk/core';

import * as ec2 from '@aws-cdk/aws-ec2';

const DEFAULT_CIDR_IPV4: string = "10.0.0.0/16";
const DEFAULT_NUMBER_OF_AZS: number = 3;

export interface ParticipantVpcProps {
  cidrIPv4?: string
  numberOfAZs?: number
}

export class ParticipantVpc extends ec2.Vpc {

  constructor(scope: cdk.Construct,
              id: string,
              props?: ParticipantVpcProps) {
    super(scope, id, {
      cidr: props?.cidrIPv4 || DEFAULT_CIDR_IPV4,

      enableDnsHostnames: true,
      enableDnsSupport: true,

      maxAzs: props?.numberOfAZs || DEFAULT_NUMBER_OF_AZS,
      natGateways:
        props?.numberOfAZs || DEFAULT_NUMBER_OF_AZS
    });

    // We need a security group that allows
    // for SSH to this VPC.

    const ssh = new ec2.SecurityGroup(this, 'SG-SSH', {
      securityGroupName: 'ssh-opened',
      vpc: this,
      allowAllOutbound: true
    });

    ssh.addIngressRule(
      ec2.Peer.anyIpv4(), ec2.Port.tcp(22)
    );

    ssh.addIngressRule(
      ec2.Peer.anyIpv6(), ec2.Port.tcp(22)
    );

    // We need an S3 VPC gateway endpoint for the
    // private subnets in this VPC.

    const selection = [
      { subnetType: ec2.SubnetType.PRIVATE }
    ];

    this.addS3Endpoint('S3-VPCE', selection);
  }

}

New Possibilities

So knowing what it is and how it looks, we need to practice and prepare more and more of those. We also know that this approach enables internal constructs and patterns available in the framework. However, that is not everything - as there are external repositories, like this one cdk-patterns/serverless, which contains more and more patterns built by the community. It’s not hard to imagine that we will have a significant library of existing patterns waiting for reuse in our projects with proper momentum and time spent on it.

It was a longer article, but a necessary one - constructs are so prevalent in the CDK, so we need to dedicate some space. Understanding this concept is critical in the effective use of the AWS CDK.

So what’s next? We will tackle another topic that requires a shift in thinking - parametrization of CDK stacks and application.

Subscribe to the newsletter and get notifications about new posts.

Subscribe

👋 Hey! My name is Wojciech Gawroński, but some people call me AWS Maniac. I am your trusted guide through the AWS Madness. If you want to learn more about me, you can start here.

Share it:

YouTube, Twitter, LinkedIn, Instagram, Facebook
awsmaniac.com © 2021, built with Gatsby and template from @kjendrzyca