Spot Instance

Deploy EC2 spot instances for significant cost savings on fault-tolerant workloads.

module "spot_worker" {
  source  = "registry.patterneddesigns.ca/patterneddesigns/ec2-instance/aws"
  version = "1.5.0"

  instance_name = "batch-worker"
  instance_type = "c6i.xlarge"
  ami_id        = data.aws_ami.amazon_linux.id
  subnet_id     = module.vpc.private_subnets[0]

  spot_price                     = "0.10"
  spot_type                      = "persistent"
  spot_instance_interruption_behavior = "stop"

  user_data = <<-EOF
    #!/bin/bash
    # Configure instance to handle spot interruption
    yum install -y aws-cli jq

    # Start monitoring for spot interruption
    cat > /usr/local/bin/spot-monitor.sh << 'SCRIPT'
    #!/bin/bash
    while true; do
      if curl -s -o /dev/null -w "%{http_code}" http://169.254.169.254/latest/meta-data/spot/termination-time | grep -q 200; then
        echo "Spot instance termination notice received"
        # Graceful shutdown logic here
        systemctl stop myapp
        exit 0
      fi
      sleep 5
    done
    SCRIPT
    chmod +x /usr/local/bin/spot-monitor.sh
    /usr/local/bin/spot-monitor.sh &
  EOF

  tags = {
    Environment = "development"
    Workload    = "batch-processing"
  }
}

Spot Instance Types

TypeBehavior
one-timeInstance terminates when interrupted
persistentInstance restarts after capacity available

Interruption Behaviors

BehaviorDescription
terminateInstance is terminated
stopInstance is stopped (persistent only)
hibernateInstance hibernates (if supported)

Cost Comparison

Spot instances typically offer 60-90% savings compared to on-demand pricing.

Notes

  • Use for fault-tolerant, flexible workloads only
  • Implement graceful shutdown handling
  • Consider Spot Fleet for mixed instance types
  • Monitor /latest/meta-data/spot/termination-time for 2-minute warning