6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VPC with a Single Public Subnet Only を boto で自作

Posted at

Amazon VPC の Management Console で VPC 作ると、

  • VPC with a Single Public Subnet Only
  • VPC with Public and Private Subnets
  • VPC with Public and Private Subnets and Hardware VPN Access
  • VPC with a Private Subnet Only and Hardware VPN Access

の四つのテンプレートから選ぶことができますが(2012年8月時点)、そいつらをどうやって API 叩いて自作するのよ?って話です。コンソールぽちぽちして作るよりも、コマンド一発のほうがカッコいいし再現性あるじゃないですか。

とりあえず、1つ目の「VPC with a Single Public Subnet Only」を作ってみます。言語は Python、ライブラリはもちろん boto です。boto の VPC リファレンスはこちら

import boto.ec2
from boto.vpc import VPCConnection

# リージョンは ap-northeast-1
ec2region = boto.ec2.get_region("ap-northeast-1")

def launch_vpc():
    conn = VPCConnection(region=ec2region)

    # VPC を作成
    vpc = conn.create_vpc('10.0.0.0/16')

    # インターネットゲートウェイを設定
    igw = conn.create_internet_gateway()
    conn.attach_internet_gateway(igw.id, vpc.id)

    # サブネットを作成
    subnet = conn.create_subnet(vpc.id, "10.0.0.0/24")

    # ルーティングを設定
    # 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

だいたいこんな感じですが、厳密にはテンプレとちょっと違ってます。

テンプレではメインのルーティングテーブルが外に出られない状態で、外に出るためのルーティングテーブルを別途作る形になっていますが、上のコードでは、メインのルーティングテーブルに対して外に出る口を設けています。作られるルーティングテーブルはひとつだけです。全部のサーバが外に出たいならこのほうが使いやすいと思います。

苦労したのは、作成した VPC に割り当てられてるルーティングテーブルを引き当てるところ。get_all_route_tables の filter を設定してやれば実現できますが、なかなかそこにたどり着けませんでした。filter の種類は DescribeRouteTable のリファレンスにたくさん書いてあります。boto 使うときには AWS 側の API リファレンスもチェックしたほうがいいですねー。

conn.get_all_route_tables(filters=(("vpc-id", vpc.id),))[0]

これで、VPC の id が vpc.id に一致するルーティングテーブルを引っ張ることができるわけです。

ちなみに、当初は Ruby で書こうと思ってたんですが、AWS SDK for Ruby は VPC のサポート無し。やっぱり AWS 使うなら Python だな!

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?