aws-lambdaaws-cloudformationaws-sam-clisam

How to add environment variables in template.yaml in a secured way?


When creating Lambda function through the SAM CLI using template.yaml, I have to pass few environment variables, and they shouldn't be exposed on GitHub. Is there any way I can refer the environment variables in template.yaml through the .env file?

I didnt find any sources for the same.

Sample code snippet from template.yaml:

Properties:
  CodeUri: student /
  FunctionName: list
  Handler: index.listHandler
  Runtime: nodejs14.x
  Environment: 
    Variables:
      MONGODB_URI: mongodb://username:pwd

Solution

  • There are few options here.

    1. Add them to the Parameters section of the template (be sure to add the NoEcho option) and pass them in at the time of deploying.
    2. A slightly better option is to use Secrets Manager to store the value and then use dynamic references in the template. CloudFormation will retrieve the values from Secrets Manager for you, at the time you deploy.
    3. A better option is to not pass them as environment variables at all (since anyone with permissions to view the function will be able to see the value). Instead, use Secrets Manager to store the value and look up the value in the code. If you decide to use this approach be sure to cache the value so that you can at least reuse it between warm starts of the lambda.
    4. One more option is to encrypt the value using KMS, and pass in the encrypted (Base64 encoded) value to the function. You'll need to call KMS decrypt to get the decrypted value. This operation is pretty fast, and isn't likely to be throttled. I would still cache the value to help speed things up between warm starts.