AWS CDK (Construct Development Kit) is a great IaC (Infrastructure as Code) technology for defining backend AWS resources for your projects.
CDK comes with three layers of abstraction for constructs
CfnBucket is an example of such a construct that maps to the AWS::S3::Bucket CloudFormation resource.Bucket is an example of such a construct that maps to the AWS::S3::Bucket CloudFormation resource.But there is problem with it that can cost you lots of money in addition to frustration. It comes from using layer 2 and 3 constructs which may create resources you may not be aware of, resources that cost when they are instantiated, even when not used (e.g. NAT gateways, databases, load balancers).
Consider the case of using a simple VPC construct in your stack.
import { Construct } from 'constructs';
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
export class DemoStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const vpc = new ec2.Vpc(this, 'demo-vpc', {
vpcName: 'Demo VPC'
});
};
};
If you deploy this infrastructure to AWS using the cdk deploy command, you might be surprised to find out,
at the end of the month that you have been charged tens of dollars
(depending on the region you deployed to). This is because the L3 construct above
creates a NAT Gateway for each availability zone in the region.
AWS::EC2::VPCAWS::EC2::InternetGatewayAWS::EC2::VPCGatewayAttachmentCustom::VpcRestrictDefaultSGAWS::IAM::RoleAWS::Lambda::FunctionAWS::EC2::SubnetAWS::EC2::RouteTableAWS::EC2::SubnetRouteTableAssociationAWS::EC2::RouteAWS::EC2::EIPAWS::EC2::NatGateway <-- this is where the problem isAWS::EC2::SubnetAWS::EC2::RouteTableAWS::EC2::SubnetRouteTableAssociationAWS::EC2::RouteAssume we deploy in the region eu-north-1. At the time of this article, we have
eu-north-1a, eu-north-1b, eu-north-1cIf you deploy this simple VPC configuration, in one month the costs will add up to over one hundred dollars, a not so insignificant cost if you don't need the gateway in the first place.
3 x 24 x 31 x 0.046 dollars = 102.7 dollars
The solution to the problem above is to prevent CDK from creating NAT gateways by specifying a count of zero.
const vpc = new ec2.Vpc(this, 'demo-vpc', {
vpcName: 'Demo VPC',
natGateways: 0,
});
CDK can save you time by generating complex CloudFormation templates from simple code
involving L2 and L3 constructs. However, you need to really understand what those constructs
entail or check the CloudFormation output (in the cdk.out folder) to see what resources
they create.