I am trying to trigger a Lambda function using Python code as follows:
import boto3
from botocore.exceptions import NoCredentialsError, PartialCredentialsError
def get_lambda_client():
return boto3.client('lambda')
def invoke_lambda():
lambda_client = get_lambda_client()
if lambda_client:
try:
response = lambda_client.invoke(
FunctionName='MyLambdaFunctionName',
InvocationType='RequestResponse', # or 'event for async invocation'
Payload=b'{}' #Not sending any payload
)
print(f" the response from the aws = {response}")
except Exception as e:
print(f" Error invoking Lambda function: {e}")
invoke_lambda()
I am using the following policies attached to the Role:
Policy to trigger the Lambda function:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": "< arn of my lambda function>"
},
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "< arn of the role I created for lambda function which intern
will trigger aws step function>"
}
]
}
Trusted policy for the role I created for this Lambda function trigger:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com",
"AWS": "<arn for the iam user>"
},
"Action": "sts:AssumeRole"
}
]
}
Please let me know if anything is missing here. The error I am getting when I try to trigger a lambda function from python code is:
Error invoking Lambda function: An error occurred (ExpiredTokenException) when calling the Invoke operation: The security token included in the request is expired
Suggest a solution which can be used here by assuming the sts role, considering that I don't have permission to fetch AccessKey
, SecreteKey
and SessionToken
.
The process should work as follows:
~/.aws/credentials
configuration file (which is typically created using the aws configure
command in the AWS CLI)Your 'policy to trigger Lambda function' does NOT require permission to AssumeRole. It simply needs permission to invoke the Lambda function.