我可以使用什么 Python 或 CLI 调用来终止 AWS spot 实例并从 spot 实例本身发出请求?

What Python or CLI call can I use to terminate an AWS spot instance and request from within the spot instance itself?

我有一份很长的 运行 aws 工作,我正在使用 spot 实例(每个工作一个实例)来省钱。 python 代码可以处理停止和重新启动,但是当我分析工作结束时,我想终止 spot 实例并且不再启动(对于那个批次)这样我就没有手动照看东西(我正在使用昂贵的 GPU 实例,所以我想尽快停止)。我的代码都在 python 中 - 是否有 aws python sdk 或 cli 调用将终止该 spot 实例 不再启动,全部来自在 spot 实例本身内?结果是我不想在工作完成后支付 GPU 时间。

几年前的一个相关问题是 here,但它没有完全回答我的问题。

谢谢!

对最后一个 spot 实例执行以下操作:

  1. 检索实例 ID:wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
  2. 修改实例的关闭行为: aws ec2 modify-instance-attribute --instance-initiated-shutdown-behavior terminate
  3. 然后当你想终止它时:sudo shutdown -h now。也可以通过以下方式安排关机:echo "sudo halt" | at now + 5 minutes.

如果您正在寻找一种更 Pythonic 的方式来做到这一点。您可以使用 boto3. It is an SDK for managing AWS instances and many services under AWS. You can use Udhav's method to get the instance id from http://169.254.169.254/latest/meta-data/instance-id and pass this instance id to the boto3 function 来终止它。

请确保在使用 sdk 或 cli 时,您必须使用 secret_access_key 和 secret_access_id 创建一个 IAM 角色来验证此请求。 以下文字来自官方AWS documentation

编程访问

您必须提供您的 AWS 访问密钥才能对 AWS 进行编程调用或使用 AWS 命令​​行界面或适用于 PowerShell 的 AWS 工具。

创建访问密钥时,将访问密钥 ID(例如 AKIAIOSFODNN7EXAMPLE)和秘密访问密钥(例如 wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY)创建为一组。秘密访问密钥仅在您创建时可供下载。如果您没有下载秘密访问密钥或丢失了它,则必须创建一个新的。