Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
AWS CDK in Practice
AWS CDK in Practice

AWS CDK in Practice: Unleash the power of ordinary coding and streamline complex cloud applications on AWS

Arrow left icon
Profile Icon Mark Avdi Profile Icon Leo Lam
Arrow right icon
€20.98 €29.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (12 Ratings)
eBook Jun 2023 196 pages 1st Edition
eBook
€20.98 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Mark Avdi Profile Icon Leo Lam
Arrow right icon
€20.98 €29.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (12 Ratings)
eBook Jun 2023 196 pages 1st Edition
eBook
€20.98 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€20.98 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

AWS CDK in Practice

Getting Started with IaC and AWS CDK

Infrastructure as code (IaC) is the standard practice of defining various infrastructure components using code. You must have heard about a few of these software tools, such as Chef, Puppet, Terraform, or the old-school Bash programming, to set up servers in a predictable way.

The need for IaC was born out of the toolset for spinning up servers circa 2006 lacking the predictability, speed, and agility of the code used in programs that were deployed onto servers. Pre IaC, the normal workflow of deploying something on AWS would be this:

  1. Spinning up Elastic Compute Cloud (EC2) servers manually via the dashboard
  2. SSHing into the machines
  3. Copying some Bash configuration files using Secure Copy Protocol (SCP)
  4. Running them in a certain sequence to deploy an application
  5. Configuring database connections

This is one of the better scenarios of how things were done back then.

Needless to say, this method was not scalable, repeatable, or reliable enough to deal with the ever-increasing complexity of web applications on the cloud. Around the same time, tools such as Chef, Puppet, and a few others showed up, which helped immensely with server configuration.

A couple of years later, tools such as Terraform popped up, which at the time were quite revolutionary in the way that they defined the desired state of the deployment on a given cloud service provider (CSP) such as Amazon Web Services (AWS) in a declarative fashion. This configuration would then be fed into the Terraform toolset, which would then decide which AWS services needed to be created, deleted, or modified. Let’s look at one such Terraform configuration file:

resource "aws_instance" "single-instance"{
  ami           = "ami-ebd02392"
  instance_type = "t2.micro"
  subnet_id     = "subnet-eddcdzz4"
  vpc_security_group_ids = ["sg-12345678"]
}

The preceding Terraform configuration file defines an AWS EC2 server using the aws_instance resource type provided by Terraform’s AWS provider and then is given an Amazon Machine Image (AMI) configuration (which is essentially the operating system image) instance type to define its CPU and RAM configuration and other network settings. If you have Terraform set up correctly locally, this will investigate your AWS setup, see that this server doesn’t exist, and then proceed to create this server for you.

Obviously, this is a very simple example. There are Terraform configuration projects with many thousand lines of configuration files. These projects can get quite elaborate and out of hand once the complexity of the deployment increases. There are various remedies for this, none of which—in our opinion—really addresses the issue here. Have you spotted the problem?

The problem is that these configurations are not really defined as code. They are defined as declarations in a declarative language that are not Turing Complete code blocks.

In this chapter, we will cover the following main topics:

  • Introduction to AWS CDK
  • Setting up your local environment and writing your first CDK app
  • Creating a containerized web application in AWS CDK using Docker
  • Understanding the inner workings of AWS CDK

Technical requirements

You will be able to find the code associated with this book in this GitHub repository: https://github.com/PacktPublishing/AWS-CDK-in-Practice.

This repository is organized into directories for each chapter. This code in this chapter can be found in this directory: https://github.com/PacktPublishing/AWS-CDK-in-Practice/tree/main/chapter-1-getting-started-with-iac-and-aws-cdk.

The code examples provided in this book are written in TypeScript. Cloud Development Kit (CDK) supports JavaScript, Python, Java, and C#. We’re sticking with TypeScript since it’s the best supported of the bunch by the CDK development team, and every feature, doc, or material is first released on TypeScript and then translated into other programming languages.

That said, converting the TypeScript code samples in this book into the programming language of your choice is relatively easy since the framework follows a set of common interface definitions. AWS has a handy guide for you: https://docs.aws.amazon.com/cdk/v2/guide/multiple_languages.html.

Do also note that to work with CDK, you will need an AWS account. You can sign up for one here: https://portal.aws.amazon.com/billing/signup.

