Wednesday, July 05, 2017

Waiting For an EC2 Instance To Initialize Before Completing a Script

Sometimes when running a script to create AWS Resources, an EC2 instance needs to be created and up and running before the script can continue.

In my case I'm instantiating a WatchGuard Firebox Cloud. Then I need to wait until it is ready before I can instantiate a Lambda function to configure it.

I have a script that gets a value (called as described in my last post on deleting a lambda function from CloudFormation which is used below. I query for an instance that has a particular tag, and the state is either pending or running. Then I use the instance-status-ok command to wait until the instance is ready to run my lambda function.

#this code assumes one firebox in account
#would need to get fancier to handle multiple instances with same tag

aws ec2 describe-instances --filters Name=tag-value,Values=firebox-network-firebox Name=instance-state-name,Values=pending,running > firebox.txt  2>&1

fireboxinstanceid=$(./execute/ firebox.txt "InstanceId")

echo "* waiting for firebox instance...see status check column in EC2 console"

aws ec2 wait instance-status-ok --instance-ids $fireboxinstanceid

echo "* firebox instance running"

Once the instance is running the Lambda function that connects to it can execute. Note that just checking the instance is running with the instance-running command will cause problems because the instance isn't actually ready to receive connections.

The above code lives in the following file: