有没有办法轻松找出EC2实例上次停止的时间?通过查看ec2.get_only_instances()
变量,我可以从launch_time
获取启动时间。但是,它看起来好像停止时间存储在任何元数据中。
我们可能会使用rc#.d
脚本来实现此功能,但我只是想知道是否可以通过boto
获取该信息。
答案 0 :(得分:8)
您可以使用reason
个实例的stopped
变量:
import boto.ec2
conn = boto.ec2.connect_to_region("eu-west-1")
reservations = conn.get_all_instances()
for r in reservations:
for i in r.instances:
if i.state == 'stopped':
print "%s [%s] %s" % (i.id, i.state, i.reason)
输出:
i-11223344 [stopped] User initiated (2013-12-20 13:59:08 GMT)
这也适用于terminated
个实例(只要它们仍然显示)。
答案 1 :(得分:2)
我认为更好的做法是:
import boto.ec2
conn = boto.ec2.connect_to_region("eu-west-1")
reservations = conn.get_all_instances()
instances = []
for reservation in reservations:
for instance in reservation.instances:
if "Name" in instance.tags.keys():
instances.append((instance.tags["Name"],
instance.get_console_output().timestamp))
您也可以替换if
并获取所需内容,但instance.get_console_output().timestamp
是获取实例已停止时间戳的正确方法
答案 2 :(得分:1)
请看这个,它返回ec2名称中的时间戳,它在aws停止并且颜色为红色。请注意,在运行之前设置包含凭证的aws配置文件环境。
import boto.ec2
class i_color:
red = '\033[31m'
reset = '\033[0m'
def name(i):
if 'Name' in i.tags:
n = i.tags['Name']
n = i_color.red + n + i_color.reset
return n
conn = boto.ec2.connect_to_region("us-east-1")
reservations = conn.get_all_instances()
for r in reservations:
for i in r.instances:
if i.state == 'stopped':
print "%s [%s] %s" % (name(i),i.state,i.reason)
示例输出:
test-ec2-temp05 [stopped] User initiated (2016-08-02 09:00:43 GMT)
答案 3 :(得分:0)
代码:
import boto3
from prettytable import PrettyTable
cli = boto3.client('ec2')
resp = cli.describe_instances(
Filters=[
{
'Name': 'instance-state-name',
'Values': [
'stopped',
]
},
],
MaxResults=1000,
)
table = PrettyTable()
table.field_names = ["Name", "ID", "State", "Reason"]
for r in resp["Reservations"]:
for i in r["Instances"]:
name = ''
for t in i["Tags"]:
if t["Key"] == "Name":
name = t["Value"]
table.add_row([name, i["InstanceId"], i["State"]["Name"],
i["StateTransitionReason"]])
print(table.get_string(sortby="Reason"))
输出:
+-------------------+---------------------+---------+------------------------------------------+
| Name | ID | State | Reason |
+-------------------+---------------------+---------+------------------------------------------+
| server-name-tag-1 | i-0a12b3056c789012a | stopped | User initiated (2017-02-27 20:20:00 GMT) |
| server-name-tag-2 | i-1b12b3956c789012b | stopped | User initiated (2018-02-27 20:20:00 GMT) |
| server-name-tag-3 | i-2c12b3856c789012c | stopped | User initiated (2019-02-27 20:20:00 GMT) |
| server-name-tag-4 | i-3d12b3756c789012d | stopped | User initiated (2020-02-27 20:20:00 GMT) |
+-------------------+---------------------+---------+------------------------------------------+