如果您不想只使用 python 脚本来调用 gcloud 命令,因为它与执行 bash 脚本相同,您可以使用Cloud Functions API Client Library for Python。
这个库的作用是创建和执行对Cloud Functions API 的HTTP 调用。您可以查看Cloud Functions REST reference 以了解这些调用的结构以及如何构建它们。
例如,我做了一个快速示例来测试这个 API 库,列出我项目中运行的函数:
import httplib2
import pprint
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
credentials = ServiceAccountCredentials.from_json_keyfile_name(
"key.json",
scopes="https://www.googleapis.com/auth/cloud-platform")
http = httplib2.Http()
http = credentials.authorize(http)
service = build("cloudfunctions", "v1", http=http)
operation = service.projects().locations().functions().list(parent='projects/wave16-joan/locations/europe-west1')
pprint.pprint(operation)
您必须安装模块oauth2client、google-api-python-client 和httplib2。如您所见,您需要创建一个服务帐户才能执行 REST API 调用,这需要“https://www.googleapis.com/auth/cloud-platform”范围来创建 CF。我自己创建了一个具有project/editor 权限的服务帐户,我认为这是创建 CF 所需的角色。
最后,要执行这个脚本,你可以做python <script_name>.py
现在,由于您要创建多个函数(请参阅此 API 调用需要如何构造here),要调用的服务应该如下所示:
operation = service.projects().locations().functions().create(
location='projects/wave16-joan/locations/europe-west1',
body={
"name":"...",
"entryPoint":"..."
"httpsTrigger": {
"url":"..."
}
}
)
您必须使用parameters listed here 中的一些填充请求的body。例如,"name" 键应为:
"name":"projects/YOUR_PROJECT/locations/YOUR_PROJECT_LOCATION/functions/FUNCTION_NAME"
附带说明一下,前面文档中列出的大多数主体参数都是可选的,但您需要名称、入口点、源、触发器等。
当然,这比创建 bash 脚本需要更多的工作,但结果更便携、更可靠,并且它允许您创建多个操作以以相同的方式部署多个功能。