For more advanced users, we recommend setting up a different AWS organization for working with CDK while you’re learning the ropes so that your development doesn’t interfere with applications that you might have already spun up in your account. You can find out more about AWS Organizations here: https://aws.amazon.com/organizations/.

We also highly recommend setting AWS billing alarms. We will keep things within the free tier of various services as much as we can in this book and will destroy stacks as soon as we’ve spun them up and interacted with them. But it’s best to be on the safe side and set a spending alarm in case mistakes happen or you forget to destroy stacks. A spending alarm of $10 should do the trick. The following link describes how you can do this: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html.

The Code in Action video for this chapter can be viewed at: https://packt.link/nX11h.

Introduction to AWS CDK

In the introduction to this chapter, we covered a basic history of IaC and how these software tools lack the expressiveness of modern programming languages. AWS without a doubt is the frontrunner in the cloud industry, and its answer to difficult infrastructure setup is CDK.

In AWS’s own definition, CDK is an open source software development framework—notice how AWS is not calling it an infrastructure provisioning framework—that defines AWS resources for a cloud application using familiar programming languages.

AWS’s definitiomeans, for example, that instead of defining the EC2 instance using declarative configuration files as we did with Terraform’s HashiCorp Configuration Language (HCL) in the intro, you can define the same instance as the following:

import * as cdk from '@aws-cdk/core'
import * as ec2 from '@aws-cdk/aws-ec2'
 export class MyAppStack extends Stack {
  public readonly default_vpc: IVpc;
  public readonly my_virtual_machine: Instance;
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    this.default_vpc = Vpc.fromLookup(this, 'VPC', {
      // This will get the default account VPC
      isDefault: true,
    });
    this.my_virtual_machine = new Instance(this, 'single-intance', {
      // The type of instance to deploy (e.g. a 't2.micro')
      instanceType: new InstanceType('t2.micro'),
      // The type of image to use for the instance
      machineImage: new AmazonLinuxImage(),
      // A reference to the object representing the VPC
      vpc: this.default_vpc,
    });
  }
}

Note

Don’t worry about running the code in this section; we will get into that after we’ve completed setting up your local machine for CDK development.

You might (rightfully) think that in terms of lines of code, this doesn’t really save you much time. It’s more or less the same amount of configuration we declare. Let’s see what happens if we want to declare 100 EC2 instances:

import * as cdk from '@aws-cdk/core'
import * as ec2 from '@aws-cdk/aws-ec2'
 export class MyAppStack extends Stack {
  public readonly default_vpc: IVpc;
  public readonly my_virtual_machines: Instance[];
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    this.default_vpc = Vpc.fromLookup(this, 'VPC', {
      isDefault: true,
    });
    this.my_virtual_machines = [...Array(100).keys()].map(
      i =>
        new Instance(this, `single-intance-${i}`, {
          instanceType: new InstanceType('t2.micro'),
          machineImage: new AmazonLinuxImage(),
          vpc: this.default_vpc,
        }),
    );
  }
}

Are you excited yet? Let’s now imagine we want to deploy 100 EC2 instances and we want every odd one to be a t2.large instance type instead. Let’s also throw in a Simple Storage Service (S3) bucket too and give all the programs that run within our VMs read access to some files in this S3 bucket. Perhaps there is a shell script in there that we want them to run as soon as they spin up. The following CDK code does exactly that:

import { RemovalPolicy, Stack, StackProps } from 'aws-cdk-lib/core';
import { Instance, InstanceType, AmazonLinuxImage, Vpc, IVpc } from 'aws-cdk-lib/aws-ec2';
import { Bucket } from 'aws-cdk-lib/aws-s3';
import { Construct } from 'constructs';
export class MyAppStack extends Stack {
  public readonly bucket: Bucket;
  public readonly default_vpc: IVpc;
  public readonly my_virtual_machines: Instance[];
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    this.default_vpc = Vpc.fromLookup(this, 'VPC', {
      isDefault: true,
    });
    this.my_virtual_machines = [...Array(100).keys()].map(
      i =>
        new Instance(this, `single-intance-${i}`, {
          instanceType: new InstanceType(i % 2 ? 't2.large' : 't2.micro'),
          machineImage: new AmazonLinuxImage(),
          vpc: this.default_vpc,
        }),
    );
    this.bucket = new Bucket(this, 'MyBucket', {
      removalPolicy: RemovalPolicy.DESTROY,
    });
    this.my_virtual_machines.forEach(virtual_machine => {
      this.bucket.grantRead(virtual_machine);
    });
  }
}

