如何为 EC2 现货实例模拟 BidEvictedEvent?

How to simulate BidEvictedEvent for EC2 spot instances?

我有一个包含多个 EC2 spot 实例的应用程序负载均衡器。

我发现其中一个因为BidEvictedEvent被终止了,即有人要求一个价格比我高的现货实例。

BidEvictedEvent 使我的 Web 服务不可用 (502 bad gateway) 几秒钟。

所以我想执行一个脚本,在 EC2 终止之前将其与自动缩放组分离。

现在我的问题是,如何模拟 BidEvictedEvent 以确保我的脚本得到正确执行?

我试过从 AWS 控制台终止 EC2 实例。但是,当在 EC2 终止之前没有执行任何脚本时,这不会为我的 Web 服务的客户端创建 502 bad gateway

我使用提到的方法 here 来监控 BidEvictedEvent 何时发生。

您提供的 link 用于检测现场中断通知的旧方法。也许这正是您想要执行此操作的方式,但现在您会使用 CloudWatch Event 规则 EC2 Spot Instance Interruption Warning.

使用该规则,您可以设置一个 lambda 函数,该函数将对计划终止的实例执行操作。这些操作可以包括从 ASG 中移除,或通过 SSM Command Run.

对它执行 运行 自定义命令

此外,您还可以轻松地模拟 事件,因为它具有已知格式并且您可以使用测试事件调用 lambda。

更多信息请见 Taking Advantage of Amazon EC2 Spot Instance Interruption Notices。您的 lambda 函数需要 process/simulate 的现场中断事件示例是:

{
  "version": "0",
  "id": "1e5527d7-bb36-4607-3370-4164db56a40e",
  "detail-type": "EC2 Spot Instance Interruption Warning",
  "source": "aws.ec2",
  "account": "123456789012",
  "time": "1970-01-01T00:00:00Z",
  "region": "us-east-1",
  "resources": [
    "arn:aws:ec2:us-east-1b:instance/i-0b662ef9931388ba0"
  ],
  "detail": {
    "instance-id": "i-0b662ef9931388ba0",
    "instance-action": "terminate"
  }
}