首页 > 解决方案 > 我如何在 python 中列出 30 天以上的 aws 安全组?

问题描述

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

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

解决方案


安全组没有“创建日期”的概念,也没有任何日期。

理论上,您可以通过 AWS Config 中的安全组历史记录来获取此信息。

始终查看文档以查看可用的字段。


推荐阅读