1. Access CloudShell from Lambda Console
Since npm is already installed in CloudShell, we can use it to create node_modules.
2. Create a lambda folder
mkdir lambda
cd lambda
3. Open Nano text editor
Run nano index.js to open the nano editing GNU.
// if no nano installed then run this first
sudo yum install -y nano
// else just run this
nano index.js
4. Copy the following code into the nano GNU
const AWSXRay = require('aws-xray-sdk-core');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
const s3 = new AWS.S3();
exports.handler = async function (event) {
return s3.listBuckets().promise();
};
Then Ctrl-X
, Y
and Enter
to exit nano.
We can run the following to double confirm the code has been pasted into index.js
cat index.js
5. Install the required Dependencies
npm i aws-xray-sdk
Run ll
to check that node_modules exist and the dependencies are indeed being installed.
6. Set proper permission for files
chmod a+r *
7. Zip the files
zip -r function.zip .
Run ll
again to double check zipped folder is created.
8. Create a IAM role
Since we are using lambda and S3, we need to assign 2 permission policies:
- AWSLambdaBasicExecutionRole
- AmazonS3ReadOnlyAccess
Name the IAM role as DemoLambdaRole
9. Use cli to upload the zipped folder to create the lambda function
Remember to replace the ARN with yours
aws lambda create-function --zip-file fileb://function_test.zip --function-name lambda-with-dependencies --runtime nodejs14.x --handler index.handler --role arn:aws:iam::023028579192:role/DemoLambdaRole
Refresh the Lambda Functions table and you should see your new lambda being created
10. Enable x-ray Tracing
Lastly, since we are using x-ray, we also need to enable x-ray tracing at the lambda function.
Once you enabled x-ray tracing, go back to the IAM DemoLambdaRole
and you will see a new permission policy being assigned.
11. Test the Lambda
You should see all your S3 buckets being returned, as shown below:
12. Clean up!
Finally, as a good habit, delete the Lambda to save resources. You may also delete the create Role too.
Cheers! Reference
Top comments (0)