I am trying to trigger a Lambda function using Python code as below
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()
with following policy attached to the Role
-
Policy to trigger 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 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 the solution which can be used here by assuming the sts role. considering that I don’t have permission to fetch AccessKey
, SecreteKey
and SessionToken
.
2
Answers
when you are doing
boto3.client('lambda')
you are retrieving credentials either from environment variables AWS_SESSION_TOKEN or from you ~/.aws/credentials fileyou need to check it, and remove it if its unusable
your session token looks expired, you need regenerate a new one with sts
boto3.client('sts').get_session_token()
see boto3 docThe process should work as follows:
~/.aws/credentials
configuration file (which is typically created using theaws 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.