Gal Aloni
Gal Aloni

Reputation: 1

How can I get current aws spot price through Terraform

I would like to create auto scaling group in Terraform and get the spot price through a data and create the launch template with the updated spot price, for example:

    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]
    }
  }

I have implemented it with an external script for now using the describe_spot_price_history command in boto3 but I know for sure that there is a way to get the price through Terraform

Upvotes: 0

Views: 1022

Answers (1)

Vladimir Tiukhtin
Vladimir Tiukhtin

Reputation: 270

Since terraform aws provider 3.1.0 got released, there is a data source called "aws_ec2_spot_price". I use construction based on desired subnet (spot prices are different from one availability zone to another), but you certainly can adjust it up to your needs. I also add two more percent to prevent an instance from termination due to price volatility:

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"
  }
}

Upvotes: 1

Related Questions