As you can see, CDK is an extremely versatile IaC framework. It unleashes the power of programming languages and compilers to declare highly complex AWS infrastructure with code that is, compared to the alternatives, easily readable and extensible. We can loop, map, reference, write conditions, and—more importantly—use the helper functions CDK provides to simplify the previously daunting task of implementing IaC.

This is a revolutionary concept. Full stack developers no longer must learn convoluted domain-specific languages (DSLs) to interact with AWS services; they can bring their current development skills to the world of cloud provisioning. There is no longer a context switch between development and DevOps. You no longer need to leave your IDE, and you can build and deploy the CDK infrastructure using common tools you’ve previously used—for example, npm.

Additionally, CDK has powerful customization and component sharing baked in. You can create batches of stacks, with your own set of governance and compliance requirements as reusable components. A set of certain EC2 machines with AWS Systems Manager parameter store configuration, security groups, certificates, and load balancers that is common within your stack can then be defined as a component (or in CDK terms, a construct) and then initialized and reused as many times as you desire. This is the true power of CDK, and it unleashes countless new opportunities for developers, as we will explore in the following chapters.

Till now, we’ve learned why CDK is cool. We hope you grow to love the toolset just as much as I do as you apply it to your own programming stack. Let’s now get into the good bits and start off by setting up your local machine for CDK development.

Setting up your local environment and writing your first CDK app

AWS CDK comes with two important tools, as follows:

  • The AWS CDK v2 standard library, which includes constructs for each of the AWS services
  • The CDK CLI, which is a command-line tool for interacting with apps and stacks

Before setting these up, let’s go ahead and set up AWS’s main CLI application to aid us with our CDK setup and deployments later on.

Setting up the AWS CLI and profile

To use CDK to provision AWS services, we will first need to set up our local machine with the configuration it needs to work with AWS. The easiest way to do this is via the AWS CLI.

Note

The AWS CLI is different from the AWS CDK CLI. The AWS CLI is mainly used to interact with AWS via command-line or Bash scripts, but it also comes in handy when using CDK.

AWS has detailed AWS CLI installation documentation for various operating systems and processor architectures, which can be found by visiting the following link: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html.

Follow the steps required for your operating system and come back here once you’re done.

We hope that wasn’t too painful. we’re on macOS, which seems to have the fewest steps of them all. Next, let’s check the installation was successful by running the following command:

$ aws --version

If all has gone well during the installation process, you should be seeing an output like the following screenshot:

Figure 1.1 – AWS CLI version output

Figure 1.1 – AWS CLI version output

Next, let’s create a separate profile for this book. As mentioned in the Technical requirements section, We highly recommend you create a separate account while you’re developing with CDK rather than using the account you normally use in your day-to-day activities.

Log in to the AWS account of your choosing, and once logged in, type IAM in the search box at the top of the AWS dashboard:

Figure 1.2 – Finding IAM in the sea of AWS services

Figure 1.2 – Finding IAM in the sea of AWS services

Click on IAM next, and from the menu on the left, select Users:

Figure 1.3 – Users section in IAM

Figure 1.3 – Users section in IAM

From the list of users, click on your own username. You will be taken to the user dashboard where the Permissions tab is active:

Figure 1.4 – IAM user roles

Figure 1.4 – IAM user roles

As you can see in the preceding screenshot, we’ve given our user AdministratorAccess permissions so that we have free rein on spinning up various services via CDK. Otherwise, we will have to constantly come back here and give ourselves service-specific permissions to spin up services.

If you are the root account holder, you should already have these permissions assigned to you. If not, you can click on Add permissions to search for your username and give yourself this permission, or it might be something that you have to ask your account administrator to do for you.

Important note

It’s generally not advised to use the root account to spin up services via CDK or any other means directly. The root account should be used to give granular permissions to secondary users that can then deploy CDK stacks. We are, for now, skipping such steps to simplify the instructions.

