Ng Sek Long
Ng Sek Long

Reputation: 4786

AWS EC2 getting a new dynamic IP without shutting down and start back up

I am testing a component that required changing the IP address for every test.

Using EC2, I can perform the following actions to change my IP:

  1. Shutdown the VM
  2. Start up the VM
  3. New IP obtained

While that work wonderfully, I need to wait 3 mins for it so shutdown and start back up for each test, which become quite troublesome overtime.

Would like to ask if there is anyway to, click a button / execute a script and obtain a new IP instantly? Thanks.

Upvotes: 0

Views: 742

Answers (1)

shimo
shimo

Reputation: 2285

When you use Elastic IP address (EIP), you can allocate new IP addresses faster than stopping and starting the EC2 inctance.

Here is a snippet with Python boto3 for checking IP addresses are changed.

Prerequisite

  • boto3
  • EC2 instance (InstanceID)
  • No EIP in the region

Code

import boto3
from botocore.exceptions import ClientError


def check_eip():
    ec2 = boto3.client("ec2")
    res_describe = ec2.describe_addresses()

    if res_describe["Addresses"]:
        return res_describe["Addresses"][0]["PublicIp"]
    else:
        return "NO EIP"

InstanceID = "i-xxxxxxxxxxxxxxxxx"

ec2 = boto3.client("ec2")

try:
    print("Step0: ", check_eip())

    allocation = ec2.allocate_address(Domain="vpc")
    print("Step1: ", check_eip())

    response = ec2.associate_address(
        AllocationId=allocation["AllocationId"], InstanceId=InstanceID
    )
    print("Step2: ", check_eip())

    # Do something here with the new EIP

    response2 = ec2.disassociate_address(
        AssociationId=response["AssociationId"])
    print("Step3: ", check_eip())

    response3 = ec2.release_address(AllocationId=allocation["AllocationId"])
    print("Step4: ", check_eip())

except ClientError as e:
    print(e)

Output

The output will be like this:

Step0:  NO EIP
Step1:  aaa.bbb.ccc.ddd
Step2:  aaa.bbb.ccc.ddd
Step3:  aaa.bbb.ccc.ddd
Step4:  NO EIP
  • It takes several seconds to run one sequence.
  • Whey you run the code again, EIP will be changed.

Note

Please make sure to release unused EIP.

$0.005 per Elastic IP address not associated with a running instance per hour on a pro rata basis

Upvotes: 1

Related Questions