Home > Net >  Python AWS Lambda Execution New Update
Python AWS Lambda Execution New Update

Time:11-29

Update

I changed the params to receive the data directly from a JSON dump to see if that fixed the JSON load issue. Received a new error:

(b'{\n "errorType": "ValidationMetadataException",\n "errorMessage": "The a' b'rgument is null or empty. Provide an argument that is not null or empty, and' b' then try the command again.",\n "stackTrace": [\n "at Amazon.Lambda.P' b'owerShellHost.PowerShellFunctionHost.ExecuteFunction(Stream inputStream, ILa' b'mbdaContext context)",\n "at lambda_method1(Closure , Stream , ILambda' b'Context , Stream )",\n
"at Amazon.Lambda.RuntimeSupport.Bootstrap.User' b'CodeLoader.Invoke(Stream lambdaData, ILambdaContext lambdaContext, Stream ou' b'tStream) in /src/Repo/Libraries/src/Amazon.Lambda.RuntimeSupport/Bootstrap/U' b'serCodeLoader.cs:line 145",\n "at Amazon.Lambda.RuntimeSupport.Handler' b'Wrapper.<>c__DisplayClass8_0.b__0(InvocationRequest invoc' b'ation) in /src/Repo/Libraries/src/Amazon.Lambda.RuntimeSupport/Bootstrap/Han' b'dlerWrapper.cs:line 56",\n "at Amazon.Lambda.RuntimeSupport.LambdaBoot' b'strap.InvokeOnceAsync(CancellationToken cancellationToken) in /src/Repo/Libr' b'aries/src/Amazon.Lambda.RuntimeSupport/Bootstrap/LambdaBootstrap.cs:line 176' b'"\n ]\n}\n')

Still having no success with passing in the lambda name. The code has been updated from the previous post.

============================================================== ORIGINAL POST

I am trying to execute a lambda function through python. I can successfully do it when I hardcode the variables but when I substitute the variables in I am unable to process the lambda.

Here is the working sample with hardcoded values:

params = {"value1": "value1-value", "value2": "value2-value", "value3": "value3-value"}
client = boto3.client('lambda')
response = client.invoke(
    FunctionName='MyLambdaFunctionName',
    InvocationType='RequestResponse',
    Payload=json.dumps(params).encode(),
)
pprint.pp(response['Payload'].read())

The part that fails is when I replace params with variables. The plan is to pass them in, as I call values but right now, I am testing it and setting the values in the function. The variables are listed below:

json_data | lambdaName |

lambdaName = os.getenv('TF_VAR_lambdaName')
value1="value1-value"
value2="value2-value"
value3="value3-value"

data = {"value1": "value1-value", "value2": "value2-value", "value3": "value3-value"}

params = json.dumps(data)
client = boto3.client('lambda')
response = client.invoke(
    FunctionName=lambdaName,
    InvocationType='RequestResponse',
    Payload=json.dumps(params).encode(),
)
pprint.pp(response['Payload'].read())

The error I get goes away when I hard-code the JSON or the Lambda Function Name.

The error log I am getting is listed below:

> Traceback (most recent call last):   File
> "/Users/go/src/github.com/repo/./cleanup/cleanup.py", line 25, in
> <module>
>     response = client.invoke(   File "/Users/Library/Python/3.9/lib/python/site-packages/botocore/client.py",
> line 515, in _api_call
>     return self._make_api_call(operation_name, kwargs)   File "/Users/Library/Python/3.9/lib/python/site-packages/botocore/client.py",
> line 893, in _make_api_call
>     request_dict = self._convert_to_request_dict(   File "/Users/Library/Python/3.9/lib/python/site-packages/botocore/client.py",
> line 964, in _convert_to_request_dict
>     request_dict = self._serializer.serialize_to_request(   File "/Users/Library/Python/3.9/lib/python/site-packages/botocore/validate.py",
> line 381, in serialize_to_request
>     raise ParamValidationError(report=report.generate_report()) botocore.exceptions.ParamValidationError: Parameter validation failed:
> Invalid type for parameter FunctionName, value: None, type: <class
> 'NoneType'>, valid types: <class 'str'>

CodePudding user response:

I think the problem you have is in the definition of your lambda:

lambdaName = os.getenv('TF_VAR_lambdaName')

Try following:

LAMBDA_NAME = os.environ.get('YOUR_LAMBDA_NAME') // make sure you put the exact name of your lambda in ''

Than use it in your code:

response = client.invoke(
  FunctionName=LAMBDA_NAME,
  InvocationType='RequestResponse',
  Payload=json.dumps(params).encode()
)

CodePudding user response:

The community, thanks for your support here. I finally figured it out with the help of my colleague.

So the first issue:

lambdaName = os.getenv('TF_VAR_lambdaName')

This was odd that it wasn't working since i had already exported the environment variables using

export TF_VAR_lambdaName="myfunctionname"

I ended up using a print statement to check the value, and it came out with none. Googling it a bit, found a post where someone suggested rerunning the export to set the value again and that did the trick. I did take a bit from Olgas suggestion and modified the export as follows:

LAMBDA_NAME = os.getenv('TF_VAR_lambdaName')

just making the variable all caps to avoid any issues.

Second Issue:

This one turned out to be an easy fix. The short in sweet of it is I didn't need

json.dumps(data)

The declaration of data was already being passed in a format that params needed. What worked was just setting params equal to data and lambda was able to handle it. Final working code below:

#!/usr/bin/env python
import boto3
import json
import pprint
import os    

LAMBDA_NAME = os.getenv('TF_VAR_lambdaName')
    value1="value1-value"
    value2="value2-value"
    value3="value3-value"
    
    data = {"value1": value1, "value2": value2 "value3": value3}
    
    params = data
    client = boto3.client('lambda')
    response = client.invoke(
        FunctionName=LAMBDA_NAME,
        InvocationType='RequestResponse',
        Payload=json.dumps(params).encode(),
    )
    pprint.pp(response['Payload'].read())
  • Related