【結論】
事前準備
1)割り当て対象となるEIPを確保
省略
2)IAM Roleを作成
→下記内容のポリシーを作成、EC2インスタンスに適用されるロールにアタッチしておく
ポリシー名:AssociateAddress(例)
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"ec2:DescribeInstances",
"ec2:DescribeAddresses",
"ec2:AssociateAddress"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
3)以下の内容のshをAMIのもとになるインスタンスに作成
例)
/usr/local/bin/associate_eip.sh
#!/bin/bash -ex
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
echo BEGIN
INSTANCE_ID=`curl http://169.254.169.254/latest/meta-data/instance-id`
REGION=`curl http://169.254.169.254/latest/dynamic/instance-identity/document | grep region | awk -F\" '{print $4}'`
for ALLOC_ID in `aws ec2 describe-addresses --region=$REGION --filter "Name=domain,Values=vpc" --output text | grep -v eipassoc- | grep -v Name | awk '{print $2}'`
do
CMD="aws ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $ALLOC_ID --no-allow-reassociation --region=$REGION"
$CMD
STATUS=$?
if [ 0 = $STATUS ] ; then
exit 0
fi
done
→実行権限を付与(chmod +x associate_eip.sh)
4)ユーザーデータ経由で実行する
オートスケーリングのユーザーデータで
#!/bin/bash
export HOME=/root
/usr/local/bin/associate_eip.sh
とかやるとうまくいった。