[python]Create VPC part 2

This post is an improvement to this.
The goal is to:

  • Create VPC.
  • Create internet gateway.
  • Attach internet gateway to vpc.
  • Name the internet gateway and vpc.

About parameters in create_tags
This method accepts

  • Resources of type list or tuple.
  • Tags of type dictionary.

The code works but is ugly and cannot scale, for demonstrating purpose it is ok… But I need to refine the code so that it is modular, such as creating classes and to be used repetitively.

import boto3
import ipaddress

# Initialize values
# Empty the list
vpc_resource_names = []
# Get user's subnet in CIDR format
user_vpc_network = input("Enter the network for VPC:")
# Get user's VPC name.
user_vpc_name = input("Enter VPC name:")
# Get user's internet gateway name.
user_vpc_igw_name = input("Enter internet gateway name:")

# this has to use twice, for creating tag to be used for create_tags method.
def create_tag(resource_name):
    tag = [
            'Key': 'Name',
            'Value': resource_name
    return tag

    # Specify to change EC2 instance
    ec2_instance = boto3.client('ec2')
    # pyboto3 autocomplete
    """:type : pyboto3.ec2"""
        # test the validity of subnet, recommended to use regex instead of ipaddress.
        valid_cidr = str(ipaddress.ip_network(user_vpc_network))
            # Creates VPC with subnet specified.
            vpc_cidr_response = ec2_instance.create_vpc(CidrBlock=valid_cidr)
            # See response in https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.create_vpc
            # Case sensitive.
            vpc_id = vpc_cidr_response['Vpc']['VpcId']
            # Include VPC ID to the list, required for create_tags method.
            # Create name for VPC
            print("{} is created successfully".format(vpc_id))
                # Create an internet gateway.
                igw_create_response = ec2_instance.create_internet_gateway()
                # See response https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Vpc.attach_internet_gateway
                igw_id = igw_create_response['InternetGateway']['InternetGatewayId']
                # Overwrites the VPC ID value with IGW ID.
                vpc_resource_names[0] = igw_id
                # Name the IGW.
                print("{} is created, attempting to attach to {}".format(igw_id, vpc_id))
                    ec2_instance.attach_internet_gateway(InternetGatewayId=igw_id, VpcId=vpc_id)
                    print("{} is successfully attached to {}".format(igw_id, vpc_id))
                except BaseException:
                    print("It seems there is a problem attaching internet gateway to VPC.")
            except BaseException:
                print("It seems there is a problem creating internet gateway.")
        except BaseException as e:
            print("It seems there is a problem creating VPC. {}".format(e))
    except ValueError:
        print("Possibly invalid subnet")
except BaseException as e:


Results with all inputs.

Results with subnet and IGW name.

Results with only subnet.

Screenshot 2019-05-05 at 5.11.32 AM.png
Result with no input. Subnet is mandatory to create VPC, in essence a VPC is similar to VRF, has its own routing table. If it is exactly like VRF then each VPC can have the same subnets as well.

This entry was posted in Python, Scripting and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s