确定亚马逊EC2实例的创建日期/时间

17
5个回答

10

EC2实例中没有名为create_time的属性,只有launch_time可用。

然而,您可以使用以下Python代码来了解卷创建的时间,这反过来可以给您实例创建的时间(请注意,我是在谈论创建实例时附加的卷):

import boto3
ec2 = boto3.resource('ec2', region_name='instance_region_name')
volume = ec2.Volume('vol-id')
print volume.create_time.strftime("%Y-%m-%d %H:%M:%S")

另一种选择是使用自定义代码。当您使用create_instances()创建实例时,您可以记录给定实例的launch_time以及其实例ID和名称到类似DynamoDB的某个位置,以便在任何时候使用实例ID检索“创建时间”。


如果有区别的话,这个时间与AWS控制台中显示的附件时间有何不同? - Zachary Ryan Smith
@ZacharyRyanSmith 在AWS控制台中显示的时间是“启动时间”,而不是“实例创建时间”,请注意两者不一定相同。如果您在中途停止实例并重新启动它,则启动时间将与实例创建时间不同。 - Venkatesh Wadawadagi
@ZacharyRyanSmith AWS控制台显示的时间是“启动时间”,而不是“实例创建时间”,请注意两者不一定相同。如果您在中间停止实例并重新启动它,启动时间将与实例创建时间不同。 - undefined

8
假设您正在使用基于EBS的实例并且没有进行任何高级磁盘操作,查找实例创建日期最好的方法是查看磁盘根卷的创建时间。 虽然每次停止和启动实例时实例的启动时间都会更改,但是EBS卷的创建时间是静态的。
以下是一个快速脚本,可用于查找当前运行实例的创建时间:
import boto
import subprocess

instance_id = subprocess.check_output(['curl', '-s', 'http://169.254.169.254/latest/meta-data/instance-id'])

conn = boto.connect_ec2()

root_device = conn.get_instance_attribute(instance_id, 'rootDeviceName')['rootDeviceName']
root_vol = conn.get_all_volumes(filters={"attachment.instance-id": instance_id, "attachment.device": root_device})[0]

print root_vol.create_time

请注意,这需要实例的IAM角色具有ec2:DescribeInstanceAttributeec2:DescribeVolumes权限。


3

无法直接获取EC2实例的创建时间。因为EC2实例的启动时间会在每次启动和停止实例时更新。

我们可以通过两种方式获取实例的创建时间:

1)通过获取实例的网络接口附加时间

2)通过获取上述卷的附加时间。

如何在boto3中获取网络接口附加时间

import boto3
from datetime import datetime
instance_details = client.describe_instances()
num_ins=(len(instance_details['Reservations'])
for x in range(num_ins):


   InstanceID=(instance_details['Reservations'][x]['Instances'][0]['InstanceId'])
   NetworkInterfaceID = (instance_details['Reservations'][x]['Instances'][0]['NetworkInterfaces'][0]['NetworkInterfaceId'])
   NetworkInterface_details = client.describe_network_interfaces(NetworkInterfaceIds=[NetworkInterfaceID])
   networkinterface_id_attachedtime = NetworkInterface_details['NetworkInterfaces'][0]['Attachment']['AttachTime']

   print(networkinterface_id_attachedtime)

打印实例所附加的网络接口时间。


0

如下所示:

http://boto.readthedocs.org/en/latest/ref/ec2.html#module-boto.ec2.instance

每个实例对象都有一个名为launch_time的属性,其中包含一个IS08601日期时间字符串,表示实例启动的时间。
在boto中,您可以这样做:
import boto.ec2

conn = boto.ec2.connect_to_region('us-west-1')
reservations = conn.get_all_instances()
for r in reservations:
    for i in r.instances:
        print('%s\t%s' % (i.id, i.launch_time)

1
但是这是否与创建时间相同呢?我对启动时间和创建时间感到困惑。 :( - megazoe
1
也许我对你所寻找的内容感到困惑。启动时间将告诉您该特定实例实际启动的时间。就像虚拟机被启动并开始引导时一样。这是你要找的吗? - garnaat
14
实际上不是相等的。如果你启动一个实例,过夜停止它,第二天早上再启动它,那么启动时间将会是当天早上的日期,而不是你第一次创建实例时的日期。 - npiani
据我所知,创建时间并未存储在实例元数据中。 - alko

0
如果您想根据 EC2 实例的启动时间计算当前的正常运行时间,可以尝试以下方法:
import datetime
lt_datetime = datetime.datetime.strptime(i.launch_time, '%Y-%m-%dT%H:%M:%S')
lt_delta = datetime.datetime.utcnow() - lt_datetime
uptime = str(lt_delta)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接