AWS elastic IP subscription

I’m still not entirely convinced that AWS shouldn’t do this for us automatically, but here you go:

Manual method

Configure the desired Elastic IP by editing a script on the host

  1. Set up an IAM user
  2. Install the EC2 API tools
    • On Ubuntu, enable multiverse and install ec2-api-tools
  3. The command to associate an Elastic IP to a running EC2 instance is:
    • ec2-associate-address -i i-b2e019da –region eu-west-1

Automated method

This script reads the desired Elastic IP from a Tag called “elastic-ip” that you’ve set in the EC2 interface

# This script assigns an Elastic IP to Instance on Reboot or Restart
# It gets the desired Elastic IP from the user tag "elastic-ip" set within the AWS interface
# Because it gets its only setting from the user tags it is autonomous and needs no on-machine configuration
set -e

export EC2_PRIVATE_KEY='/etc/ec2/user.private.key.pem'
export EC2_CERT='/etc/ec2/user-cert.pem'

if [ ! -e $EC2_PRIVATE_KEY ]; then
  echo "EC2 private key $EC2_PRIVATE_KEY missing!" >&2
  exit 1
if [ ! -e $EC2_CERT ]; then
  echo "EC2 cert $EC2_CERT missing!" >&2
  exit 1

EC2_AVAILABILITY_ZONE=`ec2metadata --availability-zone`
EC2_REGION_ID=${EC2_AVAILABILITY_ZONE:0:${#EC2_AVAILABILITY_ZONE} - 1}  # lop the last character off the availability zone
EC2_INSTANCE_ID=`ec2metadata --instance-id`
EC2_PUBLIC_IP=`ec2metadata --public-ipv4`

echo "Looking up tag:elastic-ip for $EC2_INSTANCE_ID in $EC2_REGION_ID"
# see:
ELASTIC_IP=$(ec2-describe-tags \
  --region $EC2_REGION_ID \
  --filter "resource-type=instance" \
  --filter "resource-id=$EC2_INSTANCE_ID" \
  --filter "key=elastic-ip" | cut -f5)

if [ ! "$ELASTIC_IP" ]; then
  echo "Could not find elastic-ip tag in EC2 settings for this instance!" >&2
  exit 1
echo "elastic-ip tag: $ELASTIC_IP"

if [ "$ELASTIC_IP" == "$EC2_PUBLIC_IP" ]; then
  echo "Public IP of this server already matches"
  exit 0

echo "Assigning Elastic IP"
ec2-associate-address -i $EC2_INSTANCE_ID --region $EC2_REGION_ID $EC2_ELASTIC_IP
  • Install the script in /usr/local/bin
  • mark it executable
  • call it when your eth0 interface goes up
    • in ubuntu, add this line to /etc/network/interfaces:
      post-up /etc/network/if-up.d/

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: