4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWS ElasticBeanstalk環境でEC2立ち上がり時にEIPを自動で振り当てる

Last updated at Posted at 2019-03-14

ElasticBeanstalk環境でEC2インスタンスが立ち上がった時、EIPを自動で割り当てるスクリプトを作ってみました。

オートスケーリングでEC2インスタンスが増えた場合、PublicIPが自動で割り当てられますが、
サービスによっては外部連携していて、許可されたIPのみ疎通が許可されているなどあるかと思います。
ElasticBeanstalk環境では.ebextensionsディレクトリ配下にスクリプトを配置しておけば、EC2インスタンスが立ち上がったタイミングで実行されます。

files:
  "/opt/elasticbeanstalk/hooks/appdeploy/post/00_associate_eipalloc.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/usr/bin/env bash

      env=$(/opt/elasticbeanstalk/bin/get-config optionsettings -n aws:elasticbeanstalk:application:environment -o RACK_ENV)
      
      # プールしているEIPのAllocationIDを環境毎に用意
      if [ ${env} = "production" ]; then
        eipalloc_ids="eipalloc-aaaaaaaa eipalloc-bbbbbbbb eipalloc-cccccccc eipalloc-dddddddd"
      elif [ ${env} = "test" ]; then
        eipalloc_ids="eipalloc-xxxxxxxx eipalloc-yyyyyyyy"
      fi

      if [ -z ${eipalloc_ids} ]; then
        echo Not exist AllocationID in the ${env} environment
      else
        instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
        region=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e 's/.$//')

        export AWS_DEFAULT_REGION=${region}

        available_alloc_id=$(aws ec2 describe-addresses --allocation-ids ${eipalloc_ids} | jq -r '[.Addresses[] | select(.InstanceId == null)][0] | .AllocationId')
     
     echo available_alloc_id=${available_alloc_id}

        if [ ${available_allocid} = null ]; then
          echo "Already associated"
        else
          aws ec2 associate-address --instance-id ${instance_id} --allocation-id ${available_alloc_id}
        fi
      fi

参考
https://dev.classmethod.jp/cloud/aws/choose-eip-from-addresspool/

4
1
2

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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?