skip to Main Content

I’m still trying to understand how to use JQ to get what I want. I want to get the size of all snapshots in my account older than a specific date and then add them up so that I can calculate cost. I am able to do this without the date filtering with this.

aws ec2 describe-snapshots --profile my_profile_name | jq "[.Snapshots[].VolumeSize] | add"

This returns a numerical value. Without JQ, I’m also able to get a list of snapshots using "query" but I don’t think that will be applied when using JQ but I could be wrong.

aws ec2 describe-snapshots --profile my_profile_name --owner-ids self --query "Snapshots[?(StartTime<='2022-09-08')].[SnapshotId]"

I tried various arrangements using "select" along with my first example. However, I haven’t been able to get anything returned yet. I appreciate any pointers.

This is the "select" that doesn’t quite work.

aws ec2 describe-snapshots --profile my_profile_name | jq "[.Snapshots[]select(.StartTime < "2022-09-08")] | [.Snapshots[].VolumeSize] | add"

Edit 11/15/22

I was able to make progress and I found a site that allows you to test JQ. The example is able to select strings and numbers, but I’m having trouble with the date part. I don’t understand how to interrupt the date in the format that AWS provides. I can do the add part, I removed it to simplify the example.

This the the working "select" for a string. I can only do greater/less than when I use numbers and remove the quotes from the JSON section.

.Snapshots[] | select(.StartTime == "2022-11-14T23:28:39+00:00") | .VolumeSize

jq play example

2

Answers


  1. It would appear that the jq expression you’re looking for is:

    [.Snapshots[] | select(.StartTime < "2022-09-08") | .VolumeSize] | add
    

    Without an illustrative JSON, however, it’s difficult to test this out; that’s one of the reasons for the mcve guidelines.

    Login or Signup to reply.
  2. A solution without jq is this:

    aws ec2 describe-snapshots 
        --owner-ids self 
        --query "sum(Snapshots[?StartTime < '2022-11-12'].VolumeSize)"
    

    But note that the comparison is not done "by date" but by literally comparing strings like 2016-11-02T01:25:28.000Z with 2022-11-12.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search