元数据中的启动脚本未运行(Python、Google Compute Engine、云存储触发器)

2023-12-24

我有一个在 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 中手动输入这些命令,它们的运行效果会非常好。


查看您的日志以确定其不执行的原因。

https://cloud.google.com/compute/docs/startupscript#viewing_startup_script_logs https://cloud.google.com/compute/docs/startupscript#viewing_startup_script_logs

也许你的问题是你正在尝试执行 python 脚本而不是 bash 脚本。

你的启动脚本应该是这样的:

#! /bin/bash

# ...
python3 paht/to/python_script.py
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

元数据中的启动脚本未运行(Python、Google Compute Engine、云存储触发器) 的相关文章

随机推荐