⬡ Hub
Skip to content

AWS VPC (Virtual Private Cloud)

Detailed Content

Amazon Virtual Private Cloud (Amazon VPC) enables you to launch AWS resources into a virtual network that you've defined. This virtual network closely resembles a traditional network that you'd operate in your own data center, with the benefits of using the scalable infrastructure of AWS.

Core Concepts

  • VPC: A logically isolated virtual network dedicated to your AWS account. You have complete control over your virtual networking environment, including selection of your own IP address range (CIDR block), creation of subnets, and configuration of route tables, network gateways, and security settings. This isolation ensures that your resources are separate from other AWS customers' resources.
  • Subnets: A range of IP addresses within your VPC. You can launch AWS resources, such as EC2 instances, into a specified subnet. Subnets are tied to a single Availability Zone (AZ) for high availability. They can be:
    • Public Subnet: Has a route to an Internet Gateway, allowing instances within it to communicate with the internet. Resources in public subnets typically have public IP addresses.
    • Private Subnet: Does not have a route to an Internet Gateway. Instances within it cannot directly communicate with the internet. They are typically used for backend resources like databases or application servers.
  • Route Tables: Contain a set of rules, called routes, that are used to determine where network traffic from your subnet or gateway is directed. Each subnet must be associated with a route table.
  • Internet Gateway (IGW): A horizontally scaled, redundant, and highly available VPC component that allows communication between instances in your VPC and the internet. It provides a target for internet-routable traffic in your VPC route tables.
  • NAT Gateway/NAT Instance: Enables instances in a private subnet to connect to the internet or other AWS services (e.g., for software updates, patching, or accessing S3) but prevents the internet from initiating a connection with those instances. NAT Gateways are a managed service, highly available, and preferred over self-managed NAT Instances.
  • Network Access Control Lists (NACLs): An optional layer of security for your VPC that acts as a stateless firewall for controlling traffic in and out of one or more subnets. NACLs evaluate rules in order (lowest numbered rule first) and apply to all instances within the associated subnets. They have separate inbound and outbound rules and explicitly allow or deny traffic.
  • Security Groups: Act as a virtual stateful firewall for your instance to control inbound and outbound traffic. Security groups evaluate all rules before deciding to allow traffic. They are associated with network interfaces (and thus instances) and only have allow rules (you cannot explicitly deny traffic).
  • VPC Peering: A networking connection between two VPCs that enables you to route traffic between them privately using private IP addresses. Instances in either VPC can communicate with each other as if they are within the same network. VPC peering connections are non-transitive (you cannot chain peering connections).
  • VPC Endpoints: Enables you to privately connect your VPC to supported AWS services and VPC endpoint services powered by AWS PrivateLink without requiring an internet gateway, NAT device, VPN connection, or AWS Direct Connect connection. Traffic between your VPC and the service remains within the Amazon network.
    • Interface Endpoints: Powered by AWS PrivateLink, an elastic network interface (ENI) with a private IP address from the IP address range of your subnet that serves as an entry point for traffic destined to a supported service (e.g., SQS, SNS, EC2 APIs). They are highly available and fault-tolerant.
    • Gateway Endpoints: A gateway that you specify as a target for a route in your route table for traffic destined to a supported AWS service. Currently, only Amazon S3 and DynamoDB support Gateway Endpoints.
  • AWS Direct Connect: Establishes a dedicated, private network connection from your on-premises data center to AWS. It offers higher bandwidth, lower latency, and a more consistent network experience compared to internet-based VPN connections.
  • AWS Site-to-Site VPN: Creates an encrypted connection between your VPCs and your on-premises networks over the public internet. It uses IPsec tunnels to secure communication.
  • AWS Transit Gateway: A network transit hub that you can use to interconnect your VPCs and on-premises networks. It simplifies network management by acting as a central point for routing traffic between thousands of VPCs, AWS accounts, and on-premises networks, overcoming the non-transitive limitation of VPC peering.
  • VPN CloudHub: A feature of AWS Site-to-Site VPN that allows you to connect multiple on-premises sites to a single AWS Transit Gateway or Virtual Private Gateway, enabling communication between your remote sites over the AWS network.
  • Egress-Only Internet Gateway: A stateful gateway that provides outbound-only internet access for IPv6 traffic from instances in your private subnets. It prevents inbound IPv6 traffic from the internet to your instances.

