Today I have face a problem . We want to have all time same ip on our instances because of some rules on a firewall. So how to add automatically elastic ip on a ec2 instance when start automaticaly by load balancer ?
Well this is not possible to be done automaticaly using amazon, so we have to wrote a bash script to be run on start up.
Here is the script:
#!/bin/bash
date
export EC2_HOME=/opt/aws/apitools/ec2-1.4.4.2
export JAVA_HOME=/usr/lib/jvm/jre
export CLASSPATH=${EC2_HOME}/lib
export EC2_PRIVATE_KEY=/root/pk.pem
export EC2_CERT=/root/cert.pem
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/aws/bin:/root/bin
ip=`/opt/aws/bin/ec2-describe-addresses -K /root/pk.pem -C /root/cert.pem |grep -v i-|head -1|awk {'print $2'}`
host=`hostname`
instance=`/opt/aws/bin/ec2-describe-instances -K /root/pk.pem -C /root/cert.pem | grep $host |awk {'print $2'}`
runmore=`/opt/aws/bin/ec2-describe-addresses -K /root/pk.pem -C /root/cert.pem|grep $instance`
if [[ $runmore == '' ]];then
if [[ $ip != '' ]];then
/opt/aws/bin/ec2-associate-address -K /root/pk.pem -C /root/cert.pem -i $instance $ip
fi
fi
Now all you have to do is to add this script on /etc/rc.d/rc.local to be run on startup . If your instance have a elastic ip asigned will not do anything, else will assing first free elastic ip.