LoginSignup
0
0

More than 5 years have passed since last update.

[JAWS-UG CLI] EC2:#6 インスタンスの起動 (VyOS Oregon)

Last updated at Posted at 2016-10-23

前提条件

EC2への権限

EC2に対してフル権限があること。

AWS CLIのバージョン

以下のバージョンで動作確認済

  • AWS CLI 1.10.58
コマンド
aws --version
結果(例)
      aws-cli/1.11.2 Python/2.7.11 Darwin/15.6.0 botocore/1.4.60

バージョンが古い場合は最新版に更新しましょう。

コマンド
sudo -H pip install -U awscli

AWSアカウントの属性

AWSアカウントがEC2-Classicに対応していないこと。

コマンド
AWS_SUPPORT_PLATFORMS=$( \
         aws ec2 describe-account-attributes \
           --query 'AccountAttributes[?AttributeName == `supported-platforms`].AttributeValues[].AttributeValue' \
           --output text \
) && echo ${AWS_SUPPORT_PLATFORMS}
結果
      VPC

'VPC'の他に'EC2'が表示される場合、別のアカウントを作成もしくは利用してください。

デフォルトVPCの存在

デフォルトVPCが存在すること。

0. 準備

0.1. リージョンの決定

変数の設定
AWS_DEFAULT_REGION='us-west-2'

0.2. 変数の確認:

プロファイルが想定のものになっていることを確認します。

変数の確認
aws configure list
結果(例)
            Name                    Value             Type    Location
            ----                    -----             ----    --------
         profile       ec2full-prjZ-mbp13        env    AWS_DEFAULT_PROFILE
      access_key     ****************XXXX shared-credentials-file
      secret_key     ****************XXXX shared-credentials-file
          region        us-west-2        env    AWS_DEFAULT_REGION

0.3. デフォルトVPCのVPC ID取得

コマンド
VPC_ID=$( \
        aws ec2 describe-vpcs \
          --filters Name=isDefault,Values=true \
          --query 'Vpcs[].VpcId' \
          --output text \
) \
        && echo ${VPC_ID}
結果(例)
      vpc-xxxxxxxx

1. 事前作業

1.1. サブネット、プライベートアドレスの決定

コマンド
aws ec2 describe-subnets \
        --filters Name=vpcId,Values=${VPC_ID} \
        --query 'Subnets[].{SubnetId:SubnetId,CidrBlock:CidrBlock,AvailabilityZone:AvailabilityZone}' \
        --output text
結果(例)
      us-west-2a 172.31.32.0/20 subnet-xxxxxxxx
      us-west-2b 172.31.16.0/20 subnet-xxxxxxxx
      us-west-2c 172.31.0.0/20  subnet-xxxxxxxx

インスタンスを起動するサブネットIDを指定します。

変数の設定
VPC_SUBNET_ID='<インスタンスを起動するサブネットのSubnetID(例: subnet-xxxxxxxx)>'

選択したサブネットのアドレス範囲内で、起動するインスタンスのプライベートIPアドレスを指定します。

変数の設定
EC2_PRIVATE_ADDR='<起動するインスタンスのプライベートIPアドレス(例: 172.xx.xxx.xxx)>'

1.1. セキュリティグループの決定

まず、セキュリティグループの一覧を確認します。

コマンド
aws ec2 describe-security-groups \
        --query 'SecurityGroups[].GroupName'
結果(例)
      [
        "default",
        "ec2-ssh-global-inbound"
      ]

利用するセキュリティグループ名を指定します。

変数の設定
VPC_SG_NAME='ec2-ssh-global-inbound'
コマンド
VPC_SG_ID=$( \
        aws ec2 describe-security-groups \
          --filter Name=group-name,Values=${VPC_SG_NAME} \
          --query 'SecurityGroups[].GroupId' \
          --output text \
) \
        && echo ${VPC_SG_ID}
結果(例)
      sg-xxxxxxxx

セキュリティグループを配列に入れておきます。

変数の設定
ARRAY_VPC_SG_ID="${VPC_SG_ID} ${ARRAY_VPC_SG_ID}" \
        && echo ${ARRAY_VPC_SG_ID}

1.2. キーペアの指定

まず、キーペアの一覧を確認します。

コマンド
aws ec2 describe-key-pairs \
        --query 'KeyPairs[].KeyName'
結果(例)
      {
        "KeyPairs": [
          {
              "KeyName": "<キーペアー名>",
              "KeyFingerprint": "xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
          }
        ]
      }

利用するキーペア名を指定します。

変数の設定
EC2_KEY_PAIR_NAME='<キーペアー名>'

利用するキーペアの秘密鍵ファイルを指定します。

変数の設定
FILE_SSH_KEY="${HOME}/.ssh/<キーペア秘密鍵のファイル名>" \
        echo ${FILE_SSH_KEY}

秘密鍵が存在することを確認しましょう。

コマンド
ls ${FILE_SSH_KEY}

1.3. イメージIDの決定

AMIを選択します。

変数の設定
EC2_IMAGE_ID='ami-bd2e658d'
コマンド
aws ec2 describe-images \
        --image-ids ${EC2_IMAGE_ID}
結果(例)
      {
        "Images": [
          {
              "ProductCodes": [
                  {
                      "ProductCodeId": "6zm1fgja1q6n2b0ceez4mn974",
                      "ProductCodeType": "marketplace"
                  }
              ],
              "Name": "VyOS (HVM) 1.1.0-760e742d-5ec6-4d7b-b15c-2df9e3f3a450-ami-f4338f9c.2",
              "VirtualizationType": "hvm",
              "Hypervisor": "xen",
              "ImageOwnerAlias": "aws-marketplace",
              "SriovNetSupport": "simple",
              "ImageId": "ami-bd2e658d",
              "State": "available",
              "BlockDeviceMappings": [
                  {
                      "DeviceName": "/dev/xvda",
                      "Ebs": {
                          "DeleteOnTermination": true,
                          "SnapshotId": "snap-1af45a90",
                          "VolumeSize": 4,
                          "VolumeType": "standard",
                          "Encrypted": false
                      }
                  }
              ],
              "Architecture": "x86_64",
              "ImageLocation": "aws-marketplace/VyOS (HVM) 1.1.0-760e742d-5ec6-4d7b-b15c-2df9e3f3a450-ami-f4338f9c.2",
              "RootDeviceType": "ebs",
              "OwnerId": "679593333241",
              "RootDeviceName": "/dev/xvda",
              "CreationDate": "2014-11-07T23:01:36.000Z",
              "Public": true,
              "ImageType": "machine",
              "Description": "The VyOS AMI is an EBS-backed, HVM image. It is an open-source Linux-based network operating system that provides software-based network routing, firewall, and VPN functionality."
          }
        ]
      }

1.4. インスタンスタイプの決定

変数の設定
EC2_INSTANCE_TYPE='t2.micro'

1.5. 稼動インスタンスを確認

同一リージョンでインスタンスが起動していないことを確認します。

コマンド
EC2_INSTANCE_STATUS='running'
コマンド
aws ec2 describe-instances \
        --filters Name=instance-state-name,Values=${EC2_INSTANCE_STATUS}
結果
      {
          "Reservations": []
      }

2. インスタンス起動

2.1. インスタンス起動

変数の確認
cat << ETX

        EC2_IMAGE_ID:              ${EC2_IMAGE_ID}
        EC2_INSTANCE_TYPE:         ${EC2_INSTANCE_TYPE}
        EC2_KEY_PAIR_NAME:         ${EC2_KEY_PAIR_NAME}
        EC2_PRIVATE_ADDR:          ${EC2_PRIVATE_ADDR}
        ARRAY_VPC_SG_ID:           ${ARRAY_VPC_SG_ID}
        VPC_SUBNET_ID              ${VPC_SUBNET_ID}

ETX
コマンド
aws ec2 run-instances \
        --image-id ${EC2_IMAGE_ID} \
        --instance-type ${EC2_INSTANCE_TYPE} \
        --security-group-ids ${ARRAY_VPC_SG_ID} \
        --key-name ${EC2_KEY_PAIR_NAME} \
        --subnet-id ${VPC_SUBNET_ID} \
        --private-ip-address ${EC2_PRIVATE_ADDR} \
        --associate-public-ip-address 