VPC Design, Networking, and Firewalls

Effective VPC design is crucial for security, scalability, and cost-efficiency. This involves selecting the right architecture, planning your IP space, and implementing appropriate security controls.

VPC Design Patterns

  1. Single VPC:

    • Description: All resources (web servers, application servers, databases) are placed in a single VPC, typically segregated by subnets (e.g., public subnets for web servers, private subnets for application/database tiers).
    • Use Case: Ideal for simple, small-scale applications, development/testing environments, or when you are just starting with AWS.
    • Pros: Simple to manage and understand.
    • Cons: Can become difficult to manage as the application grows. A single security breach could potentially impact all resources. Limited blast radius.
  2. Multi-VPC Architecture:

    • Description: Using multiple VPCs to isolate different environments (e.g., development, testing, production) or different business units. Connectivity between these VPCs is often achieved using VPC Peering or AWS Transit Gateway.
    • Use Case: Standard for production environments, providing strong isolation for security and billing purposes.
    • Pros: Strong security boundaries, smaller blast radius, better organization, and easier cost allocation.
    • Cons: More complex to manage connectivity and routing between VPCs.
  3. Hub-and-Spoke Model with Transit Gateway:

    • Description: A central "hub" VPC (often connected to on-premises networks) connects to multiple "spoke" VPCs via an AWS Transit Gateway. The Transit Gateway acts as a cloud router, simplifying connectivity. All traffic between spokes, or between a spoke and on-premises, flows through the hub.
    • Use Case: Large-scale deployments with many VPCs across multiple accounts, requiring centralized connectivity and shared services (like firewalls or DNS).
    • Pros: Scalable, simplified network management, centralized control point for traffic inspection and routing.
    • Cons: Transit Gateway has associated costs. The hub can become a single point of failure if not designed for high availability.

Advanced Routing and Inspection

Route tables control where network traffic is directed. In advanced scenarios, you can route traffic through intermediate appliances for inspection or security purposes.

  • Routing to a Firewall: You can create a dedicated "inspection" VPC that contains firewall appliances (like AWS Network Firewall or third-party solutions from the AWS Marketplace). By modifying route tables in your application VPCs (spokes), you can direct all internet-bound traffic (or traffic between VPCs) to the firewall endpoints in the inspection VPC before it is sent to its final destination. This allows for centralized traffic filtering and monitoring.

Centralized Firewall with AWS Network Firewall

  • AWS Network Firewall: A managed, stateful firewall service that provides deep packet inspection, intrusion prevention (IPS), and web filtering. It is designed to be deployed centrally and used across multiple VPCs.
  • How it Differs from Security Groups/NACLs:
    • Security Groups/NACLs: Provide basic, layer 4 (TCP/UDP port and IP address) filtering. They are fundamental for network segmentation.
    • AWS Network Firewall: Provides advanced, layer 7 protection. It can inspect traffic content (e.g., looking for malicious patterns in HTTP requests), block known malicious domains, and enforce more granular security policies.
  • Typical Setup:
    1. Deploy a Firewall in a central "inspection" VPC.
    2. Create firewall endpoints in each Availability Zone for high availability.
    3. Use AWS Transit Gateway to route traffic from your application VPCs to the firewall endpoints.
    4. Configure firewall policies to allow or deny traffic based on rules you define.

VPC Flow Logs

VPC Flow Logs is a feature that enables you to capture information about the IP traffic going to and from network interfaces in your VPC. Flow log data can be published to Amazon CloudWatch Logs or Amazon S3.

