How to change an Elastic IP in ec2

2.1k views Asked by At

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()
2

There are 2 answers

0
helloV On BEST ANSWER

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)
0
chrisweb On

I found an answer in the AWS Knowledge Center that says that you can do it via their web console or the command line: https://repost.aws/knowledge-center/ec2-move-elastic-ip

Use the EC2 console:

  1. Open the Amazon EC2 console, then select Elastic IPs.

  2. Choose the Elastic IP address that you want to transfer.

  3. Verify the Association ID and Associated instance ID to confirm which instance the Elastic IP address is currently associated with.

  4. Select Actions, Disassociate Elastic IP address.

  5. Select Disassociate.

  6. Select the Elastic IP address again, and then select Actions, Associate Elastic IP address.

  7. Select Instance and then search for the Instance ID of the instance that you want to associate the Elastic IP address with.

Note: If you have multiple network interfaces on the EC2 instance, then do the following:

Select Network Interface.

Choose the Elastic Network Interface ID that you want to associate the Elastic IP address with.

  1. Select Associate.