I'm using AWS, Python, and the Boto library.
I'd like to invoke .start()
or .stop()
on a Boto EC2 instance, then "poll" it until it has completed either.
import boto.ec2
credentials = {
'aws_access_key_id': 'yadayada',
'aws_secret_access_key': 'rigamarole',
}
def toggle_instance_state():
conn = boto.ec2.connect_to_region("us-east-1", **credentials)
reservations = conn.get_all_reservations()
instance = reservations[0].instances[0]
state = instance.state
if state == 'stopped':
instance.start()
elif state == 'running':
instance.stop()
state = instance.state
while state not in ('running', 'stopped'):
sleep(5)
state = instance.state
print " state:", state
However, in the final while
loop, the state seems to get "stuck" at either "pending" or "stopping". Emphasis on "seems", as from my AWS console, I can see the instance does in fact make it to "started" or "stopped".
The only way I could fix this was to recall .get_all_reservations()
in the while
loop, like this:
while state not in ('running', 'stopped'):
sleep(5)
# added this line:
instance = conn.get_all_reservations()[0].instances[0]
state = instance.state
print " state:", state
Is there a method to call so the instance
will report the ACTUAL state?
The wait_until_running function in Python Boto3 seem to be what I would use.
http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Instance.wait_until_running
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With