5
1

More than 1 year has passed since last update.

【AWS】 EC2インスタンスへElastic IP再紐付けの自動化

Last updated at Posted at 2023-08-28

Elastic BeanstalkのAmazon EC2インスタンスで動作するアプリケーションは、一部のサードパーティのAPIや外部サービスの制約により、承認された固定IPを使用する必要がある場合があります。このような場合、Elastic IPを使用すると、EC2インスタンスに直接静的IPを割り当てることができます。

しかし、Elastic Beanstalkの更新過程でEC2インスタンスが新しいインスタンスに置き換えられると、割り当てられたElastic IPが自動的に解除されるという問題が発生します。これにより、接続が切断されたり、動作が不安定になることがあります。この問題を解決する方法の一つは、既存のElastic IPを自動的に新しいEC2インスタンスに再割り当てすることです。

本ポストでは、単一インスタンスでこのような自動化された再割り当て方法について簡単に説明します。

プロセス

  1. Elastic IPの割り当てIDの取得: 使用したいElastic IPの割り当てIDをElastic Beanstalkの環境変数から取得します。
  2. 現在のEC2インスタンスIDの取得:次に、AWSの内部メタデータサービスを使用して、現在のEC2インスタンスIDを取得します。
  3. リージョン設定:AWSのリージョンをap-northeast-2に設定します。
  4. Elastic IPの再割り当て:Elastic IPがまだ該当のAmazon EC2インスタンスに割り当てられていない場合は、再割り当てを行います。

以下は、新しいEC2インスタンスにElastic IPを自動的に再割り当てするためのBashスクリプトです。

# platform/hooks/postdeploy/eip-to-ec2.sh
#!/bin/bash

# ELASTIC_IP_ALLOCATION_IDはElastic Beanstalkの環境変数
ALLOCATION_ID=$(/opt/elasticbeanstalk/bin/get-config environment -k ELASTIC_IP_ALLOCATION_ID)

CURRENT_INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)

echo "Setting region to ap-northeast-2"
aws configure set region ap-northeast-2

echo "Checking if Elastic IP with ALLOCATION_ID[$ALLOCATION_ID] is allocated to any EC2 instance"
ALLOCATED_INSTANCE_ID=$(aws ec2 describe-addresses --filters "Name=allocation-id, Values=$ALLOCATION_ID" --query Addresses[].InstanceId --output text)

if [ "$CURRENT_INSTANCE_ID" != "$ALLOCATED_INSTANCE_ID" ]; then
    echo "Running: aws ec2 associate-address --instance-id $CURRENT_INSTANCE_ID --allocation-id $ALLOCATION_ID --allow-reassociation"
    aws ec2 associate-address --instance-id $CURRENT_INSTANCE_ID --allocation-id $ALLOCATION_ID --allow-reassociation
else
    echo "CURRENT_INSTANCE_ID[$CURRENT_INSTANCE_ID] and ALLOCATED_INSTANCE_ID[$ALLOCATED_INSTANCE_ID] is the same instance. No need to reassign Elastic IP"
fi

このスクリプトを実装することで、アプリケーションが必要な固定IP設定を維持し、IP変更によるサービス中断の可能性を最小限に抑えることができます。

参考文献

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