使用 google 云调度程序和 python 脚本的系统调用

System calls with google cloud scheduler and python script

我正在尝试每 5 分钟通过 Cloud Scheduler 运行 一个 Python 脚本来检查网站和 starts/stops Google 云计算实例的状态。

代码基本上是:

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()

事实是,函数 optmain 是这样的:

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))

但我不知道如果移动到 Google Cloud Functions 这是否有效,因为 gcloud compute instances stop/start {instance} 的系统调用。我已经尝试将它放在 Cloud Scheduler 中,但失败了。再一次,我不知道我是否做对了。那么我可以在这里得到一些帮助吗?我希望你能理解我想要完成的事情,这是非常基本的。

通常最好使用 Python 客户端库,而不是去 gcloud

例如,要从 Cloud Functions 停止计算实例,您可以将 google-api-python-client 添加到您的 requirements.txt 和 运行 中,例如:

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()