We will work with the CDK mainly through the AWS CDK Toolkit (the tool was installed in the previous section). The AWS CDK Toolkit will run your code, generate a CloudFormation template, and deploy that template. The CDK Toolkit provides users with the ability to deploy, compare, remove, and debug a piece of CDK code. Refer to official AWS documentation on CDK
In this section, we will try to implement a VPC and corresponding public subnet, using Python in CDK
mkdir cdk-workshop
cd cdk-workshop
python
language, but you can completely edit it into Typescript, Javascript, Java or C#cdk init app --language python
Once it’s run, you can take a look at the directory architecture that has just been initialized. Pay attention to the two main files app.py and cdk_workshop/cdk_workshop_stack.py
cdk_workshop/cdk_workshop_stack.py
from aws_cdk import (
Stacks,
aws_ec2 as ec2,
aws_iam as iam
)
from aws_cdk.aws_s3_assets import Asset
import os
from constructs import Construct
In the file cdk_workshop/cdk_workshop_stack.py
, declare 1 VPC and 2 public subnets located in the VPC by adding the following code to the __init__
function
# VPC
vpc = ec2.Vpc(self, "CDK-Workshop-App-VPC",
nat_gateways=0,
subnet_configuration=[ec2.SubnetConfiguration(name="public",subnet_type=ec2.SubnetType.PUBLIC)]
)
cdk init
source .venv/bin/activate
python -m pip install -r requirements.txt
cdk bootstrap
On the first run, we will need to bootstrap the CDK application. This bootstrap will
cdk deploy
The above command is equivalent to running cdk deploy –app ./app.py. When run, the code in the app.py file will be called. This code will import resources from cdk_workshop/cdk_workshop_stack.py, and generate the corresponding CloudFormation template in the cdk.out folder. This CloudFormation template will then be deployed on AWS.
If you’ve made it to this step, congratulations on successfully deploying your AWS resources through the CDK!
In the next section, we will use the created VPC and subnet to deploy an EC2 server and install Apache server on it. We will also get acquainted with some other features of the CDK such as generating CloudFormation configuration from CDK using cdk synch
or checking ChangeSet using cdk diff