How to do Subnets Tagging in AWS CDK

How to do Subnets Tagging in AWS CDK

Tagging subnets in AWS CDK is a great way to organize and manage your resources within your VPC. By using tags, you can easily identify and filter resources based on their purpose, environment, or any other criteria that is important to your organization. In this blog post, we will show you how to tag subnets in AWS CDK using a few examples.

First, let's start by creating a new VPC in AWS CDK. You can do this by using the Vpc class in the aws-cdk-lib package.

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

const app = new cdk.App();
const stack = new cdk.Stack(app, 'my-stack');

const vpc = new ec2.Vpc(stack, 'my-vpc', {
  cidr: '10.0.0.0/16',
  natGateways: 0,
  subnetConfiguration: [
    {
      cidrMask: 24,
      name: 'public',
      subnetType: ec2.SubnetType.PUBLIC
    },
    {
      cidrMask: 24,
      name: 'private',
      subnetType: ec2.SubnetType.PRIVATE
    }
  ]
});

In this example, we are creating a new VPC with a CIDR block of 10.0.0.0/16 and two subnets, one public and one private. The subnetConfiguration property is used to define the subnets, and the cidrMask property is used to specify the CIDR block for each subnet.

Next, we can add tags to the subnets using the addTags method. This method takes an object that contains the tag keys and values.

vpc.publicSubnet.addTags({
  'Environment': 'Prod',
  'Purpose': 'Web servers'
});

vpc.privateSubnet.addTags({
  'Environment': 'Prod',
  'Purpose': 'Database servers'
});

In this example, we are adding two tags to the public subnet, "Environment" and "Purpose", and setting their values to "Prod" and "Web servers" respectively. We are also adding two tags to the private subnet, "Environment" and "Purpose", and setting their values to "Prod" and "Database servers" respectively.

Once you have tagged your subnets, you can use the AWS Management Console or the AWS CLI to filter and view your resources based on their tags. This can help you easily identify and manage your resources based on their purpose, environment, or any other criteria that is important to your organization.

In this way, you can use the addTags method to tag the subnets in your VPC. This is a powerful way to organize and manage your resources in AWS CDK, and it can help you easily identify and filter resources based on their purpose, environment, or any other criteria that is important to your organization.

Did you find this article valuable?

Support Mikaeel Khalid by becoming a sponsor. Any amount is appreciated!