【发布时间】:2021-04-27 10:47:51
【问题描述】:
我创建了一个云函数,当触发它时应该创建一个 VM 实例并运行一个 python 脚本。
但是,没有创建虚拟机。
我可以在 CF 日志中看到以下消息,与我的部署有关:
resource.type = "cloud_function"
resource.labels.region = "europe-west2"
severity>=DEFAULT
severity=DEBUG
...
但是,在我的一生中,我看不到去哪里实际查看错误本身。
然后我在 Google 上搜索并发现以下 thread 关于 Cloud Functions 未显示任何日志的问题。
认为这可能是同一个问题,我将推荐的环境变量添加到我的部署中,但我仍然无法在日志中的任何地方找到错误。
谁能指出我正确的方向?
这也是我的云功能代码:
import os
from googleapiclient import discovery
from google.oauth2 import service_account
scopes = ["https://www.googleapis.com/auth/cloud-platform"]
sa_file = "key.json"
zone = "europe-west2-c"
project_id = "<<proj id>>" # Project ID, not Project Name
credentials = service_account.Credentials.from_service_account_file(
sa_file, scopes=scopes
)
# Create the Cloud Compute Engine service object
service = discovery.build("compute", "v1", credentials=credentials)
def create_instance(compute, project, zone, name):
# Get the latest Debian Jessie image.
image_response = (
compute.images()
.getFromFamily(project="debian-cloud", family="debian-9")
.execute()
)
source_disk_image = image_response["selfLink"]
# Configure the machine
machine_type = "zones/%s/machineTypes/n1-standard-1" % zone
config = {
"name": name,
"machineType": machine_type,
# Specify the boot disk and the image to use as a source.
"disks": [
{
"kind": "compute#attachedDisk",
"type": "PERSISTENT",
"boot": True,
"mode": "READ_WRITE",
"autoDelete": True,
"deviceName": "instance-1",
"initializeParams": {
"sourceImage": "projects/my_account/global/images/instance-image3",
"diskType": "projects/my_account/zones/europe-west2-c/diskTypes/pd-standard",
"diskSizeGb": "10",
},
"diskEncryptionKey": {},
}
],
"metadata": {
"kind": "compute#metadata",
"items": [
{
"key": "startup-script",
"value": "sudo apt-get -y install python3-pip\npip3 install -r /home/will_charles/requirements.txt\ncd /home/will_peebles/\npython3 /home/will_charles/main.py",
}
],
},
"serviceAccounts": [
{
"email": "837516068454-compute@developer.gserviceaccount.com",
"scopes": ["https://www.googleapis.com/auth/cloud-platform"],
}
],
"networkInterfaces": [
{
"network": "global/networks/default",
"accessConfigs": [{"type": "ONE_TO_ONE_NAT", "name": "External NAT"}],
}
],
"tags": {"items": ["http-server", "https-server"]},
}
return compute.instances().insert(project=project, zone=zone, body=config).execute()
def run(data, context):
create_instance(service, project_id, zone, "pagespeed-vm-4")
【问题讨论】:
-
1) 为什么要在代码中嵌入服务帐户?这对于 Cloud Functions 来说是不必要的,也是一个非常糟糕的主意。
-
2) 你没有
try/except处理错误的逻辑。您的函数将在异常时被终止。在无头环境中使用良好的编程实践。 -
3) 您没有登录您的代码。捕获错误,然后记录这些错误。在您的情况下,还要记录成功和结果。
-
4) 如果您在创建磁盘时指定了自己的
sourceImage,为什么会得到图像? -
感谢@JohnHanley,为什么将服务帐户嵌入云功能是个坏主意?因为安全问题?您是否建议使用默认的云功能服务帐户?
标签: python google-cloud-platform google-cloud-functions google-compute-engine