python-3.x - 试图查找过去一小时内创建的任何 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()
解决方案
你的功能:
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):
推荐阅读
- c# - 在不使用 (Table-Valued-Parameter) 类型的情况下将集合作为 SQL 参数添加到 SqlCommand
- ag-grid - 如何禁用 ag-grid 的右键单击/上下文菜单?
- azure - Azure 文本转语音服务返回 401 Unauthorized
- node.js - dynamo db 从内部数组中获取数据
- regex - 用正则表达式替换数组宏
- sas - SAS中只输出ROC曲线
- css - 如何设置 XML 驱动的 URL 的样式
- ruby - 如何向 Edge/IE WebDriver 传递/创建虚假媒体流?
- android - 如何检查recyclerView中是否存在新添加的项目?
- hyperledger-fabric - 无法将 Hyperledger Fabric Marbles 链代码从存储库安装到对等点