Search code examples
amazon-web-servicesamazon-ec2botoboto3elastic-ip

How to change an Elastic IP in ec2


Is it possible to change the IP in ec2 using the server you are on?

What I currently do in the console is:

  1. Shutdown ec2
  2. Disassociate the Elastic IP address
  3. Release the Elastic IP address (so I can create a new one, otherwise, it says max IPs)
  4. Allocate a new Elastic IP address
  5. Start up ec2
  6. Associate the new Elastic IP address to ec2

But, I"m doing this in the console since the ec2 server is being shutdown. Is there a way to do this on the current server I'm using. For example, in pseudocode:

import ec2, boto
ec2.disappociate_current_ip()
ec2.release_ip()
ec2.allocate_new_ip()
ec2.associate_new_ip()

Solution

  • It is possible. BUT the moment you disassociate your elastic IP address, you may lose internet connectivity depending on your subnet settings. If your subnet is configured to allocate public IP automatically, you will get a public IP (not elastic IP) in between disassociate and associate. But if your public subnet is not configured to get a public IP automatically, your instance will lose internet connection (unless there is a route to reach internet) and the rest of your script will not execute. Following is a Boto3 script to give you an idea BUT UNTESTED. Tweak it to suit your needs.

    import boto3
    import requests
    
    client = boto3.client('ec2')
    inst_id = requests.get('http://169.254.169.254/latest/meta-data/instance-id').text
    print inst_id
    
    public_ip = requests.get('http://169.254.169.254/latest/meta-data/public-ipv4').text
    print 'Current IP:', public_ip
    print 'Disassociating:', public_ip
    client.disassociate_address(PublicIp=public_ip)
    
    public_ip = client.allocate_address( Domain='vpc')['PublicIp']
    print 'New IP:', public_ip
    print 'Associating:', public_ip
    client.associate_address(InstanceId=inst_id, PublicIp=public_ip)