Andre
Andre

Reputation: 647

ec2 wait for instance to come up with timeout [Python]

I'm using AWS python API (boto3). My script starts a few instances and then waits for them to come up online, before proceeding doing stuff. I want the wait to timeout after a predefined period, but I can't find any API for that in Python. Any ideas? A snippet of my current code:

def waitForInstance(id):
    runningWaiter = self.ec2c.get_waiter("instance_status_ok")
    runningWaiter.wait(InstanceIds = [id])
    instance = ec2resource.Instance(id)
    return instance.state

I can certainly do something like running this piece of code in a separate thread and terminate it if needed, but I was wondering whether there is already a built in API in boto3 for that and I'm just missing it.

Upvotes: 3

Views: 3164

Answers (3)

Michael Amos
Michael Amos

Reputation: 1

You could put a sleep timer in your code. Sleep for x minutes, check it to see if it is finished and go back to sleep if not. After y number of attempts take some sort it action.

Upvotes: 0

mootmoot
mootmoot

Reputation: 13176

Why not check the instances status from time to time?

#code copy from boto3 doc 
for status in ec2.meta.client.describe_instance_status()['InstanceStatuses']:
  print(status)

refence : http://boto3.readthedocs.org/en/latest/guide/migrationec2.html

BTW, it is better to use tag naming for all the instances with a standard naming convention. Query any aws resources with its original ID is a maintenance nightmare.

Upvotes: 0

garnaat
garnaat

Reputation: 45916

A waiter has a configuration associated with it which can be accessed (using your example above) as:

runningWaiter.config

One of the settings in this config is max_attempts which controls how many attempts will be tried before giving up. The default value is 40. You can change that value like this:

runningWaiter.config.max_attempts = 10

This isn't directly controlling a timeout as your question asked but will cause the waiter to give up earlier.

Upvotes: 1

Related Questions