使用 python 关闭实例脚本运行于

Use python to shut down instance script runs on

我正在 运行宁机器学习脚本需要很长时间才能完成。我想 运行 在 AWS 上使用更快的处理器运行它们,并在实例完成时停止实例。

可以在 运行ning 脚本中使用 boto 来停止它自己的实例吗?有没有更简单的方法?

请参阅 Creating a Connection 了解如何创建连接。以前从未尝试过这个,所以要小心。还要确保实例支持 EBS。否则实例将在您停止时终止。

import boto.ec2
import boto.utils

conn = boto.ec2.connect_to_region("us-east-1") # or your region

# Get the current instance's id
my_id = boto.utils.get_instance_metadata()['instance-id']

conn.stop_instances(instance_ids=[my_id])

如果您的 EC2 实例是 运行 Linux,您只需发出 haltshutdown 命令即可停止您的 EC2 实例。这使您无需 IAM 权限即可关闭 EC2 实例。