Skip to content

Instantly share code, notes, and snippets.

@animaldna
Last active September 13, 2021 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save animaldna/3df5127a96ddd7764ecafdeb13e054f9 to your computer and use it in GitHub Desktop.
Save animaldna/3df5127a96ddd7764ecafdeb13e054f9 to your computer and use it in GitHub Desktop.
Cancel spot requests and stop (or terminate) EC2 instances @ 6PM EST each night.
import json
import boto3
ec2 = boto3.resource('ec2')
ec2_client = boto3.client('ec2')
def lambda_handler(event, context):
running_instances = []
spot_instances = []
spot_requests = []
running_filter = [
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
# get list of running instances
instances = ec2.instances.filter(Filters=running_filter)
# grab instance & spot request ids
for instance in instances:
if instance.spot_instance_request_id:
spot_requests.append(instance.spot_instance_request_id)
# spot_instances.append(instance.id)
else:
running_instances.append(instance.id)
# get spot instance requests
requests = ec2_client.describe_spot_instance_requests(SpotInstanceRequestIds=spot_requests).get('SpotInstanceRequests')
for request in requests:
# terminate one-time spot instances and cancel their requests
if request['Type'] == 'one-time':
ec2_client.terminate_instances(InstanceIds=[request['InstanceId']])
ec2_client.cancel_spot_instance_requests(SpotInstanceRequestIds=[request['SpotInstanceRequestId']])
# stop persistent request spot instances
elif request['Type'] == 'persistent':
ec2_client.stop_instances(InstanceIds=[request['InstanceId']])
# stop any on-demand instances
for instance in running_instances:
ec2_client.stop_instances(InstanceIds=running_instances)
return {
'statusCode': 200,
'body': json.dumps('success')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment