import boto3
from datetime import datetime
ec2res = boto3.resource('ec2')
ec2cli = boto3.client('ec2')
now = datetime.now()
def calculator(launch_date, object):
age = now - launch_date
intage = int(age.days)
if intage <= 30:
print(object)
list_security_groups = ec2cli.describe_security_groups()
for security_group in list_security_groups['SecurityGroups']:
launch_date = datetime.strptime(security_group['CreationDate'].strftime("%Y-%m-%d %H:%M:%S.%f"), "%Y-%m-%d %H:%M:%S.%f")
intage = calculator(launch_date,security_group)
或
list_security_groups = ec2res.security_groups.all()
for security_group in list_security_groups:
launch_date = datetime.strptime(security_group.launchtime.strftime("%Y-%m-%d %H:%M:%S.%f"), "%Y-%m-%d %H:%M:%S.%f")
intage = calculator(launch_date,security_group)
这些格式适用于其他aws对象,但是我得到了安全组的KeyError
对于安全组,没有“创建日期”的概念,也没有任何日期。
理论上,您可以浏览AWS Config中安全组的历史记录以获取此信息。
总是查看文档以查看可用的字段。