If you create a VPC in the Amazon VPC Management Console,
You can choose from four templates (as of August 2012), but how do you hit them with the API to make your own? It is a story. Isn't it cooler and more reproducible with a single command than making it with a console?
For the time being, let's make the first "VPC with a Single Public Subnet Only". The language is Python, and of course the library is boto. Click here for boto's VPC reference (http://docs.pythonboto.org/en/latest/ref/vpc.html).
import boto.ec2
from boto.vpc import VPCConnection
#Region is ap-northeast-1
ec2region = boto.ec2.get_region("ap-northeast-1")
def launch_vpc():
conn = VPCConnection(region=ec2region)
#Create a VPC
vpc = conn.create_vpc('10.0.0.0/16')
#Set up internet gateway
igw = conn.create_internet_gateway()
conn.attach_internet_gateway(igw.id, vpc.id)
#Create subnet
subnet = conn.create_subnet(vpc.id, "10.0.0.0/24")
#Set up routing
#See below for filters
# http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeRouteTables.html
route_table = conn.get_all_route_tables(filters=(("vpc-id", vpc.id),))[0]
conn.create_route(route_table.id, "0.0.0.0/0", gateway_id=igw.id)
print "Created VPC %s" % vpc.id
It looks like this, but strictly speaking, it's a little different from the template.
In the template, the main routing table cannot go out, and a routing table for going out is created separately, but in the above code, an exit is provided for the main routing table. I am. Only one routing table is created. I think this is easier to use if you want all the servers to go out.
The hard part was allocating the routing table assigned to the created VPC. I could do this by setting a filter for get_all_route_tables, but I couldn't get there. There are many types of filters in DescribeRouteTable Reference. When using boto, you should also check the API reference on the AWS side.
conn.get_all_route_tables(filters=(("vpc-id", vpc.id),))[0]
Now you can pull in the routing table where the VPC id matches vpc.id.
By the way, at first I was thinking of writing in Ruby, but the AWS SDK for Ruby does not support VPC. After all, if you use AWS, it's Python!
Recommended Posts