AWS CLIを使って1 つのパブリックサブネットのみを持つVPCを構築

aws_logo

Amazon Virtual Private Cloud の Getting Started Guide ドキュメントには、1 つのパブリックサブネットのみを持つ VPC を構築し、このサブネット内に Elastic IP をもつインスタンスを一つたてるエクササイズがある。

http://docs.aws.amazon.com/AmazonVPC/latest/GettingStartedGuide/ExerciseOverview.html

このエクササイズを、管理画面のウィザードなどを使わずに、コマンドラインツール AWS CLI からゴリゴリとやってみる。

VPC_GSG_Layout

Step 1: Set Up the VPC and Internet Gateway

http://docs.aws.amazon.com/AmazonVPC/latest/GettingStartedGuide/Wizard.html

VPC のウィザードで “VPC with a Single Public Subnet Only” を選択すると

  • VPC(size/16)の作成
  • VPC にインターネットゲートウェイの設定
  • サブネット(size/24)の作成
  • サブネットにインターネットゲートウェイへのルーティングを追加

をやってくれるところを、CLI で行う。

VPC作成

$ aws ec2 create-vpc --cidr-block  "10.5.0.0/16"
{
    "Vpc": {
        "InstanceTenancy": "default",
        "State": "pending",
        "VpcId": "vpc-00000xx0",
        "CidrBlock": "10.5.0.0/16",
        "DhcpOptionsId": "dopt-e7652d8f"
    }
}
$ aws ec2 create-tags --resources vpc-00000xx0 --tags Key=Name,Value=VPC検証
{
    "return": "true"
}

インターネットゲートウェイ

$ aws ec2 create-internet-gateway
{
    "InternetGateway": {
        "Tags": [],
        "InternetGatewayId": "igw-0a0a0aa00bf8",
        "Attachments": []
    }
}

$ aws ec2 attach-internet-gateway --internet-gateway-id igw-0a0a0aa00bf8 --vpc-id vpc-00000xx0
{
    "return": "true"
}

$ aws ec2 describe-internet-gateways --filters Name=attachment.vpc-id,Values=vpc-00000xx0
{
    "InternetGateways": [
        {
            "Tags": [],
            "InternetGatewayId": "igw-0a0a0aa00bf8",
            "Attachments": [
                {
                    "State": "available",
                    "VpcId": "vpc-00000xx0"
                }
            ]
        }
    ]
}

public subnet の追加

$ aws ec2 create-subnet --vpc-id vpc-00000xx0 --cidr-block "10.5.0.0/24"
{
    "Subnet": {
        "VpcId": "vpc-00000xx0",
        "CidrBlock": "10.5.0.0/24",
        "State": "pending",
        "AvailabilityZone": "ap-northeast-1c",
        "SubnetId": "subnet-0a00000a",
        "AvailableIpAddressCount": 251
    }
}

$ aws ec2 create-tags --resources subnet-0a00000a --tags Key=Name,Value="public subnet"
{
    "return": "true"
}
$ aws ec2 describe-subnets --filters Name=vpc-id,Values=vpc-00000xx0
{
    "Subnets": [
        {
            "VpcId": "vpc-00000xx0",
            "Tags": [
                {
                    "Value": "public subnet",
                    "Key": "Name"
                }
            ],
            "CidrBlock": "10.5.0.0/24",
            "MapPublicIpOnLaunch": false,
            "DefaultForAz": false,
            "State": "available",
            "AvailabilityZone": "ap-northeast-1c",
            "SubnetId": "subnet-0a00000a",
            "AvailableIpAddressCount": 251
        }
    ]
}

インターネットゲートウェイへのルーティングの追加

“Main”: true となっているルーティングは VPC 作成時についてくる、VPC 内の通信向けルーティング

$ aws ec2 describe-route-tables --filters Name=vpc-id,Values=vpc-00000xx0
{
    "RouteTables": [
        {
            "Associations": [
                {
                    "RouteTableAssociationId": "rtbassoc-d5130bb7",
                    "Main": true,
                    "RouteTableId": "rtb-65819807"
                }
            ],
            "RouteTableId": "rtb-65819807",
            "VpcId": "vpc-00000xx0",
            "PropagatingVgws": [],
            "Tags": [],
            "Routes": [
                {
                    "GatewayId": "local",
                    "DestinationCidrBlock": "10.5.0.0/16",
                    "State": "active",
                    "Origin": "CreateRouteTable"
                }
            ]
        }
    ]
}

