【问题标题】:How can I get current aws spot price through Terraform如何通过 Terraform 获取当前的 aws 现货价格
【发布时间】:2020-10-20 01:15:23
【问题描述】:

我想在 Terraform 中创建 Auto Scaling 组并通过数据获取现货价格并使用更新的现货价格创建启动模板,例如:

    resource "aws_launch_template" "launch_cfg_spot" {
  count = length(var.pricing)
  name_prefix   = "launch_cfg_spot_${count.index}"
  instance_type = var.pricing[count.index].InstanceType
  image_id      = "ami-0ff8a91507f77f867"
  instance_market_options {
    market_type = "spot"
    spot_options {
      max_price = var.pricing[count.index].price
    }
  }
  network_interfaces{
    subnet_id = var.subnets[var.pricing[count.index].az]
    }
  }

我现在使用 boto3 中的 describe_spot_price_history 命令使用外部脚本实现了它,但我确信有一种方法可以通过 Terraform 获取价格

【问题讨论】:

标签: amazon-web-services terraform terraform-provider-aws


【解决方案1】:

自从 terraform aws provider 3.1.0 发布以来,有一个名为“aws_ec2_spot_price”的数据源。我使用基于所需子网的构造(现货价格从一个可用区到另一个可用区不同),但您当然可以根据自己的需要进行调整。我还增加了 2% 以防止实例因价格波动而终止:

data "aws_subnet" "selected" {
  id = var.subnet_id
}

data "aws_ec2_spot_price" "current" {
  instance_type     = var.instance_type
  availability_zone = data.aws_subnet.selected.availability_zone

  filter {
    name   = "product-description"
    values = ["Linux/UNIX"]
  }
}

locals {
  spot_price = data.aws_ec2_spot_price.current.spot_price + data.aws_ec2_spot_price.current.spot_price * 0.02
  common_tags = {
    ManagedBy = "terraform"
  }
}

【讨论】:

    猜你喜欢
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2021-04-08
    • 2021-05-17
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多