Want to update, create depending on the stack status and handling error
0
I want to create the stack if not exist and update the stack if its already there. While creation and updation I want to handle all different possible cases of stack being failed or rollbacks. Please help me to write robust code to manage all cases.
This is the one which I have written. It would be great if it becomes more better in terms of handling different cases.
wait() {
status=$(aws cloudformation describe-stacks --stack-name $PROJECT_NAME --query 'Stacks[0].StackStatus' --output text)
if [ "$status" = "UPDATE_IN_PROGRESS" ]; then
while [ "$status" = "UPDATE_IN_PROGRESS" ] || [ "$status" = "UPDATE_ROLLBACK_IN_PROGRESS" ]; do
if [ "$status" = "UPDATE_ROLLBACK_FAILED" ]; then
echo "Stack update failed. Rolling back changes."
aws cloudformation wait stack-delete-complete --stack-name $PROJECT_NAME
exit 1
elif [ "$status" = "ROLLBACK_FAILED" ]; then
echo "Stack is in ROLLBACK_FAILED state. Exiting."
exit 1
fi
aws cloudformation wait stack-update-complete --stack-name $PROJECT_NAME
status=$(aws cloudformation describe-stacks --stack-name $PROJECT_NAME --query 'Stacks[0].StackStatus' --output text)
done
else
aws cloudformation wait stack-create-complete --stack-name $PROJECT_NAME
fi
}
deploy-stack() {
if aws cloudformation describe-stacks --stack-name $PROJECT_NAME ; then
status=$(aws cloudformation describe-stacks --stack-name $PROJECT_NAME --query 'Stacks[0].StackStatus' --output text)
if [ "$status" = "UPDATE_ROLLBACK_COMPLETE" ] || [ "$status" = "CREATE_COMPLETE" ] || [ "$status" = "UPDATE_COMPLETE" ] || [ "$status" = "UPDATE_IN_PROGRESS" ] || [ "$status" = "UPDATE_ROLLBACK_IN_PROGRESS" ]; then
echo "Stack $PROJECT_NAME exists and is in progress. Started Updation of the resources."
update-stack
wait
elif [ "$status" = "ROLLBACK_COMPLETE" ]; then
echo "Stack $PROJECT_NAME is in ROLLBACK_COMPLETE state. Deleting the stack and creating it again."
delete-stack
aws cloudformation wait stack-delete-complete --stack-name $PROJECT_NAME
create-stack
wait
exit 0
elif [ "$status" = "ROLLBACK_FAILED" ]; then
echo "Stack $PROJECT_NAME is in ROLLBACK_FAILED state. Deleting the stack and creating it again."
echo "Deleting the stack"
delete-stack
aws cloudformation wait stack-delete-complete --stack-name $PROJECT_NAME
create-stack
wait
exit 0
else
echo "Stack $PROJECT_NAME exists and is not in progress. Skipping update."
fi
else
echo "Stack $PROJECT_NAME does not exist. Started creation"
create-stack
wait
fi
}