CALL +44 (0)20 7183 3893
Blog

Monday 17 January 2011

Elastic IP on Boot - Not too Much of a Stretch

It is quite usual to have a EC2 instance with a tied Elastic IP you need to reboot/stop from time to time. Unfortunately for you every time you do so, the elastic IP association is lost, forcing you to manually reattaching it again.

There is however a very easy way to solve this problem, by just using a script at boot. Just like a normal Unix service.
/etc/ec2autoeip.conf (Config file sample)

AWS_ACCESS_KEY = 'xxxxxxxxxxxxxxxxxx'
AWS_SECRET_ACCESS_KEY = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy’'
IP = 'ww.xx.yy.zz'


/etc/init.d/ec2autoeip (The actual service script code)

#!/usr/bin/python
import sys
import urllib
import boto.ec2
execfile("/etc/ec2autoeip.conf")
instance_id = urllib.urlopen("http://169.254.169.254/latest/meta-data/instance-id").read()
zone = urllib.urlopen("http://169.254.169.254/latest/meta-data/placement/availability-zone").read()[:-1]
conn = boto.ec2.connect_to_region(zone,
aws_access_key_id = AWS_ACCESS_KEY,
aws_secret_access_key = AWS_SECRET_ACCESS_KEY,
is_secure = False)
if len(sys.argv) > 1 and sys.argv[1]=="start":
conn.associate_address(instance_id,IP)
print("Attaching " + IP + " to " + instance_id)
elif len(sys.argv) > 1 and sys.argv[1]=="stop":
conn.disassociate_address(IP)
print("Deattaching " + IP)


Finally is time to register the service to run at boot, in Debian and Ubuntu you can do it like that:

root@somewhere# update-rc.d ec2autoeip defaults


This script uses the awesome boto python library so you will need to install it in order for the script to work properly.


Emilio Garcia
Cloudreach Senior Engineer

No comments:

Post a Comment

Pontus is ready and waiting to answer your questions