Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

amazon web services - 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"
question from:https://stackoverflow.com/questions/65851227/how-to-filter-tag-values-of-an-ec2-instance-by-a-date-in-boto3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...