Created
September 15, 2024 06:41
vpc_cdk.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from aws_cdk import Stack | |
from constructs import Construct | |
from aws_cdk import aws_ec2 as ec2 | |
import boto3 | |
class VpcStack(Stack): | |
def __init__(self, scope: Construct, id_: str, **kwargs) -> None: | |
super().__init__( | |
scope, | |
id_, | |
**kwargs, | |
) | |
az1, az2 = self.get_az_names_for_az1_az2(region_name='us-east-1', az1_id='use1-az1', az2_id='use1-az2') | |
self.vpc = ec2.Vpc( | |
self, | |
"MyTestVPC", | |
availability_zones=[az1, az2], | |
cidr="10.10.0.0/16", | |
subnet_configuration=[ | |
ec2.SubnetConfiguration(subnet_type=ec2.SubnetType.PUBLIC, name="Public", cidr_mask=24), | |
ec2.SubnetConfiguration(subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT, name="Private", cidr_mask=24), | |
ec2.SubnetConfiguration(subnet_type=ec2.SubnetType.PRIVATE_ISOLATED, name="DB", cidr_mask=24) | |
], | |
) # configuration will create 3 groups in 2 AZs = 6 subnets | |
def get_az_names_for_az1_az2(self, region_name: str, az1_id: str, az2_id: str) -> tuple: | |
""" | |
Returns the availability zone names for the specified AZ1 and AZ2 IDs in the given region. | |
:param region_name: AWS region to query | |
:param az1_id: Availability Zone ID for AZ1 | |
:param az2_id: Availability Zone ID for AZ2 | |
:return: A tuple containing the names of AZ1 and AZ2, or (None, None) if not found. | |
""" | |
# Initialize the Boto3 EC2 client | |
ec2_client = boto3.client('ec2', region_name=region_name) | |
# Get the list of all Availability Zones in the region | |
response = ec2_client.describe_availability_zones() | |
# Variables to store the names of az1 and az2 | |
az1_name = None | |
az2_name = None | |
# Iterate through the list of AZs and find the Zone Names for the specified AZ IDs | |
for az in response['AvailabilityZones']: | |
if az['ZoneId'] == az1_id: | |
az1_name = az['ZoneName'] | |
if az['ZoneId'] == az2_id: | |
az2_name = az['ZoneName'] | |
# If both names are found, break early | |
if az1_name and az2_name: | |
print(az1_name, az2_name) | |
break | |
return az1_name, az2_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment