Search code examples
amazon-web-servicesamazon-ec2aws-clijmespath

AWS CLI describe-snapshots to print SnapshotId


I am trying to print the SnapshotId for the newest snapshot using bash. Here is my command:

aws ec2 describe-snapshots | grep TestVolume1 |head -n 1| > Output.txt

Above result matches TestVolume1 to write to Output.txt the newest snapshot. I also want to print the SnapshotID and am struggling to output that to Output.txt.

I have tried awk and --filter and that does not help. Would appreciate any help with syntax to output SnapshotId. What else can I use?


Solution

  • You can use --filter argument to retrieve only the matched snapshots and use --query argument to parse the required field from the response,

    Update (adding reverse sort of snapshots based on snapshot start time):

    aws ec2 describe-snapshots --filters Name=description,Values="*TestVolume1*" --query "reverse(sort_by(Snapshots, &StartTime))[0].SnapshotId"
    

    The filter is applied on the description of the snapshot expecting it to contain the desired text (TestVolume1).