Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
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

eBook
$27.98 $39.99
Paperback
$49.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
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 [email protected]

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
Estimated delivery fee Deliver to Japan

Standard delivery 10 - 13 business days

$8.95

Premium delivery 3 - 6 business days

$34.95
(Includes tracking information)

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 : 9781801812399
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Japan

Standard delivery 10 - 13 business days

$8.95

Premium delivery 3 - 6 business days

$34.95
(Includes tracking information)

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 149.97
The Ultimate Docker Container Book
$49.99
AWS CDK in Practice
$49.99
Mastering Elastic Kubernetes Service on AWS
$49.99
Total $ 149.97 Stars icon
Banner background image

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

Top Reviews
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
Top Reviews

Filter reviews by




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
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
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
sathish Aug 16, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A very helpful book for anyone looking to get started with CDK. I highly recommend it for those who are transitioning to CDK for Infrastructure as Code (IaC). I really appreciated the book's writing style, which includes plenty of examples that make it easy for anyone to grasp the concepts.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela