How do I Pass JSON as a parameter to AWS Lambda

Viewed 1679

I have a CloudFormation template that consists of a Lambda function that reads messages from the SQS Queue.

Lambda function will read the message from the queue and transform it using a JSON template(Which I want it to be injected externally)

I will deploy different stacks for different products and for each product I will provide different JSON templates to be used for transformation.

I have different options but couldn't decide which one is better;

  1. I can write all JSON files under the project and pack them together and pass related JSON name as a parameter to lambda.
  2. I can store JSON files on S3 and pass S3 URL to lambda so I can read on runtime.
  3. I can store JSON files on Dynamo DB and read from there using the same approach with 2

The first one seems like a better approach as I don't need to read from an external file on every lambda execution. But I will need to pack all templates together.

The last two are a more clear approach but require an external call to read JSON for every call.

Another approach could be (I'm not sure if it is possible) to inject a JSON file to Lambda on deploy from S3 bucket or sth. And Lambda function will read it like an environment variable.

2 Answers

As you can see from the cloudformation documentation Lambda environment variables can be only a Map of Strings, so the actual value you can pass to the function as an environment variable must be a String. You could pass your JSON as a string but the problem is that the max size for all environment variables is 4 KB.

If your templates are bigger and you don't want to call S3 or DynamoDB at runtime you could do a workaround like writing a simple shell script that copies the correct template file to the lambda folder before building and deploying the stack. This way the lambda gets deployed in a package with the code and only the desired json template.

I decided to go with S3 setup and also improved efficiency by storing Json on a global variable (after reading the first time). So I read once and use it for the lifetime of the Lambda container.

I'm not sure this is the best solution but works well enough for my scenario.

Related