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 get_value.sh) 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/get_value.sh 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:
https://github.com/tradichel/PacketCaptureAWS/blob/master/code/execute/action.sh