Search code examples
aws-clijmespath

JMES Path: Exclude top 5 records from AWS CLI results


I would like to get the list of available snapshots for an RDS instance using AWS CLI.

I could get all the snapshots in descending order by the time they're created using this query:

aws rds describe-db-snapshots --db-instance-identifier sample-db \
 --query="(reverse(sort_by(DBSnapshots[?SnapshotType=='manual'], &SnapshotCreateTime)))[*].{DBSnapshotIdentifier: DBSnapshotIdentifier, DBSnapshotARN: DBSnapshotArn, SnapshotCreateTime: SnapshotCreateTime}" \
 --no-paginate --output json

I could also get the top 5 records from this query by replacing [*] with [:5]:

aws rds describe-db-snapshots --db-instance-identifier sample-db \
 --query="(reverse(sort_by(DBSnapshots[?SnapshotType=='manual'], &SnapshotCreateTime)))[:5].{DBSnapshotIdentifier: DBSnapshotIdentifier, DBSnapshotARN: DBSnapshotArn, SnapshotCreateTime: SnapshotCreateTime}" \
 --no-paginate --output json

However, I would like to get all the records excluding top 5. I would appreciate any inputs on JMES Path on how could I achieve this.


Solution

  • What you are looking to achieve is called slicing, and you where actually pretty close with your trial to a solution.

    The slicing syntax of JMESPath is borrowed from the Python world and is as follow:

    This syntax introduces Python style array slicing that allows a start position, stop position, and step. This syntax also proposes following the same semantics as python slices.

    [start:stop:step]

    Each part of the expression is optional. You can omit the start position, stop position, or step. No more than three values can be provided in a slice expression.

    The step value determines how my indices to skip after each element is plucked from the array. A step of 1 (the default step) will not skip any indices. A step value of 2 will skip every other index while plucking values from an array. A step value of -1 will extract values in reverse order from the array. A step value of -2 will extract values in reverse order from the array while, skipping every other index.

    Source: https://jmespath.org/proposals/array-slices.html#syntax

    So your query should read [5:], to indicate that you want the slice to start after the fifth element, ending up with:

    aws rds describe-db-snapshots --db-instance-identifier sample-db \
     --query="(reverse(sort_by(DBSnapshots[?SnapshotType=='manual'], &SnapshotCreateTime)))[5:].{DBSnapshotIdentifier: DBSnapshotIdentifier, DBSnapshotARN: DBSnapshotArn, SnapshotCreateTime: SnapshotCreateTime}" \
     --no-paginate --output json