インターネットゲートウェイ向けのルーティングを作成

$ aws ec2 create-route-table --vpc-id vpc-00000xx0
{
    "RouteTable": {
        "Associations": [],
        "RouteTableId": "rtb-f881989a",
        "VpcId": "vpc-00000xx0",
        "PropagatingVgws": [],
        "Tags": [],
        "Routes": [
            {
                "GatewayId": "local",
                "DestinationCidrBlock": "10.5.0.0/16",
                "State": "active",
                "Origin": "CreateRouteTable"
            }
        ]
    }
}
$ aws ec2 create-route --route-table-id rtb-f881989a --destination-cidr-block 0.0.0.0/0 --gateway-id igw-0a0a0aa00bf8
{
    "return": "true"
}

public subnet にアタッチ

$ aws ec2 associate-route-table --route-table-id rtb-f881989a --subnet-id subnet-0a00000a
{
    "AssociationId": "rtbassoc-3e140c5c"
}

VPC のルーティングを再確認

$ aws ec2 describe-route-tables --filters Name=vpc-id,Values=vpc-00000xx0
{
    "RouteTables": [
        {
            "Associations": [
                {
                    "SubnetId": "subnet-0a00000a",
                    "RouteTableAssociationId": "rtbassoc-3e140c5c",
                    "RouteTableId": "rtb-f881989a"
                }
            ],
            "RouteTableId": "rtb-f881989a",
            "VpcId": "vpc-00000xx0",
            "PropagatingVgws": [],
            "Tags": [],
            "Routes": [
                {
                    "GatewayId": "local",
                    "DestinationCidrBlock": "10.5.0.0/16",
                    "State": "active",
                    "Origin": "CreateRouteTable"
                },
                {
                    "GatewayId": "igw-0a0a0aa00bf8",
                    "DestinationCidrBlock": "0.0.0.0/0",
                    "State": "active",
                    "Origin": "CreateRoute"
                }
            ]
        },
        {
            "Associations": [
                {
                    "RouteTableAssociationId": "rtbassoc-d5130bb7",
                    "Main": true,
                    "RouteTableId": "rtb-65819807"
                }
            ],
            "RouteTableId": "rtb-65819807",
            "VpcId": "vpc-00000xx0",
            "PropagatingVgws": [],
            "Tags": [],
            "Routes": [
                {
                    "GatewayId": "local",
                    "DestinationCidrBlock": "10.5.0.0/16",
                    "State": "active",
                    "Origin": "CreateRouteTable"
                }
            ]
        }
    ]
}

Step 2: Set Up a Security Group for Your VPC

VPC にファイアウォールの設定をする

  • SSH(22)
  • HTTP(80)
  • HTTPS(443)

だけの Inbound を許可するセキュリティグループを作成。

コマンド

セキュリティグループの作成

$ aws ec2 create-security-group --group-name MySecurityGroup --description "My security group" --vpc-id vpc-00000xx0

{
    "return": "true",
    "GroupId": "sg-000aa000"
}

許可する inbound 通信を登録

$ aws ec2 authorize-security-group-ingress --group-id sg-000aa000 --protocol tcp --port 22 --cidr 0.0.0.0/0
{
    "return": "true"
}
$ aws ec2 authorize-security-group-ingress --group-id sg-000aa000 --protocol tcp --port 80 --cidr 0.0.0.0/0
{
    "return": "true"
}
$ aws ec2 authorize-security-group-ingress --group-id sg-000aa000 --protocol tcp --port 443 --cidr 0.0.0.0/0
{
    "return": "true"
}

VPC に登録されているセキュリティグループを確認

$ aws ec2 describe-security-groups --filters Name=vpc-id,Values=vpc-00000xx0
{
    "SecurityGroups": [
        {
            "IpPermissionsEgress": [
                {
                    "IpProtocol": "-1",
                    "IpRanges": [
                        {
                            "CidrIp": "0.0.0.0/0"
                        }
                    ],
                    "UserIdGroupPairs": []
                }
            ],
            "Description": "My security group",
            "IpPermissions": [
                {
                    "ToPort": 22,
                    "IpProtocol": "tcp",
                    "IpRanges": [
                        {
                            "CidrIp": "0.0.0.0/0"
                        }
                    ],
                    "UserIdGroupPairs": [],
                    "FromPort": 22
                },
                {
                    "ToPort": 80,
                    "IpProtocol": "tcp",
                    "IpRanges": [
                        {
                            "CidrIp": "0.0.0.0/0"
                        }
                    ],
                    "UserIdGroupPairs": [],
                    "FromPort": 80
                },
                {
                    "ToPort": 443,
                    "IpProtocol": "tcp",
                    "IpRanges": [
                        {
                            "CidrIp": "0.0.0.0/0"
                        }
                    ],
                    "UserIdGroupPairs": [],
                    "FromPort": 443
                }
            ],
            "GroupName": "MySecurityGroup",
            "VpcId": "vpc-00000xx0",
            "OwnerId": "111100003842",
            "GroupId": "sg-000aa000"
        },
        {
            "IpPermissionsEgress": [
                {
                    "IpProtocol": "-1",
                    "IpRanges": [
                        {
                            "CidrIp": "0.0.0.0/0"
                        }
                    ],
                    "UserIdGroupPairs": []
                }
            ],
            "Description": "default VPC security group",
            "IpPermissions": [
                {
                    "IpProtocol": "-1",
                    "IpRanges": [],
                    "UserIdGroupPairs": [
                        {
                            "UserId": "111100003842",
                            "GroupId": "sg-fe0ee89b"
                        }
                    ]
                }
            ],
            "GroupName": "default",
            "VpcId": "vpc-00000xx0",
            "OwnerId": "111100003842",
            "GroupId": "sg-fe0ee89b"
        }
    ]
}
}

Step 3: Launch an Instance into Your VPC

http://docs.aws.amazon.com/AmazonVPC/latest/GettingStartedGuide/LaunchInstance.html

VPC 内でインスタンスを起動させる。

まずは、EC2 インスタンスに SSH でログインするための公開鍵を登録

鍵の登録

$ aws ec2 import-key-pair --key-name amzn-linux --public-key-material file://id_rsa.pub
{
    "KeyName": "amzn-linux",
    "KeyFingerprint": "d8:d6:79:0f:18:9b:c9:db:62:05:1b:65:bc:ab:63:03"
}

インスタンスの起動

コマンド

VPC 内にマイクロインスタンス(–instance-type t1.micro)を起動させる。
起動時に Step1 で作成した public subnet や、Step 2 で作成したセキュリティグループを指定する。
–no-associate-public-ip-address オプションをつけると、public IP アドレスは付与されない。(逆に付与したい場合は –associate-public-ip-address とする。こうすればStep4の EIP操作は不要。)

$ aws ec2 run-instances --image-id ami-a1bec3a0 --count 1 --instance-type t1.micro --key-name amzn-linux --security-group-ids sg-000aa000 --subnet-id subnet-0a00000a --private-ip-address 10.5.0.11 --no-associate-public-ip-address
{
    "OwnerId": "111100003842",
    "ReservationId": "r-8ffbc989",
    "Groups": [],
    "Instances": [
        {
            "Monitoring": {
                "State": "disabled"
            },
            "PublicDnsName": null,
            "KernelId": "aki-176bf516",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "EbsOptimized": false,
            "LaunchTime": "2014-03-29T14:27:57.000Z",
            "PrivateIpAddress": "10.5.0.11",
            "ProductCodes": [],
            "VpcId": "vpc-00000xx0",
            "StateTransitionReason": null,
            "InstanceId": "i-00aaa000",
            "ImageId": "ami-a1bec3a0",
            "PrivateDnsName": "ip-10-5-0-11.ap-northeast-1.compute.internal",
            "KeyName": "amzn-linux",
            "SecurityGroups": [
                {
                    "GroupName": "MySecurityGroup",
                    "GroupId": "sg-000aa000"
                }
            ],
            "ClientToken": null,
            "SubnetId": "subnet-0a00000a",
            "InstanceType": "t1.micro",
            "NetworkInterfaces": [
                {
                    "Status": "in-use",
                    "SourceDestCheck": true,
                    "VpcId": "vpc-00000xx0",
                    "Description": null,
                    "NetworkInterfaceId": "eni-27747761",
                    "PrivateIpAddresses": [
                        {
                            "Primary": true,
                            "PrivateIpAddress": "10.5.0.11"
                        }
                    ],
                    "Attachment": {
                        "Status": "attaching",
                        "DeviceIndex": 0,
                        "DeleteOnTermination": true,
                        "AttachmentId": "eni-attach-e8c3a6ee",
                        "AttachTime": "2014-03-29T14:27:57.000Z"
                    },
                    "Groups": [
                        {
                            "GroupName": "MySecurityGroup",
                            "GroupId": "sg-000aa000"
                        }
                    ],
                    "SubnetId": "subnet-0a00000a",
                    "OwnerId": "111100003842",
                    "PrivateIpAddress": "10.5.0.11"
                }
            ],
            "SourceDestCheck": true,
            "Placement": {
                "Tenancy": "default",
                "GroupName": null,
                "AvailabilityZone": "ap-northeast-1c"
            },
            "Hypervisor": "xen",
            "BlockDeviceMappings": [],
            "Architecture": "x86_64",
            "StateReason": {
                "Message": "pending",
                "Code": "pending"
            },
            "RootDeviceName": "/dev/sda1",
            "VirtualizationType": "paravirtual",
            "RootDeviceType": "ebs",
            "AmiLaunchIndex": 0
        }
    ]
}

