QBits
QBits

Reputation: 141

How to filter tag values of an Ec2 Instance by a date in Boto3

I am trying to get instances that have tag name 'ttl' and tag values 'older than today'. Our users tag their instances based on a future date (yyyy.mm.dd) so that the script should not automatically delete them before that date. The filter below should be able to get only instances whose tag-value is smaller than today's date. Is there a way to filter the tage values based on this logic -> get me instances that are < today ?

today = = datetime.today().strftime('%Y.%m.%d')

filters = [{'Name': 'tag:ttl','Values': ['<today']},{'Name': 'instance-state-name','Values': ['running']}]

The full code looks like this:

import boto3
import logging

#setup simple logging for INFO

logger = logging.getLogger()
logger.setLevel(logging.INFO)

#define the connection

ec2 = boto3.resource('ec2')
def lambda_handler(event, context):

filters = [{'Name': 'tag:ttl','Values': ['<today']},{'Name': 'instance-state-name','Values': ['running']}]

#locate all running instances
RunningInstances = [instance.id for instance in instances]

print (RunningInstances)

#make sure there are actually instances to shut down.

if len(RunningInstances) > 0:

shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop()
print "shuttingDown"


else:
    print "Nothing to see here"

Upvotes: 0

Views: 1395

Answers (1)

samtoddler
samtoddler

Reputation: 9605

You can't compare dates in the query as you specified. You need to write some code comparing the dates in your python script and take action. Roughly like below:

import datetime
import boto3


# Connect to EC2
ec2 = boto3.resource('ec2')

def get_ttl(instance):
    for tag in instance.tags:
        if 'ttl'in tag['Key']:
            ttl = tag['Value']
            return ttl

def lambda_handler(event,context):
    running_instances = ec2.instances.filter(Filters=[{
        'Name': 'instance-state-name',
        'Values': ['running']}])

    for instance in running_instances:
            ttl = get_ttl(instance)
            if ttl:
                if datetime.date.today() > datetime.datetime.strptime(ttl, "%Y-%m-%d").date():
                    print('stopping instance')
                else:
                    print("nothing to do here")

Basically, it resolves around comparing dates

In [30]: datestring = '2021-02-22'

In [31]: datetime.date.today() == datetime.datetime.strptime(datestring, "%Y-%m-%d").date()
Out[31]: False

In [32]: datetime.date.today() <  datetime.datetime.strptime(datestring, "%Y-%m-%d").date()
Out[32]: True

In [33]: datetime.date.today() >  datetime.datetime.strptime(datestring, "%Y-%m-%d").date()
Out[33]: False

Upvotes: 2

Related Questions