Reputation: 696
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
Upvotes: 15
Views: 20535
Reputation: 569
A way to do this without having to use aws secrets manager will be using the "Parameters" section in template.yaml
with an env.json
file which you can omit from git like you would for a regular .env
file
Here's a sample template.yaml
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
sample aws sam application with env variables
Parameters:
EnvVarOne:
Type: String
Description: Sample environment variable
Default: one
EnvVarTwo:
Type: String
Description: Sample environment variable
Default: two
Globals:
Function:
Timeout: 5
MemorySize: 128
Environment:
Variables:
EnvVarOne: !Ref EnvVarOne
EnvVarTwo: !Ref EnvVarTwo
Then your env.json file would look like this
{
"Parameters": {
"EnvVarOne": "your-env-var-one",
"EnvVarTwo": "your-env-var-two"
}
}
So now when you want to test locally, all you need to do is pass in the --env-vars env.json
flag to your commands. Example:
sam local start-api --env-vars env.json
Unfortunately, the --env-vars
flag and env.json
file doesn't work for production deployment (sam deploy
) command. In order to pass in environment variables on deploy, you'll need to use --parameter-overrides
with the sam deploy command like this:
sam deploy --parameter-overrides EnvVarOne=your-env-var-one
Upvotes: 5
Reputation: 2038
By extension of @Jason's answer 2. here a full working example:
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: My test secrets manager dynamic reference SAM template/ Cloudformation stack
Resources:
# lambdas
myLambda:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub ${AWS::StackName}-myLambda
Runtime: nodejs12.x
Handler: index.handler
CodeUri: ./src/handlers/myLambda
MemorySize: 128
Timeout: 10
Environment:
Variables:
someSecret: '{{resolve:secretsmanager:somePreviouslyStoredSecret}}'
const { someSecret } = process.env;
exports.handler = (event, context, callback) => {
if (someSecret) callback(null, `secret: ${someSecret}`);
callback(`Unexpected error, secret: ${someSecret}`);
};
Upvotes: 4
Reputation: 8885
There are few options here.
Parameters
section of the template (be sure to add the NoEcho
option) and pass them in at the time of deploying.Upvotes: 19