AviKeinan

allocate pretty AWS EIP

Aug 17th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. import boto3
  2. from pprint import pprint
  3. from time import sleep
  4.  
  5. client = boto3.client('ec2')
  6.  
  7.  
  8. def tag_ip(eip_alloc_id, tag_value):
  9.     tag = client.create_tags(Resources=[eip_alloc_id, ], Tags=[{'Key': 'Name', 'Value': tag_value}, ])
  10.     if tag:
  11.         return True
  12.     else:
  13.         return False
  14.  
  15.  
  16. def release_ip(ip_release_alloc, ip):
  17.     for item in range(5):
  18.         try:
  19.             client.release_address(AllocationId=ip_release_alloc)
  20.             print(f'released ugly ip {ip}')
  21.             return True
  22.         except Exception as e:
  23.             print(str(e))
  24.             sleep(0.5)
  25.     return True
  26.  
  27.  
  28. def get_nice_ip():
  29.     response = client.allocate_address(Domain='vpc')
  30.     if response:
  31.         # print(response)
  32.         if 'PublicIp' in response:
  33.             ip = response['PublicIp']
  34.             alloc_id = response['AllocationId']
  35.             ip_split = ip.split('.')
  36.             if ip_split[2] == ip_split[3]:
  37.                 tag_ip(alloc_id, 'GOLD')
  38.                 print(f'found {ip}')
  39.             elif '00' in ip_split[2] and '00' in ip_split[3]:
  40.                 tag_ip(alloc_id, 'SILVER')
  41.                 print(f'found {ip}')
  42.             elif int(ip_split[3]) == 0:
  43.                 print(f'found {ip}')
  44.                 tag_ip(alloc_id, 'BRONZE MINUS')
  45.             elif int(ip_split[2]) + 1 == int(ip_split[3]) or int(ip_split[2]) - 1 == int(ip_split[3]) or int(
  46.                     ip_split[2]) - 1 == int(ip_split[3]) or int(ip_split[3]) - 1 == int(ip_split[2]):
  47.                 print(f'found {ip}')
  48.                 tag_ip(alloc_id, 'BRONZE')
  49.             else:
  50.                 release_ip(response['AllocationId'], ip)
  51.         else:
  52.             pprint(response)
  53.  
  54.  
  55. if __name__ == '__main__':
  56.     while True  :
  57.         get_nice_ip()
Add Comment
Please, Sign In to add comment