DEV Community

Dennis Groß (he/him)
Dennis Groß (he/him)

Posted on • Originally published at on

How To Configure a VPC in AWS CDK

Virtual Private Clouds (VPC) are separate networks that you can create on your AWS account to have some separation between the AWS resources that you deploy. They are required by all AWS services that are not fully serverless and thus have to deploy in your account.

Every AWS region comes with a default VPC that has one public subnet for each availability zone (AZ), but it is recommended to deploy your AWS resources in a custom VPC that is tailored to your deployment needs.

Read more about VPCs here.

Basic Multi-AZ VPC

Here is a basic VPC with a single NAT Gateway, on three different availability zones each with public, private, and private isolated subnet.

const vpc = new aws_ec2.Vpc(this, 'MyVpc', {
  // defines the private IP subnet used for private subnets in all AZs
  cidr: '',
  // how many AZs you want to use
  maxAzs: 3,
  // one nategateway per private subnet by default,
  //reduce number to save costs on dev envs
  natGateways: 1,
  subnetConfiguration: [
      // subnet masks => defines how many ips of the vpc ip pool
      // get used for the public subnets in each AZ
      cidrMask: 26,
      name: 'Public',
      // public subnets allow internete ingress and egress
      // internet access in both direction via internat gateway
      subnetType: aws_ec2.SubnetType.PUBLIC,
      cidrMask: 26,
      name: 'Private',
      // private network with no internet ingress but
      // internet egress. Internet egress gets routed through nat gateway
      // to the internet gateway
      subnetType: aws_ec2.SubnetType.PRIVATE_WITH_NAT,
      cidrMask: 26,
      name: 'Private Isolated',
      // private network with no internete ingress or egress.
      subnetType: aws_ec2.SubnetType.PRIVATE_ISOLATED,

Enter fullscreen mode Exit fullscreen mode

Set the natGateways to 1 if you deploy a dev environment, they are not for free.

Enable VPC Flow Logs

VPC flow logs contain log lines for each IP layer event that happens in your VPC. The flow logs are in general quite useful to troubleshoot issues with over-restrictive security groups or to monitor your network traffic in your VPC.

You need a CloudWatch log group as a sink for the flow log and I recommend you configure a retention policy. CloudWatch logs get charged per GB/per month.

const vpc = new aws_ec2.Vpc(...)

const logGroup = new aws_logs.LogGroup(this, 'MyLogGroup', {
  retention: aws_logs.RetentionDays.FIVE_DAYS,
  removalPolicy: RemovalPolicy.DESTROY,

const role = new aws_iam.Role(this, 'VpcFlowLogRole', {
  assumedBy: new aws_iam.ServicePrincipal(''),

new aws_ec2.FlowLog(this, 'VpcFlowLog', {
  resourceType: aws_ec2.FlowLogResourceType.fromVpc(vpc),
  destination: aws_ec2.FlowLogDestination.toCloudWatchLogs(logGroup, role),

Enter fullscreen mode Exit fullscreen mode

Default retention policy is to keep the logs forever

Oldest comments (0)