Next, click on the Security credentials tab. Under Access keys, click Create access key. A popup should appear offering you the option to download the credentials as a CSV file or copy them directly from the popup. You can do whichever one of them you like. Once we use the credentials, don’t forget to delete the CSV file on disk.

Now that we have the keys file downloaded from the AWS console, let’s configure our local environment with these given keys. Run the following command:

$ aws configure --profile cdk

You will be prompted to enter the AWS access key ID. You can get this from the CSV file you downloaded or the value you copied over from the previous step. Once you have done this, press Enter.

Next, you will be prompted to enter the AWS secret access key. Just as in the previous step, copy this over and press Enter.

Now you will be prompted to enter a default Region name. We normally work within us-east-1 since it’s one of the cheapest Regions (yes—AWS pricing differs per Region) and one of the first ones to receive new services and products. You can choose a Region near your geographical location if response promptness during the course of this book matters to you. us-east-1 has been selected—off we go.

Last, the tooling will ask you for a default output format; enter json.

Now, let’s make sure you’ve set things up right. To do that, run the following command:

$ aws configure list --profile cdk

If you see an output like the one shown in the following screenshot, voilà! You’re all set:

Figure 1.5 – Checking the configuration with the AWS CLI

Figure 1.5 – Checking the configuration with the AWS CLI

Important note

As you see, even though the list command covers most of our keys and secrets, we’re not taking any chances because even the last few characters could be used by a malicious actor for tracking. Keep your AWS keys as secret as your bank account details because if leaked, you could take a considerable financial hit.

Setting up the AWS CDK CLI

The AWS CDK CLI is a command-line tool that is installed as an npm package. If you’re a JavaScript or TypeScript developer, you will have it already installed on your machine; otherwise, here is a link to the Node.js website to install this as well as Node’s package manager, npm: https://nodejs.org/en/download/.

Note

Aim for the Long-Term Support (LTS) version of Node.js when downloading it. Generally, a good habit to hold as a developer is to use LTS versions of their tooling.

Once you have npm running, installing cdk on any operating system can be done by simply running the following command:

$ npm install -g aws-cdk@2.25.0

By running this, we are aiming for a specific version of the CLI, and we will also do the same with the library. CDK changes quite significantly between versions, therefore it’s best for us to focus on a specific version of CDK. Once you’ve learned the ropes, you will be able to upgrade to a later version of it when available. At the time of writing this, 2.25.0 is the latest version of CDK.

Next, type in and run the following command:

$ cdk -h

If you see a bunch of commands like the ones seen in the following screenshot, you’ve done things right:

Figure 1.6 – Making sure the CDK toolset is installed correctly

Figure 1.6 – Making sure the CDK toolset is installed correctly

Great! Now that we have the CDK CLI installed, let’s go ahead and create our first CDK app.

Creating our first CDK app

Go ahead and create a directory on your workspace. In the example code provided, we’ve named it chapter-1-introduction-to-iac-and-aws-cdk. Next, bring up the CLI of your beloved operating system and run the following command inside the directory:

$ cdk init app --language typescript

A bunch of green text should appear while CDK does its magic. Once done, run the ls command to see the top-level folder structure, or even better, if you have the tree command installed, run it as such:

$ tree -I node_modules

The following is what you should be seeing:

Figure 1.7 – Folder structure of our CDK app

Figure 1.7 – Folder structure of our CDK app

If you don’t have tree installed, you can install it with one of the following commands.

On Mac (using the Homebrew package manager), run this command:

brew install tree

On Linux (Ubuntu), run this command:

sudo apt install tree

Note

tree is already installed on Windows 10/11.

We’ve intentionally told the tree command to ignore node_modules since it’s an abyss of directories we don’t need to know about. At a high level, here are explanations of the files and directories:

  • README.md is essentially a Markdown documentation file. You must’ve come across it.
  • The bin directory is essentially where the top-level CDK app files reside:
    • chapter-1-introduction-to-iac-and-aws-cdk.ts is the file cdk created based on the name of the directory we ran the CLI init command in. This file contains the entry point of the application.
  • cdk.json tells the toolkit how to run the application and passes along some further configurations.
  • jest.config.js is the configuration file the cdk library uses to run local tests.
  • lib contains all the goodies. All the constructs we will be creating for our project will be placed inside here, as outlined next:
    • chapter-1-introduction-to-iac-and-aws-cdk-stack.ts is one such construct or component. In this chapter, we will be spending most of our time here.
  • You can safely ignore package-lock.json for now; it’s what npm uses to keep track of specific versions of node libraries installed.
  • package.json is the npm module’s manifest information such as app, versions, dependencies, and so on.
  • test is pretty self-explanatory. Our test files reside here, as detailed next:
    • chapter-1-introduction-to-iac-and-aws-cdk.test.ts: cdk has gone ahead and created a test file for us, urging us to test our application. We will do so in later chapters. For now, ignore it.
  • tsconfig.json is where TypeScript-specific configuration is stored.

