如何在 bash 脚本中等待 AWS 实例创建完成

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

我正在使用 bash 脚本通过 CLI 和 cloudformation 模板创建 AWS 实例。我希望我的脚本等到实例创建完成后再继续我的脚本。现在,我每 5 秒使用一个 while 循环到 "describe-stacks",并在状态 = "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

Ec2-wait-instance-exists 似乎是您所需要的: http://docs.aws.amazon.com/cli/latest/reference/ec2/wait/instance-exists.html

我就是这样做的。实例启动后,我等待 public 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

LAUNCH_SPEC 先前定义

aws cli 为大多数创建资源的命令提供了一个 wait 子命令。对于您的场景,您可以使用 wait 子命令等待 stack-create-complete 事件:

aws cloudformation wait stack-create-complete --stack-name myStackName

下面是一个通用的"check_status"函数。用于多项操作,例如检查堆栈是否已部署或 EKS 集群是否已启动以及是否已将节点添加到其中。

check_status() {

    max_tries=""
    test_command=""
    required_value=""
    error=""

    ok="false"
    for i in `seq 1 $max_tries`; do
        return_value=$(eval ${test_command})
        if [ "$return_value" == "$required_value" ]; then
            ok="true"
            break
        else
            echo -n "."
        fi
        sleep 5
    done
    if [ "$ok" == "false" ]; then
        printf "\n\e[31mERROR:\e[0m $error\n"
        exit 1
    fi 
}

check_vpc() {
    echo "Waiting for stack status..."
    vpc_stack_status="aws cloudformation describe-stacks --stack- 
    name=${vpc_stack_name} --query 'Stacks[0].StackStatus' --output text"
    msg="Stack creation failed - giving up"
    check_status "100" "$vpc_stack_status" "CREATE_COMPLETE" "$msg"
    [[ $? == "0" ]] && echo "VPC stack deployed successfully"
}