按当前日期过滤 aws ec2 快照

Filter aws ec2 snapshots by current date

如何按当天筛选 AWS EC2 快照?

我使用下面的 python 代码按 tag:Disaster_Recovery 和 value: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")

这可以解决问题:


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剩下的就是简单的日期比较

解决,代码如下:

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")