7

Using the aws-cli client (https://github.com/aws/aws-cli), is there a way to find instances using a date range filter? Or using an "earlier than X date" or "last X days" filter?

It seems that the only date-related filter is to specify an exact date, or a partial date with string wildcards. For example, I've found that specifying a date as follows works:

aws ec2 describe-instances --filters "Name=launch-time,Values=2015-03\*"

For example, that gets all instances launched in March, 2015.

What I want is equivalent to this POSIX "find" command, "find all things from last 30 days":

find . -mtime -30
JDS
  • 2,598
  • 4
  • 30
  • 49

2 Answers2

19

Found on Use filter "launch-time" to find all instances newer than X date? using JMESPath query:

aws ec2 describe-instances --query 'Reservations[].Instances[?LaunchTime>=`2015-03-01`][].{id: InstanceId, type: InstanceType, launched: LaunchTime}'
John Rotenstein
  • 871
  • 7
  • 16
  • One difference between `--filters` and `--query` is where it executes. `--filters` execute at the server, whereas --query executes in the client. Imagine you have 100 instances and 10 match the condition. If you can use --filters, your query will return 10 matching instances. If you use --query, 100 instances come back from the call to the EC2 API, then some python code in the AWS CLI tool does the matching to have only 10 come out in input. This matters for needle-in-haystack cases where there are 1000s of resources that have to be filtered. – Paco Hope Feb 23 '23 at 13:55
3

You cant, but to do it in python using the boto library do like this, for example, to list the instances in aws region "eu-west-1" launched more than 30 days ago.

import boto.ec2
import datetime
from dateutil import parser
conn = boto.ec2.connect_to_region('eu-west-1')
reservations = conn.get_all_instances()
for r in reservations:
    for i in r.instances:
        launchtime = parser.parse(i.launch_time)
        launchtime_naive = launchtime.replace(tzinfo=None)
        then = datetime.datetime.utcnow() + datetime.timedelta(days = -30)
        if launchtime_naive < then:
            print i.id
Sirch
  • 5,785
  • 4
  • 20
  • 36
  • holy, cow, that is nearly exactly the solution I settled on. "use boto, and do the filtering myself" – JDS Mar 10 '15 at 17:32