Navigate to the IAM service portion, and move to the Roles tab on the left. Next, we want to create a role - the name isn’t too important, just keep it something easy to comprehend. For example, my new role’s name is lambda-with-s3-read.
We now want to select the AWS Lambda service role. From there, it’s time to attach policies which will allow for access to other AWS services like S3 or Redshift. As shown below, type
s3 into the Filter field to narrow down the list of policies. If you want your Lambda function to only have read access, select the
AmazonS3ReadOnly policy, and if you want to put objects in, use
After that, you can review one more time before creating your new role. We can now hop on over to the Lambda home page to create a new Lambda function. Below is some super-simple code that allows you to access an object and return it as a string.
This method checks for an object at
test_bucket. It uses boto3, the Python AWS library. The key method in this code is
get_object. This returns a dictionary with the following syntax:
It’s a pretty complicated object, but the one we care about is
Body, which holds a
StreamingBody with a method
read that returns a string. You can learn more about
get_object in the documentation. Once you load this in as a string, you can parse it as JSON or do anything else you’d like with it before returning.
And with that, we’re all done! You know how to access your S3 objects in Lambda functions, and you have access to the boto documentation to learn all that you need.