Now that we’ve learned about the files cdk has created, let’s dive in and kick off our first AWS CDK app!

Creating a containerized web application in AWS CDK using Docker

In this step, we will keep things as simple as we can. The aim is to get you going with coding your first CDK app as quickly as you can. So, let’s get started.

Open lib/chapter-1-introduction-to-iac-and-aws-cdk-stack.ts in your favorite editor. We’re using Visual Studio Code. You will see the following code already present in the file. CDK has pretty much wired up everything for us and is ready to go:

import  * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
// import * as sqs from 'aws-cdk-lib/aws-sqs';
export class Chapter1IntroductionToIacAndAwsCdkStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    // The code that defines your stack goes here
    // example resource
    // const queue = new sqs.Queue(this, 'Chapter1IntroductionToIacAndAwsCdkQueue', {
    //   visibilityTimeout: cdk.Duration.seconds(300)
    // });
  }
}

We could get rid of all the comments and start adding our code, but for the sake of simplicity, let’s delete all that and paste the following code instead into the file:

import { Stack, StackProps } from 'aws-cdk-lib';
import { ContainerImage } from 'aws-cdk-lib/aws-ecs';
import { ApplicationLoadBalancedFargateService } from 'aws-cdk-lib/aws-ecs-patterns';
import { Construct } from 'constructs';
export class Chapter1IntroductionToIacAndAwsCdkStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    new ApplicationLoadBalancedFargateService(this, 'MyWebServer', {
      taskImageOptions: {
        image: ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
      },
      publicLoadBalancer: true
    });
  }
}

Alright—save the file, open up the command line, cd into the working directory (the root of our cdk application), and run the following:

$ cdk bootstrap --profile cdk

This command will bootstrap the AWS environment, meaning it will create all the necessary AWS resources on the cloud to make CDK work properly.

Then, run the following command:

$ cdk deploy --profile cdk

If you’ve followed the instructions correctly so far, you will see a nice green-text screen. Let’s examine it:

Figure 1.8 – Deploying our first CDK stack

Figure 1.8 – Deploying our first CDK stack

The preceding screen is first warning you that potentially sensitive changes are about to occur with this deployment; this is due to the IAM roles the stack creates. It’s fine for you to ignore this for now.

Next, it lists the names of AWS resources that are about to be created, categorized by service. The + sign and the green color of the text indicate that these resources are about to be added. Later, we will see resources that will be marked for destruction, which is logically indicated by a sign at the beginning of the line and the color red.

Yes—you’ve earned it: go ahead and type y and press Enter.

Note

If you’re in the middle of a stack being created and are about to take a break or attend to another matter, destroy the stack with cdk destroy --profile cdk to avoid unnecessary costs.

CDK will create an AWS CloudFormation template (we will cover this later in the chapter) and continue to deploy the stack. It will also keep you informed of the progress. If your user has got the necessary permissions, CDK will succeed in deploying the stack; else, it will fail and automatically roll back the changes.

The process is complete; we see a bunch of information being outputted. Under the Outputs section, you will see two links:

Figure 1.9 – CloudFormation stack output links

Figure 1.9 – CloudFormation stack output links

Copy either of the links into your web browser and navigate to it. You should see a page load up:

Figure 1.10 – The output of the Elastic Container Service (ECS) server

Figure 1.10 – The output of the Elastic Container Service (ECS) server

Nice! You’ve successfully deployed your first CDK application. If you now go back to your AWS dashboard and go to ECS Service, you will see a new cluster of services has been spun up on your behalf.

If you click on the cluster name, which should be Chapter1IntroductionToIacAndAwsCdkStack-{some other random text}, then you will be able to see the service, tasks, metrics, logs, and all the rest. This is a containerized ECS Fargate application with a lot of built-in resiliency already spun up by you already. So many other good things are about to come.

