Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting multiple instances and wait until they are completely started using boto3

I'm starting a bunch of EC2 Instances using the following code

def start_ec2_instances(self, instanceids):
    ec2client = boto3.resource('ec2')
    response = ec2client.start_instances(InstanceIds=instanceids)
    return

Now it starts successfully. However I want to use wait_until_running method to check the status of the instances and wait until all the instances are started.

wait_until_running method can be issued on single instances only? How do I wait for list of instances that has been started using boto3

This is what I'm doing currently. But wanted to know if there are any other ways to do it in one shot

def wait_until_instance_running(self, instanceids):
    ec2 = boto3.resource('ec2')
    for instanceid in instanceids:
        instance = ec2.Instance(instanceid)
        logger.info("Check the state of instance: %s",instanceid)
        instance.wait_until_running()
    return
like image 835
Damien-Amen Avatar asked Oct 28 '25 03:10

Damien-Amen


2 Answers

Use

  • Wait until instance is running or
  • Wait until a successful state is reached

Try this:

ec2 = boto3.client('ec2')
start_ec2_instances(instanceids)
waiter = ec2.get_waiter('instance_running')
waiter.wait(InstanceIds=instanceids)

The waiter function polls every 15 seconds until a successful state is reached. An error is returned after 40 failed checks.

like image 57
helloV Avatar answered Oct 29 '25 21:10

helloV


You can use EC2 client's Waiter.wait call to pass an array of EC2 instance Ids.

http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Waiter.InstanceRunning

like image 26
Asdfg Avatar answered Oct 29 '25 21:10

Asdfg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!