Reputation: 899
How do I return a hash from a aws lambda function ?
Using boto3 module.
Here is my code snip
def lambda_handler(event, context):
global cnt
any = []
for node in ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]):
inst= node.instance_type
any.append(inst)
cnt=collections.Counter(any)
return cnt
for key, val in cnt.items():
print key
print val
Exact code works in python IDE. My goal is to return a variable from AWS lambda function and use in other functions with in the same lambda-function.
Error in lambda logs
module initialization error: global name 'cnt' is not defined
Upvotes: 2
Views: 3745
Reputation: 22026
AWS will call the lambda entry point you define, and once that returns, the lambda process will be terminated. There is no opportunity to use the global in other functions unless those functions are called by your entry point. If the other functions are being called by the entry point, then you can pass cnt
as a parameter -- no need for a global. If the other functions aren't being called by your entry point, they won't be run at all -- still no need for a global :)
Upvotes: 2
Reputation: 4368
Edit: after you added the error message, it seems the problem is simply not having declared the global in the top scope. See this answer. Fixing my sample below accordingly.
AWS will load your code in a container if needed, then call the method indicated by the Lambda Function Handler property. That function can raise an error or return data, which AWS will pass back to the caller (eg: an API Gateway method).
So, for instance you could:
cnt = []
def lambda_handler(event, context):
global cnt
cnt = [{'id': 1, 'label': 'One'}, {'id': 2, 'label': 'Two'}]
print "cnt: {0!s}".format(cnt)
other_method()
return cnt
def other_method():
global cnt
print "cnt length is: {0!s}.format(len(cnt))
return
(I didn't go test this in AWS yet, so be careful of possible errors)
But arguably, you might as well have the lambda_handler
method pass the cnt
variable as an argument to other_method
.
Or make a class and call some method on it, and let the class manage the cnt
variable as a its own data (eg: via a protected variable).
Keep in mind globals may or may not survive in between successive calls to any given Lambda. See Understanding Container Reuse in AWS Lambda.
HTH
Upvotes: 2