使用 python 检查重启后 AWS 实例是否启动

To check whether AWS instance is up after reboot using python

有没有办法使用 boto3 或其他方式检查 AWS 实例是否最终出现在 python 中。 运行 状态不区分重新启动和最终启动阶段。

如果您只想检查远程端口是否打开,您可以使用内置的 socket 包。

这里是等待远程端口打开的 this answer 的快速修改:

import socket
import time

def wait_for_socket(host, port, retries, retry_delay=30):
    retry_count = 0
    while retry_count <= retries:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((host, port))
        sock.close()
        if result == 0:
            print "Port is open"
            break
        else:
            print "Port is not open, retrying..."
            time.sleep(retry_delay)

boto3 文档中提供了所有信息 http://boto3.readthedocs.org/en/latest/reference/services/ec2.html

这将显示实例的所有信息。

import boto3
reservations = boto3.client("ec2").describe_instances()["Reservations"]
for reservation in reservations:
  for each in reservation["Instances"]:
    print " instance-id{} :  {}".format(each["InstanceId"], each["State"]["Name"])

# or use describe_instance_status, much simpler query
instances = boto3.client("ec2").describe_instance_status()
for each in instances["InstanceStatuses"]: 
  print " instance-id{} :  {}".format(each["InstanceId"], each["InstanceState"]["Name"])

来自文档:

State (dict) --

The current state of the instance.

Code (integer) --

The low byte represents the state. The high byte is an opaque internal value and should be ignored.

0 : pending
16 : running
32 : shutting-down
48 : terminated
64 : stopping
80 : stopped
Name (string) --

The current state of the instance.

事实上,文档里面并没有code state show "rebooting"。我无法在我自己的 EC2 实例上真正测试它,因为在我重新启动后,实例似乎重新启动得如此之快以至于 AWS 控制台没有机会显示 "Rebooting" 状态。

尽管如此,http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html

The following are examples of problems that can cause instance status checks to fail:

Failed system status checks

Incorrect networking or startup configuration

Exhausted memory

Corrupted file system

Incompatible kernel

你也可以用InstanceStatusOk waiter in boto3 or whatever waiter是合适的。

import boto3

instance_id = '0-12345abcde'

client = boto3.client('ec2')
client.reboot_instances(InstanceIds=[instance_id])

waiter = client.get_waiter('instance_status_ok')
waiter.wait(InstanceIds=[instance_id])

print("The instance now has a status of 'ok'!")