0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

EC2設定の詳しい解説

Posted at
  1. 鍵ペアの作成とダウンロード
 aws ec2 create-key-pair \  
  --key-name my-key-pair \  
  --key-type rsa \
  --key-format pem \
  --query "KeyMaterial" \
  --output text > ~/.ssh/my-key-pair.pem

aws ec2 create-key-pairを入力
--key-name my-key-pair # ← ここだけ自分で変えてOK(任意のキーペア名)
キーを設定したらダウンロードすることを忘れずに
/home/cloudshell-user/my-key-pair.pemこれで自分のPCに保存する。

2.AMIの設定

AMI_ID=$(aws ec2 describe-images --owners amazon \
     --filters 'Name=name,Values=amzn2-ami-hvm-2.0.*-gp2' 'Name=state,Values=available' \
     --query 'reverse(sort_by(Images, &CreationDate))[:1].ImageId' \
     --output text \
     --region ap-northeast-1)

このコードでAMIを取得する。

echo $AMI_ID

このコードで取得したAMIの確認が可能

3.EC2を作成

INSTANCE_ID=$(
  aws ec2 run-instances \
    --image-id $AMI_ID \
    --count 1 \
    --instance-type t2.micro \
    --key-name my-key-pair \
    --region ap-northeast-1 \
    --query "Instances[0].InstanceId" \
    --output text
)

このコマンドではインスタンス作成時にAMIの指定・インスタンスタイプの指定・キーペアの紐付け・リージョンの指定を行っています。

4.起動したEC2インスタンスの情報を取得

aws ec2 describe-instances \
  --instance-ids $INSTANCE_ID \
  --region ap-northeast-1

さきほど作成した「EC2インスタンス」には、インターネット上の住所にあたるIPアドレスが作成時に自動で割り振られている。
しかし、サーバーを再起動させるたびにこのパブリックIPという住所が変わるという欠点を持っている。
パブリックIPで起こる現象として以下のことが挙げられます。

IPに関する設定を都度変更する必要がある
ユーザーが以前のIPに接続できなくなる

これを解決してくれるのが「Elastic IP(EIP)」です。EIPはAWSから割り振られた固定の「パブリックIPアドレス」のことでした。このパブリックIPアドレスをEC2インスタンスに紐付けることで、インスタンスの起動・停止にかかわらず常に同じIPアドレスで通信をすることが可能になります。
なので次は変動しないEIPの設定をする必要がある。

5.EIPの設定

ALLOCATION_ID=$(aws ec2 allocate-address \
  --region ap-northeast-1 \
  --query 'AllocationId' \
  --output text)

次に、作成されたElastic IPアドレスの情報を見る。

aws ec2 describe-addresses \
--allocation-ids $ALLOCATION_ID \
--region ap-northeast-1
  "Addresses": [
      {
          "PublicIp": "11.111.111.21",
          "AllocationId": "eipalloc-07baaeb44893675bb",
          "Domain": "vpc",
          "PublicIpv4Pool": "amazon",
          "NetworkBorderGroup": "ap-northeast-1"
      }
  ]
}

これは出力結果の例だがこの"PublicIP"にあたる部分がEIPである。

6.EC2インスタンスとElastic IPを紐付けます。

aws ec2 associate-address \
  --instance-id $INSTANCE_ID \
  --allocation-id $ALLOCATION_ID \
  --region ap-northeast-1

ここまででEC2の簡単な初期設定は一通り完成。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?