列出在特定日期拍摄的所有EC2 EBS快照

时间:2018-06-27 21:23:20

标签: amazon-web-services amazon-ec2 boto3 aws-cli amazon-ebs

我正在尝试列出在特定日期拍摄的所有EBS卷快照,以便我可以通过bash脚本跨区域自动执行副本以更好地进行灾难恢复 我还有另一个bash脚本,可以创建所有正在使用的EBS卷的快照,并删除所有早于30天的快照。我需要将以前日期拍摄的所有内容复制到另一个区域。

我尝试了许多jmespath开关(不提供任何输出),其中一些是:-

$aws ec2 describe-snapshots --query 'Sanpshots[?StartTime >= `2018-06-25`]|[?StartTime <= `2018-06-27`]'
$aws ec2 describe-snapshots --query 'Sanpshots[?StartTime == `2018-06-25`]

我浏览了许多页面,但找不到特定的日期列表。 请提出一些开关,分类方法,链接或其他建议。 谢谢。

2 个答案:

答案 0 :(得分:3)

鉴于您将需要某种编程方式来计算“ 30天前”,因此最好采用一种编程语言,例如:

import boto3
import pytz
from datetime import datetime, timedelta

# Get my AWS Account ID
myAccount = boto3.client('sts').get_caller_identity()['Account']

# Connect to EC2
client = boto3.client('ec2', region_name = 'ap-southeast-2')

# Get a list of snapshots for my AWS account (not all public ones)
snapshots = client.describe_snapshots(OwnerIds=[myAccount])['Snapshots']

# Find snapshots more than 30 days old
oldest_date = datetime.now(pytz.utc) - timedelta(days=30)
old_snapshots = [s for s in snapshots if s['StartTime'] < oldest_date]

# Delete the old snapshots
for s in old_snapshots:
  client.delete_snapshot(SnapshotId = s['SnapshotId'])

答案 1 :(得分:1)

我从文档右边here.看了JMESpath开关 因此,为了搜索特定日期,我应用了一个在两个日期之间进行搜索的开关。例如:-

'Snapshots[?(StartTime >= `2018-06-27`) && (StartTime <= `2018-06-28`)]

为什么“ ==”在用于完全匹配字符串的开关中不起作用。

所以完整的字符串是:-

aws ec2 describe-snapshots --query 'Snapshots[?(StartTime >= `2018-06-27`) && (StartTime <= `2018-06-28`)].{ID:SnapshotId,ST:StartTime}' --output text --region $regionname