<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=1678611822423757&amp;ev=PageView&amp;noscript=1">
Defrag This

| Read. Reflect. Reboot.

How to Create and Configure an AWS VPC with Python

Prateek Singh| March 29 2019

| IT insights, How to, Automation, Python, AWS, Scripting


Amazon Web Services enables you to create a custom defined virtual network also know as Amazon VPC or Amazon Virtual Private Cloud, which, just like any traditional network in a data center, is highly scalable and easily configurable using programming languages like Python. In this article we will demonstrate how to automate creating an AWS VPC and configure a custom virtual network.

This will let you deploy infrastructure components like EC2 instances on AWS using the AWS SDK for Python also known as the Boto3 library. Please refer to my previous article here to grant programmatic access from AWS and setup the environment local computer with AWS credentials.

Let’s start by creating a basic VPC in AWS Cloud and then we'll configure it to our requirement in later sections of this article.

Create a VPC

First thing's first let’s import the boto3 library in Python create an ‘ec2’ resource object using the method ‘resource()’ after Managed File Transfer Automationthat using the create_vpc() method create a virtual private network by passing the CIDR notation as an argument to named parameter ‘CidrBlock’. CIDR notations are compact representations of the IP addresses and its associated routing prefix like ''.

import boto3
ec2 = boto3.resource('ec2')

# create VPC
vpc = ec2.create_vpc(CidrBlock='')

Once the VPC has been created you ca even name it using the create_tags() method.

# assign a name to our VPC

vpc.create_tags(Tags=[{"Key": "Name", "Value": "my_vpc"}])


Now we can also enable the Public DNS Hostnames by calling the client method of boto3 library and then accessing the modify_vpc_attribute() method, so that we can access the public DNS names of the EC2 instance we would be creating in this VPC. 

# enable public dns hostname so that we can SSH into it later
ec2Client = boto3.client('ec2')
ec2Client.modify_vpc_attribute( VpcId = vpc.id , EnableDnsSupport = { 'Value': True } )
ec2Client.modify_vpc_attribute( VpcId = vpc.id , EnableDnsHostnames = { 'Value': True } )

vpc-1Creating an Internet Gateway and Attaching it to the VPC

You can control internet access to the instances in your VPC. If you want to make your EC2 instances available on the internet, then you have to first create an Internet Gateway and then attach it to your VPC. 

# create an internet gateway and attach it to VPC
internetgateway = ec2.create_internet_gateway()

Creating a Route Table and an Associate Route Table with the Subnet

Now we'll create a Route Table in the VPC using the create_route_table() method, and then create a new route which will ge attached to the internet gateway we created earlier, to establish a public route. 

# create a route table and a public route
routetable = vpc.create_route_table()
route = routetable.create_route(DestinationCidrBlock='', GatewayId=internetgateway.id)

Finally, we'll create a subnet in the VPC and associate it to the route table. 

# create subnet and associate it with route table
subnet = ec2.create_subnet(CidrBlock='', VpcId=vpc.id)

Creating a Security Group and Defining the In-Bound Rules

We'll now set up a new security group using the create_security_group() method, and assign it to our VPC. Then we'll define an inbound rules to only allow SSH port number 22. 

# Create a security group and allow SSH inbound rule through the VPC
securitygroup = ec2.create_security_group(GroupName='SSH-ONLY', Description='only allow SSH traffic', VpcId=vpc.id)
securitygroup.authorize_ingress(CidrIp='', IpProtocol='tcp', FromPort=22, ToPort=22)

vpc2Creating an AWS EC2 Instance in the VPC

Once the security group is set up, we'll create a new key pair to SSH into our EC2 instances, then store it t a local file: 'ec2-keypair.pem'

# create a file to store the key locally
outfile = open('ec2-keypair.pem', 'w')

# call the boto ec2 function to create a key pair
key_pair = ec2.create_key_pair(KeyName='ec2-keypair')

# capture the key and store it in a file
KeyPairOut = str(key_pair.key_material)

Finally, we'll launch a new Linux EC2 instance and pass the name of the key pair to the named parameter KeyName of the create_instances() method. 

# Create a linux instance in the subnet
instances = ec2.create_instances(
'SubnetId': subnet.id,
'DeviceIndex': 0,
'AssociatePublicIpAddress': True,
'Groups': [securitygroup.group_id]

It will take just a few minutes to launch your Linux EX2 instance in the VPC we just greated. Meanwhile, we'll change the mode of the file on which we stored our key pair t read-only mode. This is require if you want to SSH into your Linux virtual machines in AWS. 

chmod 400 ec2-keypair.pem

Now, in the AWS console under the EC2 dashboard, you can search for your virtual machines and find the public DNS name of the virtual machine we just launched. Then we can SSH into the EC2 instance using the key pair file and the Public DNS as demonstrated in the following image. 


I hope you found this tutorial useful, we'll be back soon with further Python tutorials. Until then you can check out the rest of the How-to articles on the Ipswitch site. 


Topics: IT insights, How to, Automation, Python, AWS, Scripting

Leave a Reply

Your email address will not be published. Required fields are marked *


Engineer. Blogger. Science and Technology fan. Prateek Singh is a devotee of PowerShell and Python, and the founder of RidiCurious.com.

Free Trials

Getting started has never been easier. Download a trial today.

Download Free Trials

Contact Us

Let us know how we can help you. Focus on what matters. 

Send us a note

Subscribe to our Blog

Let’s stay in touch! Register to receive our blog updates.