Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions.
| 13 | # snippet-start:[python.example_code.ec2.VpcWrapper.class] |
| 14 | # snippet-start:[python.example_code.ec2.VpcWrapper.decl] |
| 15 | class VpcWrapper: |
| 16 | """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions.""" |
| 17 | |
| 18 | def __init__(self, ec2_client: boto3.client): |
| 19 | """ |
| 20 | Initializes the VpcWrapper with an EC2 client. |
| 21 | |
| 22 | :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level |
| 23 | access to AWS EC2 services. |
| 24 | """ |
| 25 | self.ec2_client = ec2_client |
| 26 | |
| 27 | @classmethod |
| 28 | def from_client(cls) -> "VpcWrapper": |
| 29 | """ |
| 30 | Creates a VpcWrapper instance with a default EC2 client. |
| 31 | |
| 32 | :return: An instance of VpcWrapper initialized with the default EC2 client. |
| 33 | """ |
| 34 | ec2_client = boto3.client("ec2") |
| 35 | return cls(ec2_client) |
| 36 | |
| 37 | # snippet-end:[python.example_code.ec2.VpcWrapper.decl] |
| 38 | |
| 39 | # snippet-start:[python.example_code.ec2.CreateVpc] |
| 40 | def create(self, cidr_block: str) -> str: |
| 41 | """ |
| 42 | Creates a new Amazon VPC with the specified CIDR block. |
| 43 | |
| 44 | :param cidr_block: The CIDR block for the new VPC, such as '10.0.0.0/16'. |
| 45 | :return: The ID of the new VPC. |
| 46 | """ |
| 47 | try: |
| 48 | response = self.ec2_client.create_vpc(CidrBlock=cidr_block) |
| 49 | vpc_id = response["Vpc"]["VpcId"] |
| 50 | |
| 51 | waiter = self.ec2_client.get_waiter("vpc_available") |
| 52 | waiter.wait(VpcIds=[vpc_id]) |
| 53 | return vpc_id |
| 54 | except ClientError as client_error: |
| 55 | logging.error( |
| 56 | "Couldn't create the vpc. Here's why: %s", |
| 57 | client_error.response["Error"]["Message"], |
| 58 | ) |
| 59 | raise |
| 60 | |
| 61 | # snippet-end:[python.example_code.ec2.CreateVpc] |
| 62 | |
| 63 | # snippet-start:[python.example_code.ec2.DescribeRouteTables] |
| 64 | def describe_route_tables(self, vpc_ids: list[str]) -> None: |
| 65 | """ |
| 66 | Displays information about the route tables in the specified VPC. |
| 67 | |
| 68 | :param vpc_ids: A list of VPC IDs. |
| 69 | """ |
| 70 | try: |
| 71 | response = self.ec2_client.describe_route_tables( |
| 72 | Filters=[{"Name": "vpc-id", "Values": vpc_ids}] |
no outgoing calls