Benjamin Jones
Benjamin Jones

Reputation: 997

aws cli- terminate spot instance every 15 minutes

I have 6 spot instances for a project. I only need them up for 15 mins then I need to terminate them to spin then up again.

My idea is as follow. Install aws cli within the AMI. Then create a cron job to terminate ec2 spot instance

Current : aws ec2 terminate-instances

However you need the instance ID, being a spot instance I do not know the ID.

--update--

Per suggestion below, did stop-instance test. Got error

aws ec2 stop-instances --instance-ids ec2metadata

An error occurred (InvalidInstanceID.Malformed) when calling the StopInstances operation: Invalid id: "ec2metadata" (expecting "i-...")

How can I terminate the instances within the instance I want to terminate?

Upvotes: 1

Views: 376

Answers (1)

helloV
helloV

Reputation: 52443

curl -s http://169.254.169.254/latest/meta-data/instance-id

will get the instance-id of the instance. Something like:

aws ec2 stop-instances --instance-ids `curl -s http://169.254.169.254/latest/meta-data/instance-id`

or create a shell script and execute it as a cron job.

#!/bin/sh

instid = `curl -s http://169.254.169.254/latest/meta-data/instance-id`
aws ec2 stop-instances --instance-ids $instid

Upvotes: 1

Related Questions