Common Use Cases and Examples

  • Multi-Tier Web Application:

    • Architecture: A classic three-tier setup.
      • Web Tier: Public subnets with an Internet Gateway for inbound web traffic. EC2 instances are in an Auto Scaling group behind an Application Load Balancer.
      • Application Tier: Private subnets. These instances process business logic and only accept traffic from the web tier's security group. They use a NAT Gateway for outbound internet access (e.g., to call external APIs or for software updates).
      • Database Tier: Private subnets with no internet access route. These instances (e.g., RDS) only accept traffic from the application tier's security group.
    • Benefit: Strong security posture by layering defenses and minimizing the attack surface.
  • Securely Accessing AWS Services with VPC Endpoints:

    • Scenario: An application running on EC2 in a private subnet needs to read and write data to an S3 bucket and a DynamoDB table. The company's security policy prohibits any traffic from this VPC to the public internet.
    • Solution:
      • Create a Gateway Endpoint for both Amazon S3 and DynamoDB.
      • In the private subnet's route table, add a route that directs traffic destined for S3/DynamoDB to the respective gateway endpoint.
    • Benefit: All traffic to S3 and DynamoDB stays within the AWS private network, enhancing security and potentially reducing data transfer costs. No NAT Gateway is required for this communication.
  • Hybrid Cloud Connectivity:

    • Scenario: A company wants to extend its on-premises data center to AWS, allowing on-premises servers to communicate with EC2 instances in a VPC.
    • Solutions:
      • AWS Site-to-Site VPN: A cost-effective solution for creating a secure, IPsec VPN tunnel over the public internet. Ideal for moderate bandwidth requirements.
      • AWS Direct Connect: For high-bandwidth, low-latency needs, a dedicated private fiber connection is established between the on-premises data center and an AWS Direct Connect location.
    • Benefit: Creates a seamless hybrid environment, enabling use cases like data migration, disaster recovery, and bursting capacity to the cloud.
  • Scalable Inter-VPC Communication with Transit Gateway:

    • Scenario: A large enterprise has dozens of VPCs spread across multiple AWS accounts for different applications and business units. They need a scalable way for these VPCs to communicate with each other and with their on-premises network.
    • Solution:
      • Deploy a central AWS Transit Gateway.
      • Attach all VPCs and the on-premises connection (VPN or Direct Connect) to the Transit Gateway.
      • The Transit Gateway's route tables manage routing between all attachments.
    • Benefit: Drastically simplifies network management compared to a complex mesh of VPC peering connections. It provides a central point for monitoring and controlling cross-network traffic.

Connectivity Options: Step-by-Step

Setting up VPC Peering

VPC Peering allows you to connect two VPCs privately using private IP addresses.

  1. Initiate the Peering Request:

    • Navigate to the VPC dashboard.
    • In the navigation pane, choose Peering Connections, then Create Peering Connection.
    • Configure the following:
      • Name tag: Give your peering connection a descriptive name.
      • VPC ID (Requester): Select the VPC in your account that will initiate the request.
      • Accepter VPC Information: Specify the VPC you want to connect to. This can be in your account or another AWS account in the same or different region.
    • Click Create Peering Connection.
  2. Accept the Peering Request:

    • The owner of the accepter VPC must accept the request.
    • They will find the pending request in their Peering Connections dashboard with the status pending-acceptance.
    • Select the peering connection and choose Actions > Accept Request.
  3. Update Route Tables in Both VPCs:

    • For traffic to flow, you must add a route to the route table of each VPC that points to the CIDR block of the other VPC.
    • For the Requester VPC:
      • Go to Route Tables and select the route table associated with the subnets that need to communicate.
      • Choose the Routes tab, then Edit routes.
      • Add a new route: For Destination, enter the IPv4 CIDR block of the accepter VPC. For Target, select Peering Connection and choose the peering connection you created.
    • For the Accepter VPC:
      • Repeat the process, adding a route with the destination as the requester VPC's CIDR block and the target as the same peering connection.
  4. Update Security Groups and NACLs:

    • Ensure that the security groups associated with the instances in both VPCs allow traffic to and from the peered VPC's CIDR range on the required ports and protocols.
    • Similarly, check your NACL rules to ensure they don't block the traffic.

Setting up AWS Direct Connect

