LoginSignup
0
0

More than 5 years have passed since last update.

[JAWS-UG CLI] EC2:#4 インスタンス起動 (CodeDeploy Agent)

Last updated at Posted at 2016-10-10

AWS CLIを利用して、EC2を起動し、CodeDeploy Agentをインストールします。

前提条件

EC2への権限

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

AWS CLIのバージョン

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

  • AWS CLI 1.11.2
コマンド
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が存在すること。

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

0. 準備

0.1. 変数の確認

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

コマンド
aws configure list
結果(例)

               Name                    Value             Type    Location
               ----                    -----             ----    --------
            profile         iamFull-prjZ-mbp13        env    AWS_DEFAULT_PROFILE
         access_key     ****************XXXX shared-credentials-file
         secret_key     ****************XXXX shared-credentials-file
             region                         us-east-1  env    AWS_DEFAULT_REGION

AssumeRoleを利用している場合はprofileが ''と表示されます。それ以外のときにprofileが '' と表示される場合は、以下を実行してください。

変数の設定
export AWS_DEFAULT_PROFILE=<IAMユーザ名>

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

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

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

0.3. キーペアの確認

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

コマンド
aws ec2 describe-key-pairs \
        --query 'KeyPairs[].KeyName'

キーペアが存在しない場合は、http://qiita.com/tcsh/items/59303d9506ca7d13f744 を実施してください。

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

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

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

変数の設定
FILE_SSH_KEY=<秘密鍵ファイルの位置>

1. 事前作業

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

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

1.2. イメージIDの決定

AmazonLinuxの最新AMIを選択します。

変数の設定
AMZLINUX_VERSION='2016.03.3'
      EC2_IMAGE_NAME="amzn-ami-hvm-${AMZLINUX_VERSION}.x86_64-gp2"
コマンド
EC2_IMAGE_ID=$( \
        aws ec2 describe-images \
          --filters Name=name,Values="${EC2_IMAGE_NAME}" \
          --query 'Images[].ImageId' --output text \
      ) \
        && echo ${EC2_IMAGE_ID}
結果(例)
      ami-6869aa05

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

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

コマンド
aws ec2 describe-security-groups \
        --query 'SecurityGroups[].GroupName'

HTTP/HTTPS

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

変数の設定
VPC_SG_NAME='ec2-http-https-global-inbound'

セキュリティグループのIDを取得します。

コマンド
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}

SSH

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

変数の設定
VPC_SG_NAME='ec2-ssh-global-inbound'

セキュリティグループのIDを取得します。

コマンド
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}

User Data

変数の設定
FILE_EC2_USERDATA='userdata.bash'
コマンド
cat << EOF > ${FILE_EC2_USERDATA}
#!/bin/bash
yum -y update
yum install -y ruby
yum install -y wget
cd /home/ec2-user
wget https://aws-codedeploy-${AWS_DEFAULT_REGION}.s3.amazonaws.com/latest/install
chmod +x ./install
./install auto
EOF

cat ${FILE_EC2_USERDATA}

2. インスタンス起動

2.1. インスタンス起動

変数の確認
cat << ETX

        EC2_IMAGE_ID:       ${EC2_IMAGE_ID}
        EC2_INSTANCE_TYPE:  ${EC2_INSTANCE_TYPE}
        ARRAY_VPC_SG_ID:   "${ARRAY_VPC_SG_ID}"
        EC2_KEY_NAME:       ${EC2_KEY_NAME}
        IAM_INSTANCE_PROFILE_NAME: ${IAM_INSTANCE_PROFILE_NAME}
        FILE_EC2_USERDATA:      ${FILE_EC2_USERDATA}

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_NAME} \
        --associate-public-ip-address \
        --iam-instance-profile Name=${IAM_INSTANCE_PROFILE_NAME} \
        --user-data file://${FILE_EC2_USERDATA}
結果(例)
      {
        "OwnerId": "XXXXXXXXXXXX",
        "ReservationId": "r-xxxxxxxx",
        "Groups": [],
        "Instances": [
          {
              "Monitoring": {
                  "State": "disabled"
              },
              "PublicDnsName": "",
              "RootDeviceType": "ebs",
              "State": {
                  "Code": 0,
                  "Name": "pending"
              },
              "EbsOptimized": false,
              "LaunchTime": "\ |today|\ T01:23:45.000Z",
              "PrivateIpAddress": "172.31.xx.xx",
              "ProductCodes": [],
              "VpcId": "vpc-xxxxxxxx",
              "StateTransitionReason": "",
              "InstanceId": "i-xxxxxxxx",
              "ImageId": "ami-6869aa05",
              "PrivateDnsName": "ip-172-31-xx-xx.ec2.internal",
              "KeyName": "prjz-us-east-1-ec2",
              "SecurityGroups": [
                  {
                      "GroupName": "ec2-ssh-global-inbound",
                      "GroupId": "sg-xxxxxxxx"
                  },
                  {
                      "GroupName": "ec2-http-https-global-inbound",
                      "GroupId": "sg-xxxxxxxx"
                  }
              ],
              "ClientToken": "",
              "SubnetId": "subnet-xxxxxxxx",
              "InstanceType": "t2.micro",
              "NetworkInterfaces": [
                  {
                      "Status": "in-use",
                      "MacAddress": "12:29:25:xx:xx:xx",
                      "SourceDestCheck": true,
                      "VpcId": "vpc-xxxxxxxx",
                      "Description": "",
                      "NetworkInterfaceId": "eni-xxxxxxxx",
                      "PrivateIpAddresses": [
                          {
                              "PrivateDnsName": "ip-172-31-xx-xx.ec2.internal",
                              "Primary": true,
                              "PrivateIpAddress": "172.31.xx.xx"
                          }
                      ],
                      "PrivateDnsName": "ip-172-31-xx-xx.ec2.internal",
                      "Attachment": {
                          "Status": "attaching",
                          "DeviceIndex": 0,
                          "DeleteOnTermination": true,
                          "AttachmentId": "eni-attach-xxxxxxxx",
                          "AttachTime": "\ |today|\ T01:23:45.000Z"
                      },
                      "Groups": [
                          {
                              "GroupName": "ec2-ssh-global-inbound",
                              "GroupId": "sg-xxxxxxxx"
                          },
                          {
                              "GroupName": "ec2-http-https-global-inbound",
                              "GroupId": "sg-xxxxxxxx"
                          }
                      ],
                      "SubnetId": "subnet-xxxxxxxx",
                      "OwnerId": "XXXXXXXXXXXX",
                      "PrivateIpAddress": "172.31.49.75"
                  }
              ],
              "SourceDestCheck": true,
              "Placement": {
                  "Tenancy": "default",
                  "GroupName": "",
                  "AvailabilityZone": "us-east-1d"
              },
              "Hypervisor": "xen",
              "BlockDeviceMappings": [],
              "Architecture": "x86_64",
              "StateReason": {
                  "Message": "pending",
                  "Code": "pending"
              },
              "IamInstanceProfile": {
                  "Id": "AIPAXXXXXXXXXXXXXXXXX",
                  "Arn": "arn:aws:iam::XXXXXXXXXXXX:instance-profile/\ |IAM_INSTANCE_PROFILE_NAME|\ S3ReadOnlyAccess"
              },
              "RootDeviceName": "/dev/xvda",
              "VirtualizationType": "hvm",
              "AmiLaunchIndex": 0
          }
        ]
      }

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

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

起動中の場合

コマンド(起動中の場合)
EC2_INSTANCE_ID=$( \
        aws ec2 describe-instances \
          --filters Name=instance-state-name,Values=pending \
          --query 'Reservations[].Instances[].InstanceId' \
          --output text \
) \
        && echo ${EC2_INSTANCE_ID}
結果(例)
      i-xxxxxxxx

起動完了後の場合

コマンド(起動完了後の場合)
ARRAY_EC2_INSTANCE_ID=$( \
        aws ec2 describe-instances \
          --filters Name=instance-state-name,Values=running \
          --query 'Reservations[].Instances[].InstanceId' \
          --output text \
) \
        && echo ${ARRAY_EC2_INSTANCE_ID}
変数の設定
EC2_INSTANCE_ID=$( \
        echo ${ARRAY_EC2_INSTANCE_ID} | sed 's/ .*$//' \
) \
        && echo ${EC2_INSTANCE_ID}
結果(例)
      i-xxxxxxxx

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

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

3. インスタンスの確認

3.1. パブリック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

後ほどデプロイしたWebアプリにアクセスするので、ブラウザで上記のIPアドレスにアクセスして開いておいてください。

3.2. SSHログイン

変数の確認
cat << ETX

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

ETX
コマンド
ssh -i ${FILE_SSH_KEY} ec2-user@${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
結果(例)
      Warning: Permanently added '54.xxx.xxx.xxx' (RSA) to the list of known hosts.

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

      https://aws.amazon.com/amazon-linux-ami/2015.03-release-notes/
      24 package(s) needed for security, out of 53 available
      Run "sudo yum update" to apply all updates.

3.3. codedeplocy agent

コマンド
sudo service codedeploy-agent status
結果
      The AWS CodeDeploy agent is running as PID xxxx

3.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

3.5. インスタンスからログアウト

コマンド(EC2インスタンス)
logout
結果(例)
      Connection to xxx.xxx.xxx.xxx closed.

9. 事後作業

タグ

コマンド
aws ec2 describe-tags 
結果(例)
      {
        "Tags": []
      }
変数の設定
EC2_TAG_KEY='Name'
      EC2_TAG_VALUE='MyCodePipelineDemo'
変数の確認
cat << ETX

        EC2_TAG_KEY:   ${EC2_TAG_KEY}
        EC2_TAG_VALUE: ${EC2_TAG_VALUE}

ETX
コマンド
aws ec2 create-tags \
        --resources ${EC2_INSTANCE_ID} \
        --tags "Key=${EC2_TAG_KEY},Value=${EC2_TAG_VALUE}"
結果(例)
      (戻り値なし)
コマンド
aws ec2 describe-tags \
        --query "Tags[?Key == \`${EC2_TAG_KEY}\`]"
結果(例)
      [
        {
          "ResourceType": "instance",
          "ResourceId": "i-23927713",
          "Value": "MyCodePipelineDemo",
          "Key": "Name"
        }
      ]

完了

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