Right—we’ve had our fun. Let’s now go ahead and destroy the stack before we do anything else. To destroy the stack—you guessed it—run the following:

$ cdk destroy --profile cdk

Confirm by entering y. AWS CDK will now go ahead and destroy our favorite PHP stack. Perhaps it’s for the best.

Going back to the dashboard and to the ECS Service root page, you will see that the cluster is no longer there. Neither is our simple PHP app. All gone. Clean.

Understanding the inner workings of AWS CDK

We hope that was fun. In the previous section, we mentioned AWS CloudFormation and how CDK outputs a CloudFormation template and then manages its life cycle.

According to AWS, CloudFormation is an IaC service (again, I’d argue with the code bit) that you can use to model, provision, and manage AWS services. In short, it’s a YAML or JSON file with an AWS service definition of its properties and relationships.

Learning CloudFormation is outside the scope of this book, but it’s useful for you to understand and read about it, to better debug your CDK applications. Let’s take a brief look at a CloudFormation excerpt sample YAML configuration.

Here is how you set up a basic EC2 instance and open up the 22 port for SSH access. Reading YAML is straightforward, and if you look closely, you will be able to read the various components our CloudFormation configuration defines:

Parameters:
  KeyName:
    Description: The EC2 Key Pair to allow SSH access to the instance
    Type: 'AWS::EC2::KeyPair::KeyName'
Resources:
  Ec2Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
      SecurityGroups:
        - !Ref InstanceSecurityGroup
        - MyExistingSecurityGroup
      KeyName: !Ref KeyName
      ImageId: ami-7a11e213
  InstanceSecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      GroupDescription: Enable SSH access via port 22
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0

Well, CDK uses the same underlying mechanism. Working with AWS CloudFormation directly can be very daunting and complicated, even for relatively simple stacks. To prove this point, go to this chapter’s CDK app root and run the following command:

$ cdk synth

You guessed it right—this gigantic abomination of a YAML output is the result of about 20 lines of CDK TypeScript code. CDK essentially compiles your code into a CloudFormation stack and manages the rest of the complexity of adding and removing various bits, linking resources together, and a ton of other things for you.

The amount of time that developers save is undeniably massive. The amount of confusion, mistakes, and painful trials and errors of CloudFormation or any other configuration-defined IaC tool that CDK eliminates makes CDK and the new set of similar tools such as Pulumi clear winners of the IaC race. Businesses that onboard CDK into their development practices will be able to deliver a lot more in a shorter amount of time.

Developers with CDK skills will be highly sought after. Welcome aboard—this is the future of software development on the cloud!

Summary

In this chapter, we took a brief look at problems and issues with the current IaC tools and methods. We introduced CDK, got a taste of what it is capable of, and understood some of the inner workings of CDK, as well as how potentially revolutionary it is.

In the next chapter, we will dive deeper into setting up our workspace, directory structures, and environment correctly. We will also explain the concept of constructs and stacks and get to know other important aspects of CDK.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Build complex cloud applications with the revolutionary AWS CDK
  • Gain practical knowledge of AWS CDK to leverage the powerful toolset of AWS
  • Employ practical exercises & architectural design patterns for developing modern serverless application

Description

As cloud applications are becoming more complex, multiple tools and services have emerged to cater to the challenges of running reliable solutions. Although infrastructure as code, containers, and orchestration tools, such as Kubernetes, have proved to be efficient in solving these challenges, AWS CDK represents a paradigm shift in building easily developed, extended, and maintained applications. With AWS CDK in Practice, you’ll start by setting up basic day-to-day infrastructure while understanding the new prospects that CDK offers. You’ll learn how to set up pipelines for building CDK applications on the cloud that are long-lasting, agile, and maintainable. You’ll also gain practical knowledge of container-based and serverless application development. Furthermore, you’ll discover how to leverage AWS CDK to build cloud solutions using code instead of configuration files. Finally, you’ll explore current community best practices for solving production issues when dealing with CDK applications. By the end of this book, you’ll have practical knowledge of CDK, and you’ll be able to leverage the power of AWS with code that is simple to write and maintain using AWS CDK.

Who is this book for?

