Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No module named 'requests_aws4auth' when trying to import in a lambda

I need my lambda to call an API Gateway and have the following code in place as inline code for the lambda in my cloud formation template.

from requests_aws4auth import AWS4Auth
def handler(event,context):
          client = boto3.client('sts')
          responseAssumeRole = client.assume_role(
            DurationSeconds=3600,
            RoleArn='arn',// real arn of the api gateway invocation role
            RoleSessionName='Bob',
          )
          credentials = responseAssumeRole['Credentials']
          auth = AWS4Auth(aws_access_key=responseAssumeRole['Credentials']['AccessKeyId'],
                                 aws_secret_access_key=responseAssumeRole['Credentials']['SecretAccessKey'],
                                 aws_host='host.execute-api.us-east-1.amazonaws.com',
                                 aws_region='us-east-1',
                                 aws_service='execute-api')
          headers= {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
          response = requests.get('https://host.execute-api.us-east-1.amazonaws.com/test',
                                  auth=auth, headers=headers)

This gives me the following error

No module named 'requests_aws4auth'

Any solution or alternative way to get the auth created using the aws credentials would be also welcome.

like image 912
SanD Avatar asked Aug 15 '18 12:08

SanD


2 Answers

Package your source code and dependencies in a zip file, upload it to S3, and then use the S3Bucket and S3Keys Properties under your AWS::Lambda::Function resource.

e.g. On Linux:

mkdir project-dir
cp myhandler.py project-dir
pip install module-name -t /path/to/project-dir

# zip the contents of project-dir , this is your deployment package
cd project-dir
zip -r deployme.zip .
like image 151
carlsborg Avatar answered Sep 20 '22 14:09

carlsborg


Although the accepted answer works, I want to post this resource as well. If you do not want to package it and upload to S3 and still searching for an alternative approach to have the same functionality in an inline lambda, this will help. If you use this approach you do not need to use 'requests_aws4auth' in the first place.

https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html

You can replace the following

access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')

with the values you got from the assume role request like this

access_key=responseAssumeRole['Credentials']['AccessKeyId']
secret_key=responseAssumeRole['Credentials']['SecretAccessKey']
like image 37
SanD Avatar answered Sep 17 '22 14:09

SanD