Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait in bash script until AWS instance creation is complete

I'm using a bash script to create an AWS instance via CLI and a cloudformation template. I want my script to wait until the instance creation is complete before I move on in my script. Right now, I'm using a while loop to "describe-stacks" every 5 seconds, and breaking out of the loop when the status = "CREATE_COMPLETE" or some failure status. Does anyone know of a more elegant way to do this?

stackStatus="CREATE_IN_PROGRESS"

while [[ 1 ]]; do
    echo "${AWS_CLI_PATH}" cloudformation describe-stacks --region "${CfnStackRegion}" --stack-name "${CfnStackName}"
    response=$("${AWS_CLI_PATH}" cloudformation describe-stacks --region "${CfnStackRegion}" --stack-name "${CfnStackName}" 2>&1)
    responseOrig="$response"
    response=$(echo "$response" | tr '\n' ' ' | tr -s " " | sed -e 's/^ *//' -e 's/ *$//')

    if [[ "$response" != *"StackStatus"* ]]
    then
        echo "Error occurred creating AWS CloudFormation stack. Error:"
        echo "    $responseOrig"
        exit -1
    fi

    stackStatus=$(echo $response | sed -e 's/^.*"StackStatus"[ ]*:[ ]*"//' -e 's/".*//')
    echo "    StackStatus: $stackStatus"

    if [[ "$stackStatus" == "ROLLBACK_IN_PROGRESS" ]] || [[ "$stackStatus" == "ROLLBACK_COMPLETE" ]] || [[ "$stackStatus" == "DELETE_IN_PROGRESS" ]] || [[ "$stackStatus" == "DELETE_COMPLETE" ]]; then
        echo "Error occurred creating AWS CloudFormation stack and returned status code ROLLBACK_IN_PROGRESS. Details:"
        echo "$responseOrig"
        exit -1
    elif [[ "$stackStatus" == "CREATE_COMPLETE" ]]; then
        break
    fi

    # Sleep for 5 seconds, if stack creation in progress
    sleep 5
done
like image 614
Christine Lindauer Avatar asked Feb 17 '15 14:02

Christine Lindauer


People also ask

How do I run a shell script in AWS command line?

If you want to use the aws-shell but haven't started it yet, start the aws-shell by running the aws-shell command. The aws> prompt is displayed. Create a bucket. Run the aws s3 mb command with the AWS CLI or s3 mb command with the aws-shell, supplying the name of the bucket to create.


1 Answers

The aws cli provides a wait subcommand for most of the commands that create resources. For your scenario, you can use the wait subcommand to wait for the stack-create-complete event:

aws cloudformation wait stack-create-complete --stack-name myStackName
like image 69
Patrick Crocker Avatar answered Oct 23 '22 03:10

Patrick Crocker