Saturday, December 10, 2011

fetching ec2 ondemand (excluding spot instances)

EC2 describeInstance API has no way filtering out only on-demand instances. The way I do it using python boto library:

from boto.ec2.connection import EC2Connection
ec2 = EC2Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
reservations = ec2.get_all_instances(filters = {"instance-state-name":"running"})
ondemand_instances = []
for r in reservations:
    for i in r.instances:
        if not hasattr(i, "instanceLifecycle"):
            ondemand_instances.append(i)

However If I want to fetch all running instances there is a nice filter to do so:

reservations = ec2.get_all_instances(filters = {"instance-lifecycle":"spot",
                                    "instance-state-name":"running"})
spot_instances = []
for r in reservations:
    for i in r.instances:
        spot_instances.append(i)

No comments: