问题
Is there a way to check if an AWS instance has finally come up in python either using boto3 or otherwise. The running state doesnt differentiate between rebooting and finally up phase.
回答1:
If you just want to check that a remote port is open you could use the built-in socket package.
Here's a quick modification of this answer of waiting for a remote port to open:
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)
回答2:
All the info is available inside boto3 documentation http://boto3.readthedocs.org/en/latest/reference/services/ec2.html
This will show all the information of the instances.
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"])
From the documentation :
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.
In fact, there is no code state show "rebooting" inside the documentation. I can't really test it out on my own EC2 instances , because after I do reboot, it seems the instances reboot so fast that AWS console doesn't have a chance to show a "Rebooting" state.
Nevertheless, 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
回答3:
You could also use the InstanceStatusOk waiter in boto3 or whatever waiter is approprate.
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'!")
来源:https://stackoverflow.com/questions/36590699/to-check-whether-aws-instance-is-up-after-reboot-using-python