How to do Subnet Selection in AWS CDK
Tags: aws, awscdk, cdk, iac
Published: 2023-11-20 04:18:46

---
title: How to do Subnet Selection in AWS CDK
published: true
date: 2023-02-03 03:30:39 UTC
tags: #aws #awscdk #cdk #iac
canonical_url: https://blog.mikaeels.com/how-to-do-subnet-selection-in-aws-cdk
---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g73m1pwjlrzxnz72qwb7.jpeg)

AWS CDK, or Amazon Web Services Cloud Development Kit, is a software development framework for building and deploying cloud-based applications on Amazon Web Services. The CDK provides an easy-to-use and high-level API for building cloud-based applications and automates many of the underlying infrastructure management tasks. The CDK supports several programming languages, including TypeScript, Python, and Java.

In this post, we will explore how to select a subnet in AWS CDK using TypeScript. Subnets are a logical partition of a VPC (Virtual Private Cloud) network and allow you to allocate network resources and control network access. The selection of the right subnet is important in order to ensure that your applications are deployed in the desired environment and can communicate with other resources in the VPC.

We will start by creating a new AWS CDK project using TypeScript. To do this, you will need to have the AWS CDK CLI installed. You can install it by running the following command:

```
npm install -g aws-cdk
```

Next, create a new project by running the following command:

```
cdk init sample-app --language typescript
```

This will create a new AWS CDK project named `sample-app` and set the programming language to TypeScript.

Now, let's create a VPC with two subnets in the project. To do this, add the following code to the `lib/sample-app-stack.ts` file:

```
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';

export class SampleAppStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const vpc = new ec2.Vpc(this, 'VPC', {
      cidr: '10.0.0.0/16',
      subnetConfiguration: [
        {
          cidrMask: 24,
          name: 'Subnet1',
          subnetType: ec2.SubnetType.PUBLIC,
        },
        {
          cidrMask: 24,
          name: 'Subnet2',
          subnetType: ec2.SubnetType.PRIVATE,
        },
      ],
    });
  }
}
```

In the code above, we are creating a new VPC with two subnets. The first subnet is a public subnet and the second subnet is a private subnet. The subnet configuration is specified using the `subnetConfiguration` parameter, which takes an array of subnet configurations. Each subnet configuration contains the CIDR mask, subnet name, and subnet type.

Next, we need to select the desired subnet to deploy our applications in. To do this, we can use the `selectSubnets` method on the VPC object. The `selectSubnets` method allows us to specify a filter function that determines which subnets should be selected.

For example, to select the private subnet, we can add the following code to the `lib/sample-app-stack.ts` file:

```
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';

export class SampleAppStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);

const vpc = new ec2.Vpc(this, 'VPC', {
  cidr: '10.0.0.0/16',
  subnetConfiguration: [
    {
      cidrMask: 24,
      name: 'Subnet1',
      subnetType: ec2.SubnetType.PUBLIC,
    },
    {
      cidrMask: 24,
      name: 'Subnet2',
      subnetType: ec2.SubnetType.PRIVATE,
    },
  ],
});

const privateSubnets = vpc.selectSubnets({
  subnetType: ec2.SubnetType.PRIVATE,
});

  } 
}
```

In the code above, we are selecting the private subnets using the `selectSubnets` method and the `subnetType` filter. The filter is set to `ec2.SubnetType.PRIVATE`, which means that only the subnets with the type `PRIVATE` will be selected. The selected subnets are stored in the `privateSubnets` variable. Now that we have selected the desired subnet, we can use it to deploy our applications. For example, to deploy an EC2 instance in the private subnet, we can add the following code to the `lib/sample-app-stack.ts` file:

```
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';

export class SampleAppStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const vpc = new ec2.Vpc(this, 'VPC', {
      cidr: '10.0.0.0/16',
      subnetConfiguration: [
        {
          cidrMask: 24,
          name: 'Subnet1',
          subnetType: ec2.SubnetType.PUBLIC,
        },
        {
          cidrMask: 24,
          name: 'Subnet2',
          subnetType: ec2.SubnetType.PRIVATE,
        },
      ],
    });

    const privateSubnets = vpc.selectSubnets({
      subnetType: ec2.SubnetType.PRIVATE,
    });

    new ec2.Instance(this, 'Instance', {
      vpc,
      subnet: privateSubnets[0],
      instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),
      machineImage: new ec2.AmazonLinuxImage(),
    });

  }
}
```

In the code above, we are creating a new EC2 instance using the `Instance` class from the AWS CDK library. The instance is deployed in the VPC and the selected private subnet is specified using the `subnet` property of the `Instance` class. The instance is deployed in the first subnet of the `privateSubnets` array, which is accessed using `privateSubnets[0]`.

Additionally, we have specified the instance type, machine image, and other required properties to deploy the EC2 instance.

In conclusion, the AWS CDK library provides a simple and straightforward way to select subnets in your VPCs. With the `selectSubnets` method, you can easily filter the subnets based on different criteria, such as subnet type, availability zone, or tags, to deploy your applications in the desired subnets.

By using the subnet selection feature, you can control the network access to your applications and maintain the security of your resources. Moreover, you can optimize your network architecture by deploying applications in subnets that best match their requirements and ensure the optimal performance of your applications.