Search code examples
pythonamazon-web-servicesamazon-ec2boto3amazon-sns

Trying to return multiple values in output


I'm trying to get running hours on an EC2 tagged instance with (Tag-periods - active) in an sns email notification, however I'm new to Python. Nevertheless, even though I have more than 5 instances with these tag values, I only returned one of them. I tried hundreds more times, but I still couldn't attain an acceptable result.

import json
import boto3
from datetime import datetime
from datetime import timedelta

region ='ap-south-1'
ec2 = boto3.resource('ec2',region)
client = boto3.client('ec2',region)

def lambda_handler(event, context):
    ec2 = boto3.resource('ec2')
    sns = boto3.client('sns')
    instances = ec2.instances.filter(Filters=[{'Name':'tag:Period', 'Values':['active']}])
    active = ''
    for instance in instances:
        instanceStartTime = instance.launch_time.strftime("%Y-%m-%d %H:%M:%S")
        currentTime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        date_time_obj1 = datetime.strptime(instanceStartTime, '%Y-%m-%d %H:%M:%S')
        date_time_obj2 = datetime.strptime(currentTime, '%Y-%m-%d %H:%M:%S')
        timeDiff = (date_time_obj2 - date_time_obj1).total_seconds() / 3600.0
        
        active += '\n Instance Id : ' + instance.id
        active += '\n Instance Start Time : ' + instanceStartTime
        active += '\n current Time : ' + currentTime
        active += '\n Running Time : ' + str(timeDiff) + '\n\n'
        
        for x in active:
            if str(timeDiff)>='08.0':
                response = sns.publish(
                    TopicArn='arn:aws:sns:ap-south-1:123456789:SNS-Notification',
                    Message='Current Active Instances ' + active,
                    )
                return response

output: enter image description here


Solution

  • In this block:

        for x in active:
            if str(timeDiff)>='08.0':
                response = sns.publish(
                    TopicArn='arn:aws:sns:ap-south-1:123456789:SNS-Notification',
                    Message='Current Active Instances ' + active,
                    )
                return response
    

    You're returning after the first iteration that executes the if statement: in Python a function exits from execution after returning.

    Try this instead:

        for x in active:
            if str(timeDiff)>='08.0':
                sns.publish(
                    TopicArn='arn:aws:sns:ap-south-1:123456789:SNS-Notification',
                    Message='Current Active Instances ' + active,
                    )
    

    (Also: why are you iterating over active, which is a string? And what's that time comparison as a string?)