日: 2018年8月2日

  • aws-cliでEC2を作成しEIPを付与

    aws-cliでEC2を作成しEIPを付与

    はじめに

    よく使うコマンドで、いつもはシェルでラップしているけど、ある部分だけ抜き出して実施したいこともある

    注意事項

    ある程度は環境変数にしてある。変更しやすいように

    手順

    接続するための鍵

    SSH_KEY_NAME=tsukada.pem

    マシン情報

    IMAGE_ID=ami-*****
    sequrity_group_id=sg-*****
    subnet=subnet-*****
    
    #インスタンスタイプを定義。以下はt2.smallを使うこととする
    instance_type=t2.small

     

    EC2作成

    サーバ作成

    aws ec2 run-instances --key-name ${SSH_KEY_NAME} --image-id ${IMAGE_ID} --count 1 --instance-type ${instance_type} --security-group-ids ${sequrity_group_id} --subnet-id ${subnet} > create-server.json

     

    インスタンスにタグ付け

    # 今回立ち上げたいインスタンスの名前を定義する。
    INSTANCE_NAME=tsukada-test01
    instance_id=`cat create-server.json | jq -r .Instances[].InstanceId`
    
    aws ec2 create-tags --resources $instance_id --tags Key=Name,Value=${INSTANCE_NAME}

    Elastic IP付与

    aws ec2 allocate-address --domain vpc > ElasticIP.json

    ElasticIP にタグ付け

    allocation_id=`cat ElasticIP.json| jq -r .AllocationId`
    EIP_name=tsukada-eip
    aws ec2 create-tags --resources ${allocation_id} --tags Key=Name,Value=${EIP_name}

    ElasticIPをEC2インスタンスに紐付け

    aws ec2 associate-address --allocation-id ${allocation_id} --instance ${instance_id}
    
    SERVERIP=`cat ElasticIP.json | jq -r .PublicIp`

    接続

    ssh ec2-user@ `cat ElasticIP.json | jq -r $SERVERIP`