首页 > 解决方案 > 试图查找过去一小时内创建的任何 AMI

问题描述

我们经常为部署构建新的 AMI。我正在尝试编写一些东西来返回我们的帐户在过去一小时内创建的任何 AMI 的列表。这样做的原因是,在我们确定所有 AMI 都已创建之前,我们无法启动部署。

我有一个查找 AMI 的功能,只是坚持弄清楚如何将搜索范围缩小到仅在过去 60 分钟内创建的 AMI。我正在使用的是我创建的另一个 lambda,用于查找过去 30 天内创建的任何 AMI。它不会缩小到我可以告诉的时间,这是我可以使用一些帮助的地方。

#!/usr/bin/env python3

import boto3
import datetime

age = 1
aws_profile_name = 'default'

current_images = []

# Functions to calculate age for AMI's and Snapshots. 
def ami_days_old(date):
    lastHourDateTime = datetime.datetime.now() - datetime.timedelta(hours = 1)
    return lastHourDateTime

# Setup boto3 client connections
boto3.setup_default_session(profile_name = aws_profile_name)
ec2 = boto3.client('ec2')

# Filter on what to search for in order to grab just OUR images and snapshots
custom_filter = [{
    'Name':'<redacted>', 
    'Values': ['<redacted>']}]

def get_recent_images():
    amis = ec2.describe_images(Owners=['self'], Filters=custom_filter)
    for ami in amis['Images']:
        create_date = ami['CreationDate']
        location = ami['ImageLocation']
        ami_id = ami['ImageId']
        # print ami['ImageId'], ami['CreationDate']
        day_old = ami_days_old(create_date)
        if day_old > age:
            try:

                print("deleting -> " + ami_id + " - create_date = " + create_date + " as image is " + str(day_old)  + " old.")
                # deregister the AMI
                #ec2.deregister_image(ImageId=ami_id)
            except:
                print("can't delete " + ami_id)

def main():
    get_recent_images()
    print(get_recent_images())

main()

标签: python-3.xamazon-web-servicesamazon-ec2

解决方案


你的功能:

def ami_days_old(date):
    lastHourDateTime = datetime.datetime.now() - datetime.timedelta(hours = 1)
    return lastHourDateTime

正在传递一个date参数,但您的代码没有使用它!相反,它返回 1 小时前的时间戳,但您的代码需要一个年龄?

age = 1
...
        create_date = ami['CreationDate']
        ...
        if day_old > age:

所以,你的代码都混在一起了!

尝试这个:

from datetime import datetime, timedelta, timezone
...

  if ami['CreationDate'] > datetime.now(tz=timezone.utc) - timedelta(hours=1):

推荐阅读