简体   繁体   中英

AWS RDS: how to get latest snapshot with boto3 and jmespath?

Here is what I tried:

#!/usr/bin/env python3
import boto3
import jmespath
from datetime import datetime, timedelta

now = datetime.utcnow()
yesterday = now - timedelta(days=1)

boto3.setup_default_session(profile_name='profilename')
rds_client = boto3.client('rds')

response = rds_client.describe_db_snapshots(DBInstanceIdentifier='instanseid')

snaplist=jmespath.search("DBSnapshots[?SnapshotCreateTime >`2016-10-24 06:11:30`].[DBSnapshotIdentifier]", response)

print(snaplist)

What I get is:

TypeError: unorderable types: datetime.datetime() < str()

I tried creating date (yesterday in the script) and passing it to jmepath search but I couldn't figure out how to pass that date object to the search. "+" doesn't work on datetime objects and if I convert it to sting with str() I return to the error posted above.

First, describe_db_snapshot response for SnapShotCreateTime is a datetime object.

'SnapshotCreateTime': datetime(2015, 1, 1)

So you are trying to compare datetime with string. To fix it, you need to convert the string to datetime or vice-versa.

search_date = datetime.strptime('2016-10-24 06:11:30', '%Y-%m-%d %H:%M:%s')
snaplist=jmespath.search(
    "DBSnapshots[?SnapshotCreateTime > search_date].[DBSnapshotIdentifier]",
    response)

You should be able to query similar stuff using AWS CLI that implement JMESpath, however AWS CLI already taken care of the string conversion. And the date value must be embraced in `backticks`.

More reading : Use filter "launch-time" to find all instances newer than X date

aws rds describe-db-snapshots --query 'DBSnapshots[?SnapshotCreateTime >`2016-10-24 06:11:30`].[DBSnapshotIdentifier]'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM