How Should I Pass My S3 Credentials To Python Lambda Function On AWS?
Solution 1:
You never need to use AWS access keys when you are using one AWS resource within another. Just allow the Lambda function to access the S3 bucket and any actions that you want to take (e.g. PutObject). If you make sure the Lambda function receives the role with the policy to allow for that kind of access, the SDK takes all authentication out of your hands.
If you do need to use any secrets keys in Lambda, e.g. of 3rd party systems or an AWS RDS database (non-Aurora), you may want to have a look at AWS KMS. This works nicely together with Lambda. But again: using S3 in Lambda should be handled with the right role/policy in IAM.
Solution 2:
The fact that your account has permissions to "write" to the S3 account does not mean that you can do it. AWS has a service called IAM which will handle the permissions that your lambda (among many other services) have to perform actions against other AWS resources.
Most probably you are lacking the relevant IAM role/policy associated to your lambda to write to the S3 bucket.
As pointed in AWS Lambda Permissions Model you need to create and associate an IAM role when creating the lambda. You can do this from the console or using CloudFormation.
Once you have the relevant permissions in place for your lambda you do not need to deal with keys or authentication.
Solution 3:
Incidentally, I was curious to see if it took less time for AWS to authenticate me if I explicitly passed ACCESS_KEY and SECRET_ACCESS_KEY when accessing AWS DynamoDB from AWS Lambda instead of letting Lambda find my credentials automatically via environment variables. Here's the log entry from AWS Cloudwatch for example:
[INFO] 2018-12-23T15:34:56.174Z 4c399add-06c8-11e9-8970-3b3cbb83cd9c Found credentials in environment variables.
I did this because when I switched from using AWS RDS with MySQL to DynamoDB it took nearly 1000ms longer to complete some simple table reads and updates. For reference, my calls to AWS RDS MySQL passed credentials explicitly eg:
conn = pymysql.connect(host=db_host, port=db_port, user=db_user, \
passwd=db_pass, db=db_name, connect_timeout=5)
so, I thought this might be the problem because when connecting to DynamoDB I was using:
db = boto3.resource('dynamodb')
table = db.Table(dynamo_db_table)
I decided to try the following to see if my authentication time decreased:
session = boto3.Session(
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)
db = session.resource('dynamodb')
table = db.Table(dynamo_db_table)
End result was explicitly providing my access keys ended up saving less than 100ms on average so I went back to letting the Lambda execution environment dynamically determine my access credential. Still working to understand why MySQL is so much faster for my simple table {key:value} query and update use case.
Post a Comment for "How Should I Pass My S3 Credentials To Python Lambda Function On AWS?"