1

I have found some example code which is apparently able to create an Amazon Ec2 instance using python boto. However, for the life of me I can't work out how to make a function to delete the instance.

Can anyone who knows a bit more about python and boto show me what I should be doing in order to remove this instance.

# Delete EC2 instance
def delete_server():
    print(_yellow("Deleting EC2 instance"))

# Create EC2 instance
def create_server():
    print(_yellow("Creating EC2 instance"))

    image = conn.get_all_images(ec2_amis)

    reservation = image[0].run(1, 1, key_name=ec2_key_pair, security_groups=ec2_security,
        instance_type=ec2_instancetype)

    instance = reservation.instances[0]
    conn.create_tags([instance.id], {"Name":config['INSTANCE_NAME_TAG']})
    while instance.state == u'pending':
        print(_yellow("Instance state: %s" % instance.state))
        time.sleep(10)
        instance.update()

    print(_green("Instance state: %s" % instance.state))
    print(_green("Public dns: %s" % instance.public_dns_name))

    return instance.public_dns_name

2 Answers 2

6

The boto documentation for EC2 covers this need. You have the instance ID you created, just terminate it with:

def delete_server(instanceId):
    conn.terminate_instances(instance_ids=[instanceId])

where conn is the same global connection variable you used to create the instance. Note that the boto call takes an array of instance IDs. The terminate_instances call will return a list of instance IDs that were terminated.

Note that if you protected the instance from API termination you'd have to remove that protection first. Your example code does not do that, so you should have no trouble removing it.

Sign up to request clarification or add additional context in comments.

1 Comment

some times the instance stuck in the 'terminated' state ! therefore, might be this function does not really remove the instance.
0

You also might want to look at starcluster.

It might serve your purpose better than raw boto, but in any case the code uses boto and provides examples of most things you would probably want to do in terms of managing EC2 instances and clusters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.