Direct Connect provides a dedicated, private physical network connection from your on-premises data center to AWS.

  1. Order a Direct Connect Connection:

    • In the AWS Direct Connect console, choose Connections, then Create connection.
    • Select the Direct Connect location where you want to establish the connection, the desired port speed (e.g., 1 Gbps, 10 Gbps), and the service provider.
  2. Download the Letter of Authorization (LOA-CFA):

    • After you submit the request, AWS will make the LOA-CFA available for download. This is a standard document that authorizes the service provider to establish the physical cross-connect between their network and the AWS routers at the Direct Connect location.
    • Provide this document to your service provider to provision the connection.
  3. Create a Virtual Interface (VIF):

    • Once the physical connection is established (your provider will notify you), you must create a VIF to handle traffic.
    • In the Direct Connect console, select your connection and choose Create Virtual Interface.
    • Private VIF: To connect to your VPCs. You will associate it with a Virtual Private Gateway (VGW) attached to your VPC or a Direct Connect Gateway.
    • Transit VIF: To connect to one or more Transit Gateways.
    • Public VIF: To access public AWS services (like S3, EC2 APIs) over a private path.
    • You will need to provide your network's public ASN and configure BGP settings.
  4. Configure On-Premises Router and Establish BGP:

    • Using the VIF details (AWS router IP, your router IP, BGP ASN), configure your on-premises router to establish a BGP session with the AWS router.
    • Once the BGP session is up, your on-premises network will learn the AWS routes, and AWS will learn your on-premises routes.
  5. Attach to VPC and Update Routing:

    • If using a Private VIF with a VGW, ensure the VGW is attached to your VPC.
    • Enable Route Propagation in your VPC's route tables to automatically propagate the on-premises routes learned via BGP. Alternatively, you can add static routes pointing to the VGW.

Setting up AWS Transit Gateway

Transit Gateway is a network transit hub that simplifies connectivity between VPCs and on-premises networks in a hub-and-spoke model.

  1. Create the Transit Gateway:

    • In the VPC console, navigate to Transit Gateways and choose Create Transit Gateway.
    • Provide a Name tag and description.
    • Configure options such as the Amazon side ASN, DNS support, and VPN ECMP support.
    • Click Create Transit Gateway. The creation process can take a few minutes.
  2. Create Transit Gateway Attachments:

    • A Transit Gateway is not useful until you attach your networks to it.
    • Go to Transit Gateway Attachments and click Create Transit Gateway Attachment.
    • VPC Attachment: Select the Transit Gateway ID and the VPC you want to attach. Choose one subnet from each Availability Zone within the VPC for the attachment to use. This ensures high availability.
    • VPN Attachment: To connect an on-premises network via a Site-to-Site VPN. You will link it to a Customer Gateway.
    • Direct Connect Attachment: To connect via a Direct Connect connection. You will link it to a Direct Connect Gateway with a Transit VIF.
  3. Configure Routing:

    • VPC Subnet Route Tables: For each attached VPC, you must update the subnet route tables. Add a route for any destination CIDR (e.g., another VPC's CIDR or your on-premises network's CIDR) and set the Target to the Transit Gateway ID.
    • Transit Gateway Route Tables: The Transit Gateway itself has route tables that control where traffic is sent after it arrives.
      • By default, all attachments are associated with a single default route table, and routes are propagated from all attachments, creating a full mesh network.
      • For more granular control (e.g., isolating spokes or creating a centralized inspection VPC), you can create additional route tables, disable propagation, and create static routes to direct traffic flow precisely.

Interview Questions

Conceptual Questions

  1. What is a VPC and why is it important?
    • An Amazon Virtual Private Cloud (VPC) is a logically isolated virtual network dedicated to your AWS account. It allows you to launch AWS resources into a virtual network that you've defined, giving you complete control over your network environment. It's crucial for:
      • Isolation and Security: Your resources are isolated from other AWS customers and the public internet.
      • Network Control: You define IP address ranges, subnets, route tables, network gateways, and security settings.
      • Hybrid Cloud: Enables secure connectivity between your AWS cloud and on-premises data centers.
      • Compliance: Helps meet various regulatory and compliance requirements.
  2. Explain the difference between a public and a private subnet. How do instances in each communicate with the internet?
    • Public Subnet: Has a route to an Internet Gateway (IGW). Instances in a public subnet can communicate directly with the internet if they have a public IP address or an Elastic IP (EIP).
    • Private Subnet: Does not have a route to an Internet Gateway. Instances in a private subnet cannot directly communicate with the internet. To access the internet (e.g., for updates), they must route their traffic through a NAT Gateway (or NAT instance) located in a public subnet.
  3. What is the difference between Security Groups and NACLs? When would you use each?
    • Security Groups:
      • Instance-level: Applied to EC2 instances (or ENIs).
      • Stateful: If you allow inbound traffic, the outbound response is automatically allowed.
      • Allow rules only: You can only specify rules that allow traffic.
      • Primary use: Controlling traffic to/from individual instances.
    • Network Access Control Lists (NACLs):
      • Subnet-level: Applied to subnets.
      • Stateless: If you allow inbound traffic, you must explicitly allow outbound response traffic.
      • Allow and deny rules: You can specify both allow and deny rules.
      • Primary use: Providing an additional layer of security at the subnet boundary, often used for stricter network segmentation.
  4. When would you use a NAT Gateway versus an Internet Gateway?
    • Internet Gateway (IGW): Used for public subnets to enable both inbound and outbound internet access for resources that need to be directly reachable from the internet (e.g., web servers).
    • NAT Gateway: Used for private subnets to allow instances to initiate outbound connections to the internet (e.g., for software updates, accessing AWS services) while preventing unsolicited inbound connections from the internet. It provides network address translation.
  5. Explain VPC Endpoints. What are the two types and when would you use them?
    • VPC Endpoints allow you to privately connect your VPC to supported AWS services and VPC endpoint services powered by AWS PrivateLink without requiring an internet gateway, NAT device, VPN connection, or AWS Direct Connect. Traffic stays within the AWS network.
    • Gateway Endpoints: Used for Amazon S3 and DynamoDB. You specify them as a target in your route table. They are free.
    • Interface Endpoints: Powered by AWS PrivateLink. They create an Elastic Network Interface (ENI) with a private IP address in your subnet, acting as an entry point for traffic to a service. Used for a wide range of AWS services (e.g., SQS, SNS, EC2 APIs) and your own PrivateLink services. You pay for Interface Endpoints.
  6. What is AWS Transit Gateway and how does it improve network architecture compared to VPC peering?
    • AWS Transit Gateway is a network transit hub that you can use to interconnect your VPCs and on-premises networks. It simplifies network management by acting as a central point for routing traffic between thousands of VPCs, AWS accounts, and on-premises networks. It overcomes the non-transitive limitation of VPC peering, allowing any attached VPC or network to communicate with any other attached VPC or network.

Scenario-Based Questions

  1. You have a multi-tier application with a web server in a public subnet, an application server in a private subnet, and a database server in another private subnet. How would you ensure that:
    • a) The web server can communicate with the application server.
    • b) The application server can communicate with the database server.
    • c) The application server can access the internet for software updates, but is not directly accessible from the internet.
    • d) The database server has no internet access at all.
    • Solution:
      • a) Web to App: Ensure the web server's security group allows outbound traffic to the application server's security group on the necessary ports (e.g., 8080). The application server's security group must allow inbound traffic from the web server's security group.
      • b) App to DB: Similarly, the application server's security group allows outbound to the database server's security group (e.g., port 3306 for MySQL). The database server's security group allows inbound from the application server's security group.
      • c) App Server Internet Access: Deploy a NAT Gateway in the public subnet. Configure the route table of the application server's private subnet to route all internet-bound traffic (0.0.0.0/0) through the NAT Gateway. This allows outbound internet access while preventing inbound connections.
      • d) DB Server No Internet Access: The database server would be in a private subnet whose route table does not have a route to an Internet Gateway or a NAT Gateway. This ensures complete isolation from the internet.
  2. Your company has multiple AWS accounts, each with its own VPC, and an on-premises data center. You need to establish secure and scalable connectivity between all these VPCs and the on-premises network. What is the most efficient AWS networking service to achieve this?
    • I would use AWS Transit Gateway. Instead of creating numerous point-to-point VPC peering connections (which are non-transitive and become complex with many VPCs), Transit Gateway acts as a central hub. All VPCs and the on-premises network (via Site-to-Site VPN or Direct Connect) would connect to the Transit Gateway, simplifying routing and management. This provides a hub-and-spoke network architecture.
  3. You need to access an SQS queue and an EC2 API from an EC2 instance located in a private subnet, without exposing any traffic to the public internet. How would you configure this?
    • For the SQS queue and EC2 API, I would use VPC Interface Endpoints (powered by AWS PrivateLink). I would create an interface endpoint for SQS and another for EC2 in the private subnet. This creates ENIs with private IP addresses in my VPC, allowing the EC2 instance to communicate with SQS and the EC2 API directly over the AWS private network, bypassing the internet gateway and NAT gateway.
  4. You are troubleshooting network connectivity issues within your VPC. What AWS feature can help you capture and analyze IP traffic information?
    • I would use VPC Flow Logs. VPC Flow Logs capture information about the IP traffic going to and from network interfaces in your VPC. This data can be published to Amazon CloudWatch Logs or Amazon S3, allowing me to analyze traffic patterns, identify blocked ports, diagnose connectivity issues, and detect anomalies.

Coding/CLI Examples

Here are some common VPC operations using the AWS CLI and Python (Boto3).

AWS CLI Examples

  1. Create a VPC with a specified CIDR block: bash aws ec2 create-vpc --cidr-block 10.0.0.0/16 --tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=MyNewVPC}]'

  2. Create a public subnet within a VPC: bash VPC_ID="vpc-0abcdef1234567890" # Replace with your VPC ID aws ec2 create-subnet \ --vpc-id $VPC_ID \ --cidr-block 10.0.1.0/24 \ --availability-zone us-east-1a \ --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=MyPublicSubnet}]'

  3. Create an Internet Gateway and attach it to a VPC: ```bash VPC_ID="vpc-0abcdef1234567890" # Replace with your VPC ID

    IGW_ID=$(aws ec2 create-internet-gateway --tag-specifications 'ResourceType=internet-gateway,Tags=[{Key=Name,Value=MyIGW}]' --query 'InternetGateway.InternetGatewayId' --output text) echo "Created Internet Gateway: $IGW_ID"

    aws ec2 attach-internet-gateway --vpc-id $VPC_ID --internet-gateway-id $IGW_ID echo "Attached Internet Gateway $IGW_ID to VPC $VPC_ID" ```

  4. Create a Route Table and associate it with a subnet: ```bash VPC_ID="vpc-0abcdef1234567890" # Replace with your VPC ID SUBNET_ID="subnet-0abcdef1234567890" # Replace with your Subnet ID IGW_ID="igw-0abcdef1234567890" # Replace with your Internet Gateway ID

    ROUTE_TABLE_ID=$(aws ec2 create-route-table --vpc-id $VPC_ID --tag-specifications 'ResourceType=route-table,Tags=[{Key=Name,Value=MyPublicRouteTable}]' --query 'RouteTable.RouteTableId' --output text) echo "Created Route Table: $ROUTE_TABLE_ID"

    Add a route to the Internet Gateway

    aws ec2 create-route --route-table-id $ROUTE_TABLE_ID --destination-cidr-block 0.0.0.0/0 --gateway-id $IGW_ID echo "Added default route to IGW in Route Table $ROUTE_TABLE_ID"

    Associate the route table with the subnet

    aws ec2 associate-route-table --subnet-id $SUBNET_ID --route-table-id $ROUTE_TABLE_ID echo "Associated Route Table $ROUTE_TABLE_ID with Subnet $SUBNET_ID" ```

  5. Create a NAT Gateway: ```bash PUBLIC_SUBNET_ID="subnet-0abcdef1234567890" # Replace with a public subnet ID

    Allocate an Elastic IP for the NAT Gateway

    EIP_ALLOC_ID=$(aws ec2 allocate-address --domain vpc --query 'AllocationId' --output text) echo "Allocated Elastic IP Allocation ID: $EIP_ALLOC_ID"

    NAT_GATEWAY_ID=$(aws ec2 create-nat-gateway \ --subnet-id $PUBLIC_SUBNET_ID \ --allocation-id $EIP_ALLOC_ID \ --tag-specifications 'ResourceType=natgateway,Tags=[{Key=Name,Value=MyNATGateway}]' \ --query 'NatGateway.NatGatewayId' --output text) echo "Created NAT Gateway: $NAT_GATEWAY_ID"

    Wait for NAT Gateway to become available (this can take a few minutes)

    echo "Waiting for NAT Gateway to become available..." aws ec2 wait nat-gateway-available --nat-gateway-ids $NAT_GATEWAY_ID echo "NAT Gateway $NAT_GATEWAY_ID is available."

    Update private subnet's route table to use NAT Gateway for internet-bound traffic

    PRIVATE_ROUTE_TABLE_ID="rtb-0abcdef1234567890" # Replace with your private subnet's route table ID

    aws ec2 create-route --route-table-id $PRIVATE_ROUTE_TABLE_ID --destination-cidr-block 0.0.0.0/0 --nat-gateway-id $NAT_GATEWAY_ID

    ```

Python (Boto3) Examples

First, ensure you have Boto3 installed (pip install boto3) and your AWS credentials configured.

  1. Create a VPC, Subnet, and Internet Gateway: ```python import boto3

    ec2 = boto3.client('ec2')

    vpc_cidr = '10.0.0.0/16' subnet_cidr = '10.0.1.0/24' az = 'us-east-1a' # Replace with your desired AZ

    try: # Create VPC vpc_response = ec2.create_vpc(CidrBlock=vpc_cidr) vpc_id = vpc_response['Vpc']['VpcId'] ec2.create_tags(Resources=[vpc_id], Tags=[{'Key': 'Name', 'Value': 'MyBoto3VPC'}]) print(f"Created VPC: {vpc_id}")

    # Create Internet Gateway
    igw_response = ec2.create_internet_gateway()
    igw_id = igw_response['InternetGateway']['InternetGatewayId']
    ec2.create_tags(Resources=[igw_id], Tags=[{'Key': 'Name', 'Value': 'MyBoto3IGW'}])
    print(f"Created Internet Gateway: {igw_id}")
    
    # Attach IGW to VPC
    ec2.attach_internet_gateway(VpcId=vpc_id, InternetGatewayId=igw_id)
    print(f"Attached IGW {igw_id} to VPC {vpc_id}")
    
    # Create Subnet
    subnet_response = ec2.create_subnet(
        VpcId=vpc_id,
        CidrBlock=subnet_cidr,
        AvailabilityZone=az
    )
    subnet_id = subnet_response['Subnet']['SubnetId']
    ec2.create_tags(Resources=[subnet_id], Tags=[{'Key': 'Name', 'Value': 'MyBoto3PublicSubnet'}])
    print(f"Created Subnet: {subnet_id}")
    
    # Create Route Table and associate with Subnet
    route_table_response = ec2.create_route_table(VpcId=vpc_id)
    route_table_id = route_table_response['RouteTable']['RouteTableId']
    ec2.create_tags(Resources=[route_table_id], Tags=[{'Key': 'Name', 'Value': 'MyBoto3PublicRouteTable'}])
    print(f"Created Route Table: {route_table_id}")
    
    ec2.create_route(
        RouteTableId=route_table_id,
        DestinationCidrBlock='0.0.0.0/0',
        GatewayId=igw_id
    )
    print("Added default route to IGW")
    
    ec2.associate_route_table(
        SubnetId=subnet_id,
        RouteTableId=route_table_id
    )
    print(f"Associated Route Table {route_table_id} with Subnet {subnet_id}")
    

    except Exception as e: print(f"Error creating VPC resources: {e}") ```

  2. Create a VPC Interface Endpoint for SQS: ```python import boto3

    ec2 = boto3.client('ec2')

    vpc_id = "vpc-0abcdef1234567890" # Replace with your VPC ID subnet_ids = ["subnet-0abcdef1234567890", "subnet-0abcdef1234567891"] # Replace with your subnet IDs security_group_ids = ["sg-0abcdef1234567890"] # Replace with your security group ID

    try: response = ec2.create_vpc_endpoint( VpcId=vpc_id, VpcEndpointType='Interface', ServiceName='com.amazonaws.us-east-1.sqs', # Replace region if needed SubnetIds=subnet_ids, SecurityGroupIds=security_group_ids, TagSpecifications=[ { 'ResourceType': 'vpc-endpoint', 'Tags': [ { 'Key': 'Name', 'Value': 'MySQSInterfaceEndpoint' }, ] }, ] ) endpoint_id = response['VpcEndpoint']['VpcEndpointId'] print(f"Created SQS Interface Endpoint: {endpoint_id}") except Exception as e: print(f"Error creating VPC Interface Endpoint: {e}") ```