我是谷歌云的新手。我想在 VM 实例上运行 Python 脚本(在 Python 脚本结束时,结果将保存为文件)。由于脚本会运行很长时间,我想从本地 Linux 控制台使用gcloud
命令提交它。脚本运行完成后,VM 实例会自动停止以避免额外的成本,结果文件应该存储在某个地方,以便我以后可以访问它。
我不熟悉 Bash 命令,我想我可以提交一个“.sh”文件?我应该在文件中放入什么以及如何将任务提交给 VM 实例?非常感谢!
我是谷歌云的新手。我想在 VM 实例上运行 Python 脚本(在 Python 脚本结束时,结果将保存为文件)。由于脚本会运行很长时间,我想从本地 Linux 控制台使用gcloud
命令提交它。脚本运行完成后,VM 实例会自动停止以避免额外的成本,结果文件应该存储在某个地方,以便我以后可以访问它。
我不熟悉 Bash 命令,我想我可以提交一个“.sh”文件?我应该在文件中放入什么以及如何将任务提交给 VM 实例?非常感谢!
您可以利用Cloud Functions 存储触发器和Compute Engine API 中的instance.stop 方法来完成所需的任务。
一般的想法是使用gcloud compute instance start命令启动实例,然后利用带有 --command 标志的 gcloud compute ssh在实例中运行脚本。使实例中的 Python 脚本使用适用于 Python 的 Cloud Storage 客户端库将文件上传到 Cloud Storage,并利用 Cloud Functions Storage Object Finalize事件作为触发器来调用 Cloud Function 并停止实例。
Set access for each API
并选择Read Write
存储。gcloud compute ssh your-instance
SSH 进入您的 VM 并创建您的 Python 脚本(不要忘记通过运行使其可执行chmod +x your-script.py
)。例如,以下脚本将存储在默认目录中,并具有以下内容:#!/usr/bin/env python3
import os
from time import sleep
from google.cloud import storage
bucket_name = 'test-bucket-vmss'
destination_blob_name = 'myuploadedfile.txt'
file_name = 'example_upload_file.txt'
#Create a file
f=open(file_name,'w+')
f.write('This is an example file to upload to Google Cloud Storage')
f.close()
#Simulates that the file takes 5 minutes to be created
sleep(300)
#Upload the file to Google Cloud Storage
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename("./"+file_name)
compute.instances.stop
分配的权限。一个。Cloud Function 的 main.py 部分应包含:from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from time import sleep
credentials = GoogleCredentials.get_application_default()
service = discovery.build('compute', 'v1', credentials=credentials)
# Project ID for this request.
project = 'you-project-name' # TODO: Update placeholder value.
# The name of the zone for this request.
zone = 'the-zone-of-the-vm' # TODO: Update placeholder value.
# Name of the instance resource to stop.
instance = 'the-name-of-the-vm' # TODO: Update placeholder value.
def hello_gcs(event, context):
"""Triggered by a change to a Cloud Storage bucket.
Args:
event (dict): Event payload.
context (google.cloud.functions.Context): Metadata for the event.
"""
file = event
print(f"The file: {file['name']} was uploaded to the bucket.")
#Stopping VM after the file is processed
sleep(5)
request = service.instances().stop(project=project, zone=zone, instance=instance)
response = request.execute()
print("The VM was stopped.")
湾。Cloud Function 的 requirements.txt 部分应包含:
google-api-python-client
oauth2client
并部署功能。
### Start the Compute engine instance
gcloud compute instances start the-name-of-the-vm --zone=the-zone-of-the-vm
### Take advantage of the --command flag to run your script within the Compute Engine instance
gcloud compute ssh instance-2 --command="./your-script.py &" --zone=the-zone-of-the-vm
文件上传到 Cloud Storage 存储桶后,Cloud Function 将负责停止实例。