我有一个在 Google App Engine 上运行的应用程序,以及一个在 Google Compute Engine 上运行的 AI。我触发 VM 实例在 Google Cloud Storage 存储桶中发生更改时启动,并尝试将启动脚本存储在 GCE 实例的元数据中。我的云功能如下所示:
import os
from googleapiclient.discovery import build
def start(event, context):
file = event
print(file["id"])
string = file["id"]
new_string = string.split('/')
user_id = new_string[1]
payment_id = new_string[2]
name = new_string[3]
print(name)
if name == "uploadcomplete.txt":
startup_script = """ #! /bin/bash
sudo su username
cd directory/directory
python analysis.py -- gs://location/{userId}/{paymentId}
""".format(userId=user_id, paymentId=payment_id)
# initialize compute api
service = build('compute', 'v1', cache_discovery=False)
print('VM Instance starting')
project = 'zephyrd'
zone = 'us-east1-c'
instance = 'zephyr-a'
# get metadata fingerprint in order to set new metadata
metadata = service.instances().get(project=project, zone=zone, instance=instance)
metares = metadata.execute()
fingerprint = metares["metadata"]["fingerprint"]
# set new metadata
bodydata = {"fingerprint": fingerprint,
"items": [{"key": "startup-script", "value": startup_script}]}
meta = service.instances().setMetadata(project=project, zone=zone, instance=instance,
body=bodydata).execute()
print(meta)
# confirm new metdata
instanceget = service.instances().get(project=project, zone=zone, instance=instance).execute()
print("'New Metadata:", instanceget['metadata'])
print(instanceget)
# start VM
request = service.instances().start(project=project, zone=zone, instance=instance)
response = request.execute()
print('VM Instance started')
print(response)
虚拟机启动,但启动脚本不运行。为了解决问题,该脚本已被简化,但这只是我尝试运行的基本命令。我会将脚本直接添加到控制台中的元数据中,但我使用云函数触发器中的值在虚拟机中运行命令。我缺少什么?
我尝试通过两种方式设置元数据:
"items": [{"key": "startup-script", "value": startup_script}]
也:
"items": [{"startup-script" : startup_script}]
都不起作用。如果我在 shell 中手动输入这些命令,它们的运行效果会非常好。