【问题标题】:Spin an AWS EC2 Spot instance with some validity using Terraform使用 Terraform 旋转具有一定有效性的 AWS EC2 Spot 实例
【发布时间】:2019-12-18 02:00:13
【问题描述】:

我正在尝试旋转具有一定有效性的 AWS EC2 Spot 实例(例如,创建的 Spot 应该可以访问 2 小时或 3 小时,并且 Spot 实例应该被终止)。 我可以使用以下代码旋转 Spot 实例,但无法设置创建的 Spot 实例的持续时间/有效性。

我正在共享我的 Terraform 代码(main.tf 和 variable.tf),我试图通过它来旋转一个 Spot 实例。 我尝试使用 main.tf 文件中的以下 2 行代码设置 Spot 实例的到期时间,但没有成功

  valid_until = "${var.spot_instance_validity}"
  terminate_instances_with_expiration = true

对于 valid_until ,我无法提供 RFC3339 格式或 YYYY-MM-DDTHH:MM:SSZ - 从我旋转 Spot 实例开始计算 2 小时。所以从我的 main.tf 文件中删除了上面两行代码

下面是我用来旋转 Spot 实例的 main.tf 文件

provider "aws" {
  access_key = "${var.access_key}"
  secret_key = "${var.secret_key}"
  region     = "${var.region}"
}

resource "aws_spot_instance_request" "dev-spot" {
  ami = "${var.ami_web}"
  instance_type = "t3.medium"
  subnet_id = "subnet-xxxxxx"
  associate_public_ip_address = "true"
  key_name = "${var.key_name}"
  vpc_security_group_ids = ["sg-xxxxxxx"]
  spot_price                      = "${var.linux_spot_price}"
  wait_for_fulfillment            = "${var.wait_for_fulfillment}"
  spot_type                       = "${var.spot_type}"
  instance_interruption_behaviour = "${var.instance_interruption_behaviour}"
  block_duration_minutes          = "${var.block_duration_minutes}"
  tags = {
    Name = "dev-spot"
  }
}

下面是变量文件“variable.tf”

variable "access_key" {
  default = ""
  } 
variable "secret_key" {
  default = ""
} 

variable "region" {
  default = "us-west-1"
}

variable "key_name" {
  default = "win-key"  
}

variable "windows_spot_price" {
  type        = "string"
  default     = "0.0309"
}
variable "linux_spot_price" {
  type        = "string"
  default     = "0.0125"
}
variable "wait_for_fulfillment" {
  default     = false
}
variable "spot_type" {
  type        = "string"
  default     = "one-time"
}
variable "instance_interruption_behaviour" {
  type        = "string"
  default     = "terminate"
}

variable "block_duration_minutes" {
  type        = "string"
  default     = "0"
}

variable "ami_web" {
  default = "ami-xxxxxxxxxxxx"
}

创建的 Spot 实例的有效期应设置为 1 小时或 2 小时,我可以从 variable.tf 文件调用,因此 Spot 实例应在 1 小时或 2 小时后终止(或应取消 Spot 实例请求)

有没有办法让我在过期的情况下旋转 aws ec2 Spot 实例?

【问题讨论】:

    标签: amazon-web-services amazon-ec2 terraform


    【解决方案1】:

    无法安排实例终止。 但是,您可以使用 CloudWatch Events 和 Lambda 创建您自己的实例终止逻辑。您需要根据您的变量(valid_until)在 Terraform 中创建一个scheduled event,它会调用 Lambda 函数来终止实例。

    AWS 还有一个名为Instance Scheduler 的解决方案。您可以简单地将标签附加到您的 Spot 实例以创建启动/停止计划。 但是,在这种情况下,您应该更改实例停止行为(默认为关闭)以终止。因此,您的实例将在停止时终止。这可以通过在 Terraform 中使用 aws_instance.instance_initiated_shutdown_behavior 参数来实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-02
      • 2021-05-27
      • 2021-05-04
      • 2021-10-05
      • 2015-12-04
      • 2018-07-12
      • 2011-07-08
      • 2022-12-07
      相关资源
      最近更新 更多