Skip to content

Instantly share code, notes, and snippets.

@rodrigoSyscop
Created March 9, 2019 19:06
Show Gist options
  • Save rodrigoSyscop/7a7dec3ecdc688008418422f5221270b to your computer and use it in GitHub Desktop.
Save rodrigoSyscop/7a7dec3ecdc688008418422f5221270b to your computer and use it in GitHub Desktop.
Renew current EIP of an AWS EC2 Instance
import boto3
import urllib.request
from botocore.exceptions import ClientError
METADATA_URL = 'http://169.254.169.254/latest/meta-data'
instance_id = urllib.request.urlopen(METADATA_URL + '/instance-id').read().decode()
current_eip = urllib.request.urlopen(METADATA_URL + '/public-ipv4').read().decode()
try:
ec2 = boto3.client('ec2')
# Alocar um novo EIP
allocation = ec2.allocate_address(Domain='vpc')
new_eip = allocation['PublicIp']
print("Novo EIP alocado: %s" % (new_eip))
# Disassocia o EIP atual
response = ec2.describe_addresses(PublicIps=[current_eip])
allocation_id = response['Addresses'][0]['AllocationId']
association_id = response['Addresses'][0]['AssociationId']
response = ec2.disassociate_address(AssociationId=association_id)
# Liberar o EIP atual
response = ec2.release_address(AllocationId=allocation_id)
print("EIP antigo %s liberado" % (current_eip))
# Associar o novo EIP a instância corrente
response = ec2.associate_address(
AllocationId=allocation['AllocationId'],
InstanceId=instance_id)
print("EIP associado a instância %s." % (instance_id))
except ClientError as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment