aws-cdk-examples
aws-cdk-examples copied to clipboard
Add CDK Example: How to do a lookup by subnet group name
Describe the feature
The subnet group name can be used to refer to the intended subnet quickly.
Use Case
Many samples reference subnets created in the VPC stack, such as ec2.SubnetSelection is handled by a subnet type call, list, or import function. However, in actual requirements, many requirements cannot be divided by subnet type, such as subnets for network firewalls, transit gateways, and so on.
Proposed Solution
subnet_group_name_tag and cdk.json
Other Information
No response
Acknowledgements
- [X] I may be able to implement this feature request
- [ ] This feature might incur a breaking change
Language
Python
@takashi-uchida , I checked that in subnet Selection we can use subnetGroupName. During my testing , I noticed that CDK uses the tag "aws-cdk:subnet-name" for subnetGroupName.
I added the tag 'aws-cdk:subnet-name' to my subnets in a VPC with value 'Private-tag' and used the below code :
vpc = ec2.Vpc.from_lookup(self, "MyVpc",
vpc_id='vpc-XXXXXXXXX'
)
subnet_ids = vpc.select_subnets(
subnet_group_name="Private-tag"
).subnet_ids
for subnet_id in subnet_ids:
print("Subnet Ids: " + subnet_id)
I was able to check in my cdk.context.json file , under subnetGroups , there were subnets with this tag. And in the output of " print("Subnet Ids: " + subnet_id)" , I could see my subnets on which I added the tag.
You can add tag "aws-cdk:subnet-name" on the required subnets with same value and then use above way to select them by subnetGroupName.
Thank you. I have been handling it as follows.
self.vpc = ec2.Vpc(
self,
"vpc",
vpc_name=f"vpc-{project_name}",
ip_addresses=ec2.IpAddresses.cidr(vpc_cidr),
max_azs=3,
subnet_configuration=[
ec2.SubnetConfiguration(
name=f"public-{project_name}",
cidr_mask=24,
subnet_type=ec2.SubnetType.PUBLIC,
),
ec2.SubnetConfiguration(
name=f"private-{project_name}",
cidr_mask=24,
subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS,
),
ec2.SubnetConfiguration(
name=f"isolated-{project_name}",
cidr_mask=24,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED,
),
ec2.SubnetConfiguration(
name=f"tgw-{project_name}",
cidr_mask=24,
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED,
),
],
)
vpc = ec2.Vpc.from_lookup(
self, "vpc", vpc_name=vpc_name, subnet_group_name_tag="aws-cdk:subnet-name"
)
vpc_subnets=ec2.SubnetSelection(
subnet_group_name="private-{project_name}"),
⚠️COMMENT VISIBILITY WARNING⚠️
Comments on closed issues are hard for our team to see. If you need more assistance, please either tag a team member or open a new issue that references this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.