Automatically assign elastic IP to ec2 spot instance with user data script

Is it possible to automatically assign an Elastic IP address to a spot instance that has a persistent spot request using the 'Advanced' 'User Data' script box?

I'm thinking that I could craft a script like...

#!/bin/bash 

# Credentials
export AWS_ACCESS_KEY=(insert key here) 
export AWS_SECRET_KEY=(insert key here) 

# EC2 Instance ID
instanceid=`/usr/bin/curl -s http://169.254.169.254/latest/meta-data/instance-id` 

# Associate EIP with the captured instance ID.
ec2-associate-address -i $instanceid (insert EIP here)

And stick this in the user data box (using web gui) before I finalize my spot request. Any thoughts or better methods for this? I don't need to autoscale, just using this one instance that comes up and down depending on spot prices but I'd like it to retain the same IP each time it comes back.


Solution 1:

Recently, I also thought about automating the process of re-assigning an Elastic IP to my spot instance. After some Internet research, I have found several solid how-to resources on the topic:

  1. http://www.newvem.com/how-to-automate-elastic-ip-assignment-on-ec2-instance-restart-or-reboot
  2. http://www.idevelopment.info/data/AWS/AWS_Tips/AWS_Management/AWS_14.shtml
  3. https://boto.readthedocs.org/en/latest/ref/ec2.html (not exactly a HOWTO, but still might be useful).

Hope this helps!