carol Alex carol Alex - 1 month ago 9
Python Question

Python - return multiple values using tuple (AWS lambda function)

This is the current code that I have:

def handler():
ec2 = boto3.resource("ec2", region_name="ap-southeast-2")
instances = ec2.instances.filter(Filters=[{'Name':'iam-instance-profile.arn', 'Values': ['arn:aws:iam::123456789012:instance-profile/TestRole']}])
for instance in instances:
return (instance.private_ip_address)


I'm trying to return all the private_ip_addresses. This code only returns me 1 ip address but I should be getting back 3 addresses. If i did a
print
instead, it returns the correct 3 values

I did some research and found using tuple is a good way but it hasn't been working for me thus far. Here is an example code I'm trying out with tuple (that should work with my code if it is correct)

myList=[1,2,3,4,5,6]

def handler():
tup=()
for element in myList:
tup+= (element,)
return tup


This currently returns a null value. However, if i do
print tup
, it returns me with
(1, 2, 3, 4, 5, 6)


Can anyone let me know where I am going wrong with my use of tuple. OR if there is a better way to do this (corresponding with how lambda functions work)?

Answer

The statement "return (instance.private_ip_address)" returns a tuple consisting of a single value. The fact that it is called from a loop, doesn't make any difference - as soon as the return statement is executed during the first iteration, the loop terminates.

The following should work:

def handler():
    ec2 = boto3.resource("ec2", region_name="ap-southeast-2")
    instances = ec2.instances.filter(Filters=[{'Name':'iam-instance-profile.arn', 'Values': ['arn:aws:iam::123456789012:instance-profile/TestRole']}])
    return tuple([instance.private_ip_address for instance in instances])