goose goose - 15 days ago 6
Python Question

Use python to shut down instance script runs on

I am running machine learning scripts that take a long time to finish. I want to run them on AWS on a faster processor and stop the instance when it finishes.

Can boto be used within the running script to stop its own instance? Is there a simpler way?

Answer

See Creating a Connection on how to create a connection. Never tried this one before, so use caution. Also make sure the instance is EBS backed. Otherwise the instance will be terminated when you stop it.

import boto.ec2
import boto.utils

conn = boto.ec2.connect_to_region("us-east-1") # or your region

# Get the current instance's id
my_id = boto.utils.get_instance_metadata()['instance-id']

conn.stop_instances(instance_ids=[my_id])