liorko
liorko

Reputation: 1664

Terminate spot instances when the request expires

I'm using boto3 to deploy spot instances. My request is expired after period of time (as I defined). When the request expires, I'm expecting that the machine will terminate. In order to create the spot request I used this script:

client = boto3.client('ec2', region_name=regions[idx][:-1])    
client.request_spot_instances(
                        DryRun=False,
                        SpotPrice=price_bids,
                        InstanceCount=number_of_instances_to_deploy,
                        LaunchSpecification=
                        {
                            'ImageId': amis_id[idx],
                            'KeyName': 'MyKey',
                            'SecurityGroups': ['SG'],
                            'InstanceType': machine_type,
                            'Placement':
                                {
                                    'AvailabilityZone': regions[idx],
                                },
                        },
                        ValidUntil=new_date,
                )

How can I terminate the spot instances when the request is not valid anymore?

Upvotes: 3

Views: 1131

Answers (2)

Matt Houser
Matt Houser

Reputation: 36063

In a Spot Instance request, the ValidUntil only determines the length of time in which the request is active. After the ValidUntil time, the request will expire and will not be fulfilled.

However, if your request is fulfilled before the request expires, then the EC2 instances that are launched will run until one of these happens:

  • The current spot price exceeds the maximum spot price and you are out-bid, or
  • You terminate your EC2 instances.

If you want your EC2 instances to terminate before they are out-bid, then you need to terminate them yourselves.

Upvotes: 5

helloV
helloV

Reputation: 52375

There is no spot instance launched if the request is still active, so there is no question of terminating your spot instances. Your request will expire once the ValidUntil time is reached. You didn't specify the type of this spot request:

Type='one-time'|'persistent'

By default, the value is one-time. In that case, the request expires and removed once the ValidUntil time is reached. If you do not specify ValidUntil then the request is effective indefinitely.

From: request_spot_instances

ValidUntil (datetime) -- The end date of the request. If this is a one-time request, the request remains active until all instances launch, the request is canceled, or this date is reached. If the request is persistent, it remains active until it is canceled or this date and time is reached.

Default: The request is effective indefinitely.

Upvotes: 2

Related Questions