boto3 问题检查 ec2 实例状态

boto3 issue checking ec2 instance state

所以我有这个启动 ec2 实例的 boto3 脚本。但是当我 运行 这个 lambda 函数时,函数 describe_instance_status returns 空白 InstanceStatus 数组。所以程序终止,在说索引我们的范围之后。有什么建议吗?

import boto3
from time import sleep
region = 'your region name'


def lambda_handler(event, context):

 cye_production_web_server_2 = 'abcdefgh'

 ec2 = boto3.client('ec2',region)

 start_response = ec2.start_instances(
    InstanceIds=[cye_production_web_server_2, ],
    DryRun=False
 )

 print(
    'instance id:',
    start_response['StartingInstances'][0]['InstanceId'],
    'is',
    start_response['StartingInstances'][0]['CurrentState']['Name']
 )

 status = None
 counter = 5
 while (status != 'ok' and counter > 0):
    status_response = ec2.describe_instance_status(
        DryRun=False,
        InstanceIds=[cye_production_web_server_2, ],
    )
    status = status_response['InstanceStatuses'][0]['SystemStatus']      ['Status']
    sleep(5)    # 5 second throttle
    counter=counter-1

 print(status_response)
 print('status is', status.capitalize())

默认情况下,仅描述 运行 个实例,除非另有说明。

实例进入 运行 状态可能需要几分钟时间。

您的程序永远不会休眠,因为它在前面的步骤中失败了,在第一次迭代中实际上没有返回状态。

使用"IncludeAllInstances",这是一个布尔请求参数,当为真时,包括所有实例的健康状态。如果为 false,则仅包括 运行 个实例的健康状态。默认为 false

正如 omuthu 所提到的,默认的 return 类型仅提供有关实例的 运行 状态的信息。要获得瞬间的其他状态,请将 describe_instance_status() 的“IncludeAllInstances”参数设置为 True。