【问题标题】:how to find out when an EC2 instance was last stopped如何找出 EC2 实例上次停止的时间
【发布时间】:2014-01-18 05:22:06
【问题描述】:

有没有一种方法可以轻松找出 EC2 实例上次停止的时间?通过查看launch_time 变量,我可以从ec2.get_only_instances() 获得启动时间。但是,停止时间似乎没有存储在任何元数据中。

我们可能会使用rc#.d 关闭脚本来实现此功能,但我只是想知道是否可以通过boto 获得该信息。

【问题讨论】:

    标签: python amazon-ec2 boto


    【解决方案1】:

    您可以使用stopped 实例的reason 变量:

    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 实例(只要它们仍然显示)。

    【讨论】:

    • 看起来不错。谢谢。
    • 是否存在不打印时间戳的已知情况?它对我来说效果很好,只是它在User initiated 之后结束打印并且它没有为我提供时间戳。
    【解决方案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 是获取实例停止时间戳的正确方法

    【讨论】:

    • 这种方法是唯一允许正确获取时间戳的方法。
    【解决方案3】:

    请看这个,它返回 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)
    

    【讨论】:

      【解决方案4】:

      代码:

      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) |
      +-------------------+---------------------+---------+------------------------------------------+
      

      【讨论】:

        猜你喜欢
        • 2021-03-15
        • 1970-01-01
        • 2015-11-15
        • 1970-01-01
        • 2014-09-02
        • 2017-05-05
        • 1970-01-01
        • 1970-01-01
        • 2013-10-30
        相关资源
        最近更新 更多