I am trying to run a Python script via Cloud Scheduler every 5 minutes that checks the statuses of websites and starts/stops Google Cloud Compute instances.
The code is basically:
import requests
import os
import sys
import optmain
websites = {'espn':'https://www.espn.com/', 'fb':'https://www.facebook.com/'}
def auto_fix():
for x in websites:
try:
z = requests.get(websites[x], timeout=15)
except:
optmain('restart', x)
auto_fix()
Thing is, the function optmain
was this:
def optmain(option, instance):
option = option.lower()
instance = instance.lower()
if option == 'restart':
os.system('gcloud compute instances stop {}'.format(instance))
time.sleep(100)
os.system('gcloud compute instances start {}'.format(instance))
But I dont know if this will work if moved to Google Cloud Functions because of the system call for gcloud compute instances stop/start {instance}
. I already tried putting this up in Cloud Scheduler and it failed. Yet again, I don't know if I even did that right. So can I please get some assistance here? I hope you get the jist of what I'm trying to accomplish, its very basic.
It's generally better to use the Python client library rather than shelling out to gcloud
.
For example, to stop a Compute instance from a Cloud Function, you would add google-api-python-client
to your requirements.txt
and run something like:
from googleapiclient import discovery
service = discovery.build('compute', 'v1')
# Project ID for this request.
project = 'my-project' # TODO: Update placeholder value.
# The name of the zone for this request.
zone = 'my-zone' # TODO: Update placeholder value.
# Name of the instance resource to stop.
instance = 'my-instance' # TODO: Update placeholder value.
request = service.instances().stop(project=project, zone=zone, instance=instance)
response = request.execute()