Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for EC2 instance to start

Tags:

I have a custom AMI which runs my service. Using the AWS Java SDK, I create an EC2 instance using RunInstancesRequest from the AMI. Now before I begin to use my service, I must ensure that the newly created instance is up and running. I poll the instance using:

var transitionCompleted = false
while (!transitionCompleted) {
  val currentState = instance.getState.getName
  if (currentState == desiredState) {
    transitionCompleted = true
  }
  if(!transitionCompleted) {
    try {
      Thread.sleep(TRANSITION_INTERVAL)
    } catch {
      case e: InterruptedException => e.printStackTrace()
    }
  }
}

So when the currentState of the instance turns into desiredState(which is running), I get the status that the instance is ready. However any newly created instance, despite being in running state, is not available for immediate use as it is still initializing.

How do I ensure that I return only when I'm able to access the instance and its services? Are there any specific status checks to make?

PS: I use Scala

like image 951
Slartibartfast Avatar asked Aug 10 '16 04:08

Slartibartfast


1 Answers

You are checking instance state, while what you are actually interested in are the instance status checks. You could use describeInstanceStatus method from the Amazon Java SDK, but instead of implementing your own polling (in a non-idiomatic Scala) it's better to use a ready solution from the SDK: the EC2 waiters.

import com.amazonaws.services.ec2._, model._, waiters._

val ec2client: AmazonEC2 = ...

val request = new DescribeInstanceStatusRequest().withInstanceIds(instanceID)

ec2client.waiters.instanceStatusOk.run(
  new WaiterParameters()
    .withRequest(request)
    // Optionally, you can tune the PollingStrategy:
    // .withPollingStrategy(...)
  )
)

To customize polling delay and retry strategies of the waiter check the PollingStrategy documentation.

like image 91
laughedelic Avatar answered Sep 22 '22 16:09

laughedelic