Eloise
Eloise

Reputation: 89

Filtering EC2 instances older than 24 hours using boto3 and python

I want to search for EC2 instances older than 24 hours old, so that I can clear down only the instances that are likely not being used by anyone for testing.

I'm able to filter for instances spun up on a date, or if I just specify the year I can search for all instances created that year. But I can't find out how to filter instances which were spun up before a given date. Here's what I have:

    session = get_aws_session()
    ec2 = session.resource("ec2", region_name=REGION)
    ssm = session.client("ssm")

    instances = list(
        ec2.instances.filter(
            Filters=[
                {"Name": "tag:Environment", "Values": ["test"]},
                {"Name": "launch-time", "Values": ["2021-09-21*"]},
            ]
        )
    )

Upvotes: 0

Views: 1651

Answers (2)

Eloise
Eloise

Reputation: 89

This is what solved my problem:

    session = get_aws_session()
    ec2 = session.resource("ec2", region_name=REGION)
    ssm = session.client("ssm")

    instances = list(
        ec2.instances.filter(
            Filters=[
                {"Name": "tag:Environment", "Values": ["test"]},
                {"Name": "instance-state-name", "Values": ["running"]},
            ]
        )
    )

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

    instances_over_24hours_old = list(
        filter(lambda instance: instance.launch_time.timestamp() < yesterday, instances)
    )

Note: the ec2 launch_time value doesn't have time zone information, so I just used the timestamp property

Upvotes: 1

Coin Graham
Coin Graham

Reputation: 1584

You can't filter on when the instances were created, only when they were last "launched" (which is the last time they were started). The best bet for finding the created date for instances is to use the root disk. Check out this for more information on that strategy.

Upvotes: 2

Related Questions