This book is for traditional full stack developers looking to explore the new world of Infrastructure as Code and serverless applications, solutions architects seeking to define their services with AWS CDK, and DevOps specialists searching for a better management technique to configure files. Readers should not be new to coding and must have experience in web development in languages such as Python, JS, Typescript, Java, etc. along with a basic understanding of how web applications are developed.

What you will learn

  • Turn containerized web applications into fully managed solutions
  • Explore the benefits of building DevOps into everyday code with AWS CDK
  • Uncover the potential of AWS services with CDK
  • Create a serverless-focused local development environment
  • Self-assemble projects with CI/CD and automated live testing
  • Build the complete path from development to production with AWS CDK
  • Become well versed in dealing with production issues through best practices

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 16, 2023
Length: 196 pages
Edition : 1st
Language : English
ISBN-13 : 9781801815277

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

Publication date : Jun 16, 2023
Length: 196 pages
Edition : 1st
Language : English
ISBN-13 : 9781801815277

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 113.97
The Ultimate Docker Container Book
€37.99
AWS CDK in Practice
€37.99
Mastering Elastic Kubernetes Service on AWS
€37.99
Total 113.97 Stars icon

Table of Contents

16 Chapters
Part 1: An Introduction to AWS CDK Chevron down icon Chevron up icon
Chapter 1: Getting Started with IaC and AWS CDK Chevron down icon Chevron up icon
Chapter 2: A Starter Project and Core Concepts Chevron down icon Chevron up icon
Part 2: Practical Cloud Development with AWS CDK Chevron down icon Chevron up icon
Chapter 3: Building a Full Stack Application with CDK Chevron down icon Chevron up icon
Chapter 4: Complete Web Application Deployment with AWS CDK Chevron down icon Chevron up icon
Chapter 5: Continuous Delivery with CDK-Powered Apps Chevron down icon Chevron up icon
Chapter 6: Testing and Troubleshooting AWS CDK Applications Chevron down icon Chevron up icon
Part 3: Serverless Development with AWS CDK Chevron down icon Chevron up icon
Chapter 7: Serverless Application Development with AWS CDK Chevron down icon Chevron up icon
Chapter 8: Streamlined Serverless Development Chevron down icon Chevron up icon
Part 4: Advanced Architectural Concepts Chevron down icon Chevron up icon
Chapter 9: Indestructible Serverless Application Architecture (ISAA) Chevron down icon Chevron up icon
Chapter 10: The Current CDK Landscape and Outlook Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Most Recent
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(12 Ratings)
5 star 91.7%
4 star 0%
3 star 0%
2 star 8.3%
1 star 0%
Filter icon Filter
Most Recent

Filter reviews by




