问题
I have an app running on Google App Engine, and an AI running on Google Compute Engine. I'm triggering the VM instance to start on a change in a Google Cloud Storage bucket, and have a start-up script that I attempt to store in the metadata of the GCE instance. My cloud functions looks like this:
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)
The VM starts, but the startup script does not run. The script has been simplified for the purposes of the question, but this is just a basic command I'm trying to run. I would add the script directly to the metadata in the console, but I use values from the cloud function trigger to run commands in the VM. What am I missing?
I've attempted to set the metadata in two ways:
"items": [{"key": "startup-script", "value": startup_script}]
as well as:
"items": [{"startup-script" : startup_script}]
Neither work. The commands run beautifully if I manually type them in the shell.
回答1:
Look into your logs to determine why its not executing.
https://cloud.google.com/compute/docs/startupscript#viewing_startup_script_logs
Probably you the issue is that you are trying to execute a python script instead of a bash script.
Your startup script should be something like:
#! /bin/bash
# ...
python3 paht/to/python_script.py
来源:https://stackoverflow.com/questions/62096826/startup-script-in-metadata-not-running-python-google-compute-engine-cloud-sto