結果(例)
      {
        "OwnerId": "XXXXXXXXXXXX",
        "ReservationId": "r-xxxxxxxx",
        "Groups": [],
        "Instances": [
          {
              "Monitoring": {
                  "State": "disabled"
              },
              "PublicDnsName": "",
              "RootDeviceType": "ebs",
              "State": {
                  "Code": 0,
                  "Name": "pending"
              },
              "EbsOptimized": false,
              "LaunchTime": "2016-10-21T01:23:45.000Z",
              "PrivateIpAddress": "172.31.32.33",
              "ProductCodes": [],
              "VpcId": "vpc-xxxxxxxx",
              "StateTransitionReason": "",
              "InstanceId": "i-xxxxxxxx",
              "ImageId": "ami-xxxxxxxx",
              "PrivateDnsName": "ip-xxx-xx-xx-xxx.us-west-2.compute.internal",
              "KeyName": "<キーペアー名>",
              "SecurityGroups": [
                  {
                      "GroupName": "ec2-ssh-global-inbound",
                      "GroupId": "sg-xxxxxxxx"
                  }
              ],
              "ClientToken": "",
              "SubnetId": "subnet-xxxxxxxx",
              "InstanceType": "t2.micro",
              "NetworkInterfaces": [
                  {
                      "Status": "in-use",
                      "MacAddress": "xx:xx:xx:xx:xx:xx",
                      "SourceDestCheck": true,
                      "VpcId": "vpc-xxxxxxxx",
                      "Description": "",
                      "NetworkInterfaceId": "eni-xxxxxxxx",
                      "PrivateIpAddresses": [
                          {
                              "PrivateDnsName": "ip-xxx-xx-xx-xxx.us-west-2.compute.internal",
                              "Primary": true,
                              "PrivateIpAddress": "172.31.32.33"
                          }
                      ],
                      "PrivateDnsName": "ip-xxx-xx-xx-xxx.us-west-2.compute.internal",
                      "Attachment": {
                          "Status": "attaching",
                          "DeviceIndex": 0,
                          "DeleteOnTermination": true,
                          "AttachmentId": "eni-attach-xxxxxxxx",
                          "AttachTime": "2016-10-21T01:23:45.000Z"
                      },
                      "Groups": [
                          {
                              "GroupName": "ec2-ssh-global-inbound",
                              "GroupId": "sg-xxxxxxxx"
                          }
                      ],
                      "SubnetId": "subnet-xxxxxxxx",
                      "OwnerId": "XXXXXXXXXXXX",
                      "PrivateIpAddress": "172.31.32.33"
                  }
              ],
              "SourceDestCheck": true,
              "Placement": {
                  "Tenancy": "default",
                  "GroupName": "",
                  "AvailabilityZone": "us-west-2a"
              },
              "Hypervisor": "xen",
              "BlockDeviceMappings": [],
              "Architecture": "x86_64",
              "StateReason": {
                  "Message": "pending",
                  "Code": "running"
              },
              "RootDeviceName": "/dev/xvda",
              "VirtualizationType": "hvm",
              "AmiLaunchIndex": 0
          }
        ]
      }
注釈
An error occurred (OptInRequired) when calling the RunInstances operation: In order to use this AWS Marketplace product you need to accept terms and subscribe. To do so please visit http://aws.amazon.com/marketplace/pp?sku=6zm1fgja1q6n2b0ceez4mn974

と表示される場合は、URLにブラウザでアクセスし、以下の操作をしてください。

 - Continue
 - Accept Software Terms & Launch with 1-Click
 - Return to Product Page

2.2. インスタンスIDの取得

起動中のインスタンスからインスタンスIDを取得します。

コマンド
EC2_INSTANCE_ID=$( \
        aws ec2 describe-instances \
          --filters Name=private-ip-address,Values=${EC2_PRIVATE_ADDR} \
          --query 'Reservations[].Instances[].InstanceId' \
          --output text \
) \
        && echo ${EC2_INSTANCE_ID}
結果(例)
      i-xxxxxxxx

3. 送信元/送信先チェックの無効化

3.1. 送信元/送信先チェックの確認

変数の設定
EC2_INSTANCE_ATTRIBUTE='sourceDestCheck'
コマンド
aws ec2 describe-instance-attribute \
        --instance-id ${EC2_INSTANCE_ID} \
        --attribute ${EC2_INSTANCE_ATTRIBUTE}
結果(例)
      {
        "InstanceId": "i-xxxxxxxx",
        "SourceDestCheck": {
          "Value": true
        }
      }

3.2. 送信元/送信先チェックの無効化

