DEV Community

KenjiGoh
KenjiGoh

Posted on

Create Lambda function using AWS CloudShell

1. Access CloudShell from Lambda Console

Image description
Since npm is already installed in CloudShell, we can use it to create node_modules.

2. Create a lambda folder

mkdir lambda
cd lambda
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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();
};
Enter fullscreen mode Exit fullscreen mode

Image description

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
Enter fullscreen mode Exit fullscreen mode

Image description

5. Install the required Dependencies

npm i aws-xray-sdk
Enter fullscreen mode Exit fullscreen mode

Run ll to check that node_modules exist and the dependencies are indeed being installed.

Image description

6. Set proper permission for files

chmod a+r *
Enter fullscreen mode Exit fullscreen mode

7. Zip the files

zip -r function.zip .
Enter fullscreen mode Exit fullscreen mode

Run ll again to double check zipped folder is created.

Image description

8. Create a IAM role

Since we are using lambda and S3, we need to assign 2 permission policies:

  1. AWSLambdaBasicExecutionRole
  2. AmazonS3ReadOnlyAccess

Name the IAM role as DemoLambdaRole

Image description

Copy the role ARN
Image description

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
Enter fullscreen mode Exit fullscreen mode

Image description

Refresh the Lambda Functions table and you should see your new lambda being created

Image description

10. Enable x-ray Tracing

Lastly, since we are using x-ray, we also need to enable x-ray tracing at the lambda function.

Image description

Once you enabled x-ray tracing, go back to the IAM DemoLambdaRole and you will see a new permission policy being assigned.

Image description

11. Test the Lambda

You should see all your S3 buckets being returned, as shown below:

Image description

12. Clean up!

Finally, as a good habit, delete the Lambda to save resources. You may also delete the create Role too.

Image description

Cheers! Reference

Top comments (0)