Created
December 25, 2022 16:16
-
-
Save Burekasim/4d189547a75b92a392f37b9a5c11866c to your computer and use it in GitHub Desktop.
associate elastic ip for ec2 instances
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python36 | |
import boto3 | |
import requests | |
import os | |
def ec2_associate_eip(aws_instance, region_name, tag_name, tag_value): | |
client = boto3.client('ec2', region_name=region_name) | |
eip_list = client.describe_addresses(Filters=[{'Name': f'tag:{tag_name}', 'Values': [tag_value]}]) | |
free_eips = [] | |
if 'Addresses' in eip_list: | |
for eip_list in eip_list['Addresses']: | |
if 'InstanceId' in eip_list: | |
if eip_list['InstanceId']: | |
continue | |
free_eips.append(eip_list['PublicIp']) | |
else: | |
print('Could not retrieve elastic ip list') | |
exit(0) | |
if free_eips: | |
associate_eip = client.associate_address(PublicIp=free_eips[0], InstanceId=aws_instance) | |
if associate_eip['AssociationId']: | |
return 'EIP {} associated to {}'.format(free_eips[0], aws_instance) | |
else: | |
return 'Could not associate elastic ip' | |
else: | |
return 'Could not retrieve elastic ip' | |
def ec2_metadata(param): | |
try: | |
response = requests.get(f'http://169.254.169.254/latest/meta-data/{param}') | |
if response.ok: | |
return response.text | |
else: | |
return '' | |
except Exception as e: | |
print(str(e)) | |
return '' | |
if __name__ == '__main__': | |
eip_tag_name = os.environ['EIP_TAG'] | |
eip_tag_value = os.environ['EIP_TAG_VALUE'] | |
instance_id = ec2_metadata('instance-id') | |
region = ec2_metadata('placement/availability-zone')[:-1] | |
if instance_id and region: | |
print(ec2_associate_eip(instance_id, region, eip_tag_name, eip_tag_value)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment