【问题标题】:Filter aws ec2 snapshots by current date按当前日期过滤 aws ec2 快照
【发布时间】:2019-08-20 14:11:18
【问题描述】:

如何按当天过滤 AWS EC2 快照?

我正在使用下面的 python 代码按标签:Disaster_Recovery 过滤快照,值为:Full,我还需要在当天过滤它。

import boto3
region_source = 'us-east-1'

client_source = boto3.client('ec2', region_name=region_source)

# Getting all snapshots as per specified filter
def get_snapshots():
    response = client_source.describe_snapshots(
        Filters=[{'Name': 'tag:Disaster_Recovery', 'Values': ['Full']}]
    )
    return response["Snapshots"]


print(*get_snapshots(), sep="\n")

【问题讨论】:

标签: python amazon-web-services aws-lambda boto3 snapshot


【解决方案1】:

通过下面的代码解决它:

import boto3
from datetime import date

region_source = 'us-east-1'
client_source = boto3.client('ec2', region_name=region_source)

date_today = date.isoformat(date.today())


# Getting all snapshots as per specified filter
def get_snapshots():
    response = client_source.describe_snapshots(
        Filters=[{'Name': 'tag:Disaster_Recovery', 'Values': ['Full']}]
    )
    return response["Snapshots"]


# Getting snapshots were created today
snapshots = [s for s in get_snapshots() if s["StartTime"].strftime('%Y-%m-%d') == date_today]

print(*snapshots, sep="\n")

【讨论】:

    【解决方案2】:

    这可以解决问题:

    
    import boto3
    from datetime import date
    
    region_source = 'us-east-1'
    
    
    client_source = boto3.client('ec2', region_name=region_source)
    
    # Getting all snapshots as per specified filter
    def get_snapshots():
        response = client_source.describe_snapshots(
            Filters=[{'Name': 'tag:Disaster_Recovery', 'Values': ['Full']}]
        )
        snapshotsInDay = []
        for snapshots in response["Snapshots"]:
           if(snapshots["StartTime"].strftime('%Y-%m-%d') == date.isoformat(date.today())):
               snapshotsInDay.append(snapshots)
        return snapshotsInDay
    
    print(*get_snapshots(), sep="\n")
    
    

    看完docs剩下的就是简单的日期对比

    【讨论】:

    • print(datetime.date.today()) 给出结果 2019-08-21 并且 ["StartTime"] 具有 2019-08-21 05:26:43.510000+00:00 格式,因此比较不匹配。
    • 在这种情况下,它将首先应用带有标签的过滤器,而不是在今天匹配“StartTime”,并打印所有快照,而不仅仅是今天创建的快照。为了解决这个问题,我猜return response["Snapshots"] 应该被替换为将收集当天快照的变量。
    • 是的,它部分不完整,我不知道你还想用这个函数做什么,但它只是创建一个列表并返回它。我会提出一个比你的更详细的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多