Skip to main content

EC2 spot instance

sample launch template In some instance type and OS, we are able to stop or hybernate the EC2 spot instances, and restart or resume them when we want to do so. While stop or hybernate the instances, we must pay for EBS and Elastic IP etc...

  MyLaunchTemplate:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateName: spot-instance-template
      LaunchTemplateData:
        InstanceType: "t3.nano"
        CreditSpecification:
          CpuCredits: "standard"
        InstanceInitiatedShutdownBehavior: stop
        KeyName: "mykeyname"
        NetworkInterfaces:
          - DeviceIndex: "0"
            AssociatePublicIpAddress: "true"
            Groups:
              - Ref: mysecuritygroup
            SubnetId:
              Ref: mysubnet
        InstanceMarketOptions:
          MarketType: spot
          SpotOptions:
            InstanceInterruptionBehavior: stop
            SpotInstanceType: persistent
        BlockDeviceMappings:
          - DeviceName: /dev/xvda
            Ebs:
              DeleteOnTermination: true
              VolumeType: gp3
              VolumeSize: 8

after create or update the stack, confirm the launch template you've just created

aws ec2 describe-launch-templates
aws ec2 describe-launch-template-versions --launch-template-id lt-xxxx --versions x

create spot instance with the launch template. this example override image id, instance type.

$ aws ec2 run-instances --image-id ami-xxxx --instance-type t2.medium --launch-template 'LaunchTemplateId=lt-xxxx,Version=x' --dry-run
$ aws ec2 run-instances --image-id ami-xxxx --instance-type t2.medium --launch-template 'LaunchTemplateId=lt-xxxx,Version=x'

confirm spot instance

$ aws ec2 describe-spot-instance-requests --query 'SpotInstanceRequests[].{"SpotInstanceRequestId":SpotInstanceRequestId, "InstanceId":InstanceId, "Status":Status, "State":State}'  
4 aws ec2 describe-instances --filter 'Name=spot-instance-request-id,Values=sir-xxxx' --query 'Reservations[].Instances[].{"State":State, "InstanceId":InstanceId}'

temporary stop instance and restart it

$ aws ec2 stop-instances --instance-id i-xxxx
$ aws ec2 start-instances --instance-id i-xxxx

cancel spot instance request and terminate spot instance

$ aws ec2 cancel-spot-instance-requests --spot-instance-request-ids sir-xxxx
$ aws ec2 terminate-instances --instance-id i-xxxx