コマンド
aws ec2 modify-instance-attribute \
        --instance-id ${EC2_INSTANCE_ID} \
        --no-source-dest-check
結果(例)
      (戻り値なし)

3.3. 送信元/送信先チェックの確認

コマンド
aws ec2 describe-instance-attribute \
        --instance-id ${EC2_INSTANCE_ID} \
        --attribute ${EC2_INSTANCE_ATTRIBUTE}
結果(例)
      {
        "InstanceId": "i-xxxxxxxx",
        "SourceDestCheck": {
          "Value": false
        }
      }

4. EIPの付与

4.1. EIPの取得

コマンド
  aws ec2 allocate-address > eip.json \
    && cat eip.json

4.2. EIPのアドレス確認

コマンド
  cat eip.json \
    | jp.py 'PublicIp' \
    | sed 's/\"//g'

東京リージョンでカスタマゲートウェイ(VPNコネクション)を作成するときに必要になります。

4.3. アロケーションIDの取得

コマンド
VPC_ALLOCATION_ID=$( \
    cat eip.json \
    | jp.py 'AllocationId' \
    | sed 's/\"//g' \
) && echo ${VPC_ALLOCATION_ID}

4.4. インスタンスへの付与

コマンド
aws ec2 associate-address \
    --instance-id ${EC2_INSTANCE_ID} \
    --allocation-id ${VPC_ALLOCATION_ID}
結果(例)
  {
    "AssociationId": "eipassoc-xxxxxxxx"
  }

5. 事後作業

5.1 インスタンスのステータス確認

コマンド
EC2_INSTANCE_STATE=$( \
        aws ec2 describe-instances \
        --instance-ids ${EC2_INSTANCE_ID} \
        --query 'Reservations[].Instances[].State.Name' \
        --output text \
) \
        && echo ${EC2_INSTANCE_STATE}
結果(例)
      running

5.2. パブリックIPアドレスの取得

コマンド
EC2_PUBLIC_IP=$( \
        aws ec2 describe-instances \
          --instance-id ${EC2_INSTANCE_ID} \
          --query "Reservations[].Instances[].PublicIpAddress" \
          --output text \
) \
        && echo ${EC2_PUBLIC_IP}
結果(例)
      54.xxx.xxx.xxx

6. インスタンスへのログイン

6.2. SSHログイン

変数の確認
cat << ETX

        FILE_SSH_KEY:  ${FILE_SSH_KEY}
        EC2_PUBLIC_IP: ${EC2_PUBLIC_IP}

ETX
コマンド
ssh -i ${FILE_SSH_KEY} vyos@${EC2_PUBLIC_IP}
結果(例)
      The authenticity of host '54.xxx.xxx.xxx (54.xxx.xxx.xxx)' can't be established.
      RSA key fingerprint is xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx.
      Are you sure you want to continue connecting (yes/no)?
入力
      yes
結果(例)
      Welcome to VyOS
      Linux vyatta 3.13.11-1-amd64-vyos #1 SMP Wed Sep 3 20:04:22 UTC 2014 x86_64
      Welcome to VyOS.
      This system is open-source software. The exact distribution terms for
      each module comprising the full system are described in the individual
      files in /usr/share/doc/*/copyright.

6.3. バージョン確認

コマンド
show version
結果(例)
      Version:      VyOS 1.1.0
      Description:  VyOS 1.1.0 (helium)
      Copyright:    2014 VyOS maintainers and contributors
      Built by:     maintainers@vyos.net
      Built on:     Thu Oct  9 22:27:26 UTC 2014
      Build ID:     1410092227-af6433f
      System type:  x86 64-bit
      Boot via:     image
      Hypervisor:   Xen hvm
      HW model:     HVM domU
      HW S/N:       ec26c384-e9e4-fb0f-135c-3543be059925
      HW UUID:      EC26C384-E9E4-FB0F-135C-3543BE059925
      Uptime:       07:37:49 up 16 min,  1 user,  load average: 0.00, 0.01, 0.02

6.4. EC2メタ情報の確認

コマンド(EC2インスタンス)
echo -e "\n"   && curl http://169.254.169.254/latest/meta-data/public-hostname   && echo -e "\n"
結果(例)
      ec2-52-xxx-xxx-xxx.ap-northeast-1.compute.amazonaws.com

完了

0
0
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
0
0