[python]Create AWS VPC with boto3

This is a follow up on this post https://cyruslab.net/2018/10/19/pythontrying-out-aws-sdk/
back then I was only trying out…
However I am beginning to take this seriously… as a hobby…


  • Setup awscli. The awscli is used to setup a default connection, by putting your access key id and secret key id, your preferred region and your default output format which i chose json. This output format is for me to process the response after vpc creation method was called.
    The awscli acts as an interface for passing python to my EC2, hence in my code there is no need to specify setup_default_session as default session has already been created by awscli.

  • Install boto3 using pip3 install boto3
  • Install pyboto3, this is for boto3 methods autocompletion in my pycharm IDE.
import boto3
import ipaddress

ec2_client = boto3.client('ec2')
# boto3 autocomplete https://blog.wavycloud.com/2016/12/27/boto3-pyboto3-autocomplete/
""" :type : pyboto3.ec2 """
user_response = input("Enter VPC subnet:")
    subnet = str(ipaddress.ip_network(user_response))
    response = ec2_client.create_vpc(CidrBlock=subnet)
    # print(type(response['ResponseMetadata']['HTTPStatusCode']))
    # print(response)
    if response['ResponseMetadata']['HTTPStatusCode'] == 200:
        print("VPC, {}, was created successfully at {}".format(response['Vpc']['VpcId'],
        print("There seems to be a problem fulfilling the request.")
except ValueError as e:

Screenshot 2019-05-05 at 12.58.17 AM
Before the script is triggered, this the default vpc created by AWS.

Screenshot 2019-05-05 at 1.00.47 AM
The response after the script was triggered.

Screenshot 2019-05-05 at 1.01.40 AM
New VPC was created.


One thought on “[python]Create AWS VPC with boto3

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 )

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