Chr*_*uer 9 bash amazon-web-services aws-cloudformation
我正在使用bash脚本通过CLI和cloudformation模板创建AWS实例.我希望我的脚本等到实例创建完成后再继续我的脚本.现在,我每隔5秒钟使用一个while循环"describe-stacks",并在status ="CREATE_COMPLETE"或某些失败状态时断开循环.有谁知道更优雅的方式来做到这一点?
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
Run Code Online (Sandbox Code Playgroud)
Ec2-wait-instance-exists 似乎是您所需要的: http://docs.aws.amazon.com/cli/latest/reference/ec2/wait/instance-exists.html
我就是这样做的。实例启动后,我等待公共 IP:
INSTANCE_ID="$(aws ec2 run-instances --cli-input-json "${LAUNCH_SPEC}" | jq -r '.Instances[0].InstanceId')"
echo "Instance id ${INSTANCE_ID}"
while true; do
PUBLIC_IP="$(aws ec2 describe-instances --instance-ids ${INSTANCE_ID} | jq -r '.Reservations[0].Instances[0].PublicIpAddress')"
if [[ "${PUBLIC_IP}" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then break; fi
sleep 1
echo -n '.'
done
Run Code Online (Sandbox Code Playgroud)
之前定义的 LAUNCH_SPEC
aws cli为wait创建资源的大多数命令提供了一个子命令。对于您的方案,可以使用wait子命令来等待stack-create-complete事件:
aws cloudformation wait stack-create-complete --stack-name myStackName
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4487 次 |
| 最近记录: |