Step 4: Assign an Elastic IP Address to Your Instance

http://docs.aws.amazon.com/AmazonVPC/latest/GettingStartedGuide/EIP.html

作成したインスタンスにインターネットからアクセスできるように、Elastic IP をとって、インスタンスに紐付ける

Elastic IP 設定

コマンド

EC2 Classic ではないので --domain vpc オプションをつける。

$ aws ec2 allocate-address --domain vpc
{
    "PublicIp": "1.2.3.4",
    "Domain": "vpc",
    "AllocationId": "eipalloc-aaa0a00a"
}

$ aws ec2 associate-address --instance-id i-00aaa000 --allocation-id eipalloc-aaa0a00a
{
    "AssociationId": "eipassoc-5ea6483b",
    "return": "true"
}

$ aws ec2 describe-addresses
{
    "Addresses": [
        {
            "Domain": "vpc",
            "InstanceId": "i-00aaa000",
            "NetworkInterfaceId": "eni-27747761",
            "AssociationId": "eipassoc-5ea6483b",
            "NetworkInterfaceOwnerId": "111100003842",
            "PublicIp": "1.2.3.4",
            "AllocationId": "eipalloc-aaa0a00a",
            "PrivateIpAddress": "10.5.0.11"
        }
    ]
}

VPC 内のインスタンスに SSH で接続

$ ssh -i ~/.ssh/id_rsa ec2-user@1.2.3.4
The authenticity of host '1.2.3.4 (1.2.3.4)' can't be established.
ECDSA key fingerprint is 6e:83:02:a4:ed:33:68:a3:bf:33:93:02:c5:78:1d:94.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '1.2.3.4' (ECDSA) to the list of known hosts.
Last login: Sat Mar 29 14:32:53 2014 from aaa.bbb.ccc.ddd.jp

       __|  __|_  )
       _|  (     /   Amazon Linux AMI
      ___|\___|___|

https://aws.amazon.com/amazon-linux-ami/2014.03-release-notes/
[ec2-user@ip-10-5-0-10 ~]$

MEMO

VPC を CLI だけで構築することはまずないだろうけど(ID 管理が超面倒)、ピンポイントで設定の確認や変更をするために簡単な CLI 操作は覚えておいても損は無いかも。

Advertisements
Tagged with: , ,
Posted in aws

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 )

Google+ photo

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

Connecting to %s

Archives
  • RT @__apf__: How to write a research paper: a guide for software engineers & practitioners. docs.google.com/presentation/d… /cc @inwyrd 4 months ago
  • RT @HayatoChiba: 昔、自然と対話しながら数学に打ち込んだら何かを悟れるのではと思いたち、専門書1つだけ持ってパワースポットで名高い奈良の山奥に1週間籠ったことがある。しかし泊まった民宿にドカベンが全巻揃っていたため、水島新司と対話しただけで1週間過ぎた。 それ… 5 months ago
  • RT @googlecloud: Ever wonder what underwater fiber optic internet cables look like? Look no further than this deep dive w/ @NatAndLo: https… 5 months ago
  • @ijin UTC+01:00 な時間帯で生活しています、、、 10 months ago
  • RT @mattcutts: Google's world-class Site Reliability Engineering team wrote a new book: amazon.com/Site-Reliabili… It's about managing produc… 1 year ago
%d bloggers like this: