old_guy
old_guy

Reputation: 23

Python call to AWS lambda - security token in the request is invalid

The attempt to call an AWS lambda function from Python on windows fails.

I have reset my credentials to new AWS keys. No good. I have added AWSLambdaFullAccess to my user ID and group. No workee.

import boto3,json

session = boto3.Session(
    aws_access_key_id="YesSireee",
    aws_secret_access_key="MySuperDuperSecretAccessKey",
)
lambda_client = boto3.client('lambda', region_name="us-east-2")
test_event = dict(key1="testme") 
try: 
    response = lambda_client.invoke(
  FunctionName='arn_copied_from_console',
  InvocationType='Event',
  LogType='None',
  Payload=json.dumps(test_event),
  )
except Exception as e: print(e)
print(response); # should be None. 

The error is:

An error occurred (UnrecognizedClientException) when calling the Invoke operation: The security token included in the request is invalid.

Upvotes: 0

Views: 1086

Answers (2)

keithRozario
keithRozario

Reputation: 406

Your problem is here:

lambda_client = boto3.client('lambda', region_name="us-east-2")

It should be session.client instead of boto3.client. If you use boto3.client, it will search for credentials in the environment variables, credential file, IMDS etc, disregarding the session you created.

To use the credentials supplied in the code, use the session.client.

A better way to address this problem is to remove your credentials from your code, and populate them in the ~/.aws/credentials file, or in your environment variables, and then continue using boto3.client without creating sessions with hard-coded credentials.

Hope that helps :)

Upvotes: 0

Ashaman Kingpin
Ashaman Kingpin

Reputation: 1577

This is a wild guess but is the time on your test system correct (for example using NTP)?

Upvotes: 1

Related Questions