Javier Feb 08, 2024
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I'm on page 30 and I've already found quite a few errors that don't let you move forward with the code and you have to resolve them. In the first examples, the GitHub code does not match that of the book, there are typos and import errors, when you create the first S3 bucket you cannot because they have forgotten to remove the public access block that exists by default in S3, etc. .. I don't think it's been even remotely revised it, you have to waste a lot of time correcting errors. I hope it's not the general tone for the rest of the book, but everything points to a bad review.
Subscriber review Packt
Patsy Phelan Jan 19, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Walter Lee Aug 26, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is an excellent resource for learning about the AWS CDK and how to use it to create cloud infrastructure. The authors do a great job of explaining the concepts in a clear and concise way, and there are many helpful examples throughout the book.The book begins by introducing the AWS CDK and explaining why it is a valuable tool for infrastructure as code (IaC). The author then goes on to discuss the different components of the CDK, such as constructs, stacks, and apps. He also provides detailed instructions on how to create and deploy CDK applications.In addition to the theoretical content, the book also includes a number of practical examples. These examples cover a wide range of topics, from creating simple EC2 instances to building complex serverless applications. The examples are well-explained and easy to follow, making them a valuable resource for learning how to use the CDK.The book also includes a section on troubleshooting CDK problems. This section covers common problems such as IAM permissions and bootstrapping. The author provides clear and concise solutions to these problems, making it easy to get your CDK applications up and running.Overall, this book is an excellent resource for anyone who wants to learn about the AWS CDK. It is well-written, informative, and practical. I highly recommend it to anyone who is interested in using the CDK to create cloud infrastructure.
Amazon Verified review Amazon
Cory Jaccino Aug 21, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A little background for context…I’m a Google Search veteran (Google Ads, Google Analytics, and SEO) who is expanding his knowledge and skill set to the major cloud providers and related technologies. I’m currently certified as a Google Cloud Professional Cloud Architect as well as a Google Cloud Professional Cloud Developer.I’ve passed the AWS Certified Cloud Practitioner exam and, within AWS, I’m currently focused on preparing for the Solutions Architect Associate and Developer Associate exams.I’m still reading this book but I’d like to give some initial feedback.At 196 paperback pages, this book is shorter than I would have expect it to be. But, don’t let that fool you. It wastes little time getting into the CDK with the minimum amount of background needed.So far, the exercises don’t feel rushed. They feel focused but not rushed. Sometimes the “why” is explained just above or below the steps, and sometimes it’s in the middle. But, it’s clarifying in nature and often a related option or something helpful is given.For example, to aid with clarity in the terminal, they explain how to ignore certain directories in the tree command output.$ tree -I node_modulesI had never learned this. It’s obvious to me that the authors understand the value of a good setup. It can make a big difference when these little things are added up.How do you install the tree command on a Mac?brew install treeAs the example above and total page count suggest, it’s a great value-to-page count ratio so far.Some books focus on one platform such as macOS, Windows, or Linux. Then they ask you to look up the equivalent command by giving you a link to official documentation, which can be good.But, this book gives you what you need so you can continue focusing on the lesson. It keeps the momentum going, which is better in my mind because life has enough distractions and I’d really like to learn how to be a better developer.From time to time, the authors elaborate, share their experience, and explain why they make certain choices, which I find insightful and sometimes unexpected.For example, I appreciated their candor about how they manage repositories for and with their clients — the decision to use organizations, monorepos, etc. I wasn’t expecting the preference for monorepos, but I’m still learning the use cases on the AWS CDK side.For me, the setup is often the most difficult part. So far, I’m off to a good start.If you can, I’d encourage you to read the first chapter or two, actually set up the CDK, and see for yourself. If all goes well, try the next chapter and go from there. I’ll circle back and add more to this review in progress once I finish.As a disclaimer, I did recently receive a free copy of this book for review at the request of the publisher, Packt. That said, I already had online access to the book’s content through my annual (self-paid) Packt subscription.So, what does that mean?It means that I got a copy that I could highlight on my iPad so that I could take my time and really learn this well. If you buy the book here or via Packt, so can you. It’s all in the setup and follow through. Step by step.I will update this review and elaborate once finished. Now, back to the content and exercises.
Amazon Verified review Amazon
Cinthya Cabanzo Aug 21, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
"AWS CDK in Practice" is a standout guide that skillfully navigates readers through the intricacies of Amazon Web Services Cloud Development Kit (CDK). The book's structured approach, starting from simple examples and progressing towards production-grade setups, makes it an invaluable resource for both beginners and experienced AWS developers.The book's strength lies in its ability to bridge the gap between theory and practice through the use of visual aids. The inclusion of graphics and screenshots showcasing expected outcomes enhances the reader's comprehension of complex topics and facilitates self-assessment. This feature not only fosters a better understanding of the material but also ensures that readers can confidently implement CDK solutions.An aspect that truly distinguishes this book is its comprehensive evaluation of solution benefits and limitations. By offering a balanced exploration of different approaches, readers gain insights into the nuances of CDK's capabilities. This equips them with the knowledge needed to make informed decisions when crafting their own AWS solutions, enhancing the overall quality of their projects.Furthermore, "AWS CDK in Practice" delves into advanced concepts, enriching the reader's understanding beyond the basics. The book adeptly explains complex ideas, making them accessible to readers of various skill levels. This inclusivity ensures that both newcomers and seasoned professionals can grasp and leverage the full potential of CDK effectively.In conclusion, "AWS CDK in Practice" is an invaluable resource for anyone seeking to master AWS CDK. From its gradual progression from simple examples to in-depth production-grade configurations, to its strategic use of visual aids and comprehensive analysis of solution pros and cons, the book stands as a crucial companion on the journey to becoming a proficient AWS CDK developer. Whether you're looking to solidify your foundation or delve into advanced concepts, this book is an indispensable asset in your quest for AWS mastery.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.