如何自动退出/停止正在运行的实例

时间:2013-05-17 12:06:22

标签: google-compute-engine

我设法创建了一个实例并将ssh加入其中。但是,我对Google Compute Engine有几个问题。

  1. 我知道我的实例运行时会收费。直到我退出实例。我的理解是否正确?
  2. 我希望在我的实例上运行一些批处理作业(java程序)。如何在作业完成后自动停止我的实例(这样我就不会因为它可能运行的额外时间而收费)
  3. 如果我开始工作并断开我的电脑,那么这个工作会继续在实例上运行吗?
  4. 此致 阿西

4 个答案:

答案 0 :(得分:10)

正确,实例会在运行时收取费用。 (至分钟,至少10分钟)。实例从它们通过API启动时开始运行,直到它们通过API停止。是否有任何用户通过SSH登录并不重要。对于大多数自动用例,用户从不登录 - 通过start up scripts安装和启动程序。

您可以通过Cloud Console查看正在运行的实例,以确认当前是否正在运行。

如果要从实例内部停止实例,最简单的方法是使用compute-rw Service Account Scope启动实例并使用gcutil。

例如,要使用compute-rw范围从命令行启动实例:

$ gcutil --project=<project-id> addinstance <instance name> --service_account_scopes=compute-rw

(这是通过云控制台手动创建实例时的默认设置)

稍后,在批处理作业完成后,您可以从里面实例中删除实例:

$ gcutil deleteinstance -f <instance name>

答案 1 :(得分:4)

您可以在批处理脚本的末尾放置halt命令(假设您在持久磁盘上输出结果)。 暂停后,实例将处于TERMINATED状态,您将不会被收费。 见https://developers.google.com/compute/docs/pricing 向下滚动到“实例正常运行时间”

答案 2 :(得分:0)

您可以在模型训练后自动关闭实例。模型训练完成后,只需再运行几行代码即可。

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials

credentials = GoogleCredentials.get_application_default()

service = discovery.build('compute', 'v1', credentials=credentials)

# Project ID for this request.
project = 'xyz'  # Project ID
# The name of the zone for this request.
zone = 'xyz'  # Zone information

# Name of the instance resource to stop.
instance = 'xyz'  # instance id

request = service.instances().stop(project=project, zone=zone, instance=instance)
response = request.execute()

将此添加到模型训练脚本中。训练完成后,GCP实例将自动关闭。 官方网站上的更多信息: https://cloud.google.com/compute/docs/reference/rest/v1/instances/stop

答案 3 :(得分:0)

如果你想使用python脚本停止实例,你可以这样:

from google.cloud.compute_v1.services.instances import InstancesClient
from google.oauth2 import service_account

instance_client = InstancesClient().from_service_account_file(<location-path>)
zone = <zone>
project = <project>
instance = <instance_id>
instance_client.stop(project=project, instance=instance, zone=zone)

在上面的脚本中,我假设您使用 service-account 进行身份验证。有关使用的库的文档,您可以访问这里: https://googleapis.dev/python/compute/latest/compute_v1/instances.html

相关问题