Skip to content

Commit

Permalink
Remove other ips after attach static ip to instance
Browse files Browse the repository at this point in the history
  • Loading branch information
coolbeevip committed Nov 7, 2023
1 parent 4438ff3 commit 0cd9007
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 9 deletions.
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def job_wrapper():


if __name__ == '__main__':
schedule.every(5).minutes.do(job_wrapper)
schedule.every(1).minutes.do(job_wrapper)

while True:
schedule.run_pending()
Expand Down
13 changes: 6 additions & 7 deletions src/aws_lightsail_guard/guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class Guard:

def lightsail_instance_public_ip_keepalive(self, name):
instance = lightsail.get_instance(instanceName=name)['instance']
# TODO 此处应该检查域名
if check_address(instance['publicIpAddress'], 443):
logging.info(
f"Instance {instance['name']} public static ip {instance['publicIpAddress']} OK")
Expand All @@ -20,19 +21,17 @@ def lightsail_instance_public_ip_keepalive(self, name):
allocate_static_ip_response = lightsail.allocate_static_ip(
staticIpName=new_static_ip_name
)
new_static_ip = allocate_static_ip_response['staticIp']['ipAddress']
logging.debug(f"Allocate public ip {allocate_static_ip_response} success")

# Release old static ip
released_old_static_ip = None
# Release others static ip
for static_ip in lightsail.get_static_ips()['staticIps']:
if static_ip['ipAddress'] == instance['publicIpAddress']:
if static_ip['name'] == new_static_ip_name:
new_static_ip = static_ip['ipAddress']
else:
try:
release_static_ip_response = lightsail.release_static_ip(
staticIpName=static_ip['name'])
logging.info(f"Release public ip {release_static_ip_response} success")
released_old_static_ip = static_ip['ipAddress']
break
except Exception as e:
logging.info(f"Release public ip {release_static_ip_response} fails")

Expand All @@ -47,7 +46,7 @@ def lightsail_instance_public_ip_keepalive(self, name):
get_domains_response = lightsail_domain.get_domains()
for domain in get_domains_response['domains']:
for domainEntry in domain['domainEntries']:
if domainEntry['target'] == released_old_static_ip:
if domainEntry['target'] == 't5.coolbeevip.com':
lightsail_domain.update_domain_entry(
domainName=domain['name'],
domainEntry={
Expand Down
2 changes: 1 addition & 1 deletion src/aws_lightsail_guard/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@


def check_address(host, port):
socket.setdefaulttimeout(5)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
location = (host, port)
sock.settimeout(30)
result = sock.connect_ex(location)
sock.close()
return result == 0

0 comments on commit 0cd9007

Please sign in to comment.