Can I load code from file in a AWS Lambda?

Viewed 357

I am thinking of creating 2 generic AWS Lambda functions, one as an "Invoker" to run the other Lambda function. The invoked Lambda function loads the code of the Lambda from a file based on the parameter that is passed to it.

Invoker: Calls the invoked Lambda with a specified parameter, e.g. ID

Invoked: Based on the ID, load the appropriate text file containing the actual code to run

Can this be done?

The reason for this thinking is that I don't want to have to deploy 100 Lambda functions if I could just save the code in 100 text files in S3 bucket and load them as required.

The code is uploaded constantly by users and so I cannot include it in the lambda. And the code can be in all languages supported by AWS (.NET, NodeJs, Python, etc.)

For security, is there a way to maybe "containerized" running the code?

Any recommendation and ideas are greatly appreciated.

Thanking you in advance.

2 Answers

The very first I'd like to mention is that you should pay a lot of attention to the security aspects of your app as you are going to execute code uploaded by users, meaning that they will potentially be able to access sensitive data.

My example is based on NodeJS, but I think something similar may be achieved using other runtimes, not sure. There are main two things you need to know:

  • AWS Lambda execution environment provides you with the /tmp folder with capacity of 512 MB and you are allowed to put there any necessary resources needed for the current particular invocation.
  • NodeJS allows you to require modules dynamically at any place in the app.

So, basically, you may download the desired js file into the /tmp folder and then require it from your code. I am not going to write the real code now as it could be quite big, but here is some general steps just to make things clear:

  1. Lambda receives fileId as a parameter in event.

  2. Lambda searches S3 for the file named fileId and then downloads it to the /tmp folder as fileId.js

  3. Now in the app you may require that file and consider it as a module:

    const dynamicModule = require("/tmp/fileId.js");

  4. Use the the module loaded

You certainly won't be able to run Python code, or .Net code, in a Node lambda. Can you load files and dynamically run the code? Probably. Should you? Probably not. Even if trust the source of that code you don't want them all running in the same function. 1) they would share the same permissions. That means that, at a minimum, they would all have access to the same S3 bucket where the code is stored. 2) they would all log to the same place. Good luck debugging.

We have several hundred lambda functions deployed in our account. I would never even entertain this idea as an alternative.

Related