aws cli query to find the last snapshot taken, the date it was taken, the tag used if any, the name tag of the instance and the instance i.d

Viewed 1586

I need to get 5 colums reported from awscli. These are, last snapshot taken for instance, the date it was taken, the tag used if any, the name tag of the instance and the instance i.d.

The below will list ALL snapshots and the time taken and a 'null' name gets reported...

aws ec2 describe-snapshots --query 'Snapshots[*].{ID:SnapshotId,Time:StartTime,Name:Tags[?Key==`Name`]|[0].Value}'

This will give me the description of the snapshot, the snap id and the date:

 aws ec2 describe-snapshots --owner self --output json | jq '.Snapshots[] | select(.StartTime < "'$(date --date='-1 month' '+%Y-%m-%d')'") | [.Description, .StartTime, .SnapshotId]'

So basically I have something that gives me the snapshot data, will query on date and tell me what time it was taken but I'm missing the full requirement all in one.

I guess the main stumbling block for me is how to only report on the last snapshot that was taken for an instance. Can anyone please help?

1 Answers

You can use sort_by get the latest snapshot.

aws ec2 describe-snapshots  --query "sort_by(Snapshots, &StartTime)[-1].{SnapshotId:SnapshotId,StartTime:StartTime}"

output

{
    "SnapshotId": "snap-123456", 
    "StartTime": "2020-07-07T13:57:05.982Z"
}

OR if you just looking for owned by you then

MY_ACCOUNT_ID=1234567 aws ec2 describe-snapshots  --filter "Name=owner-id,Values=$MY_ACCOUNT_ID" --query "sort_by(Snapshots, &StartTime)[-1].{SnapshotId:SnapshotId,StartTime:StartTime}"

aws-snapshot-by-me

Update:

As the above query does not contain instance information, so you can get instance information by doing a reverse query. find snapshot first and then find instance ID using attached volume ID.

VOLUME_ID=$(aws ec2 describe-snapshots --filter "Name=owner-id,Values=$MY_ACCOUNT_ID"  --query "sort_by(Snapshots, &StartTime)[-1].VolumeId" --output text)
aws ec2 describe-volumes --filter "Name=volume-id,Values=$VOLUME_ID" --query 'Volumes[?Attachments != `null`].Attachments[].InstanceId'
Related