Skip to content

Instantly share code, notes, and snippets.

@daffodilistic
Last active April 28, 2021 13:13
Show Gist options
  • Save daffodilistic/ea648df41d9accb8604917386ce97851 to your computer and use it in GitHub Desktop.
Save daffodilistic/ea648df41d9accb8604917386ce97851 to your computer and use it in GitHub Desktop.
Keeps a GCP instance alive. Useful for preemptible instances
import os
from googleapiclient import discovery
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "./service-account-key.json"
HOSTNAME = "example.com"
GCP_PROJECT = 'project_name'
GCP_INSTANCE_ZONE = 'instance_zone'
GCP_INSTANCE_NAME = 'instance_name'
def check_ping():
response = os.system(F"ping -c 1 {HOSTNAME} > /dev/null")
# if response == 0:
# pingstatus = "Network Active"
# else:
# pingstatus = "Network Error"
# return pingstatus
return response
is_server_alive = True if check_ping() == 0 else False
if (is_server_alive == False):
print("Instance stopped - sending request to start")
service = discovery.build('compute', 'v1')
request = service.instances().start(project=GCP_PROJECT, zone=GCP_INSTANCE_ZONE, instance=GCP_INSTANCE_NAME)
response = request.execute()
else :
print("Instance is still up, exiting")
print("Finished keepalive check")
#!/bin/bash
source ./venv/bin/activate
python keepalive.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment