EC2: Waiting for a new instance to be operational

I would like to create a new instance based on my saved AMI.

I achieve this with the following code:

RunInstancesRequest rir = new RunInstancesRequest(imageId,1, 1); // Code for configuring the settings of the new instance ... RunInstancesResult runResult = ec2.runInstances(rir); 

However, I cannot wait to โ€œlockโ€ / wait until the instance rises and closes from the Thread.currentThread () command. sleep (xxxx).

On the other hand, StartInstancesResult and TerminateInstancesResult gives you the ability to access the state of instances and control any changes. But what about the state of an entirely new instance?

+6
source share
5 answers

Waiting for an EC2 instance to be ready is a common pattern. In the Python library, you also solve this with sleep calls:

  reservation = conn.run_instances([Instance configuration here]) instance = reservation.instances[0] while instance.state != 'running': print '...instance is %s' % instance.state time.sleep(10) instance.update() 

With this mechanism, you can poll when a new instance appears.

+3
source

boto3 has:

 instance.wait_until_running() 
+11
source

From the CLS change log for v1.6.0 :

Add a wait subcommand that allows the command to block until the AWS resource reaches a certain state ( issue 992 , issue 985 )

I don't see this in the documentation, but for me it worked:

 aws ec2 start-instances --instance-ids "i-XXXXXXXX" aws ec2 wait instance-running --instance-ids "i-XXXXXXXX" 

The wait instance-running did not end until the EC2 instance was started.

I do not use Python / boto / botocore, but I guess it has something similar. Check out waiter.py on Github .

+8
source

Depending on what you are trying to do (and how many servers you plan to start), instead of polling for instance launch events, you can install a simple program / script in AMI that runs once when the instance starts and sends a notification about it, i.e. AWS SNS theme.

A process that needs to know about starting new servers can then subscribe to this SNS topic and will receive push notifications every time the server starts.

Solves the same problem from a different angle; Your mileage may vary.

+1
source

Source: https://habr.com/ru/post/954788/