Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?

More than 1 year has passed since last update.

@3104k

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

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/

1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What is going on with this article?