Skip to content

Instantly share code, notes, and snippets.

@nirbhabbarat
Last active February 19, 2018 08:23
Show Gist options
  • Save nirbhabbarat/bdb104cc5db4ba3e87c0a010ff54fdca to your computer and use it in GitHub Desktop.
Save nirbhabbarat/bdb104cc5db4ba3e87c0a010ff54fdca to your computer and use it in GitHub Desktop.
Rotate all the ondemand machines which are not in spot - spotinst
import time
import datetime
import requests
import boto3
aws_profile_name = 'default'
token = 'XXX' # generate token from http://docs.spotinst.com/#page:authentication,header:header-permanent-access-token
headers = {'Authorization': 'Bearer '+token}
def get_instance_by_id(id):
boto3.setup_default_session(profile_name = aws_profile_name)
ec2 = boto3.client('ec2')
instances = ec2.describe_instances(InstanceIds=[id])
for reservation in instances["Reservations"]:
for instance in reservation["Instances"]:
return instance["InstanceLifecycle"]
def list_elasticgroups():
epoc = int(time.time())
today = datetime.datetime.now().strftime("%Y-%m-%d")
minCreatedAt = datetime.date(2000,1, 1) #year, month, day
createdAt = minCreatedAt.strftime("%Y-%m-%d")
url = 'https://api.spotinst.io/aws/ec2/group?includeDeleted=false&minCreatedAt='+createdAt+'&maxCreatedAt='+today
res = requests.get(url, headers=headers)
res_json = res.json()
print res_json
for sig_ojb in res_json["response"]["items"]:
print sig_ojb["id"]
print sig_ojb["name"]
get_statefull_instance_by_sig(sig_ojb["id"])
def get_statefull_instance_by_sig(sig):
url = 'https://api.spotinst.io/aws/ec2/group/'+sig+'/statefulInstance'
res = requests.get(url, headers=headers)
res_json = res.json()
for sig_obj in res_json["response"]["items"]:
print sig_obj["id"]
if(get_instance_by_id(sig_obj["instanceId"]) != 'spot')
recyle(sig, sig_obj["id"])
def recyle(sig, ssig):
url = 'https://api.spotinst.io/aws/ec2/group/'+sig+'/statefulInstance/'+ssig+'/recycle'
res = requests.put(url, headers=headers)
res_json = res.json()
print res_json
list_elasticgroups()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment