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.
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 .
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With