In the previous post, we optimized AWS SAM Node.js Lambda with esbuild.
We’ll dive into configuring environment variables and securely managing secrets using AWS Secrets Manager in an AWS Lambda function built with Node.js and AWS SAM.
You'll learn how to:
- Define environment variables using Parameters in template.yml
- Access them inside your Lambda function
- Securely retrieve secrets from Secrets Manager
- Add necessary IAM permissions to your Lambda role
Step 1: Define Parameters in template.yml
Add environment-specific parameters at the top of your SAM template:
Parameters:
ENVIRONMENT:
Type: String
Default: dev
SecretName:
Type: String
Description: Name of the AWS Secrets Manager secret
Step 2: Add Environment Variables and IAM Permissions
Update your Lambda function configuration:
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs22.x
Environment:
Variables:
ENV: !Ref ENVIRONMENT
SECRET_NAME: !Ref SecretName
Policies:
- AWSSecretsManagerGetSecretValuePolicy:
SecretArn: !Sub arn:aws:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:${SecretName}*
🔐 What This Does
- Sets ENV and SECRET_NAME as environment variables
- Grants the Lambda function permission to fetch secrets using the Secrets Manager policy
Step 3: Access Environment Variables in Your Code
In your index.js
or index.ts
:
const env = process.env.ENV;
const secretName = process.env.SECRET_NAME;
console.log(`Running in ${env} environment`);
Step 4: Fetch a Secret from AWS Secrets Manager
Install the AWS SDK v3 module if not already installed:
npm install @aws-sdk/client-secrets-manager
In your Lambda code:
import {
SecretsManagerClient,
GetSecretValueCommand
} from "@aws-sdk/client-secrets-manager";
const getSecretValue = async (secretName: string) => {
const client = new SecretsManagerClient({});
const command = new GetSecretValueCommand({ SecretId: secretName });
const response = await client.send(command);
return response.SecretString ? JSON.parse(response.SecretString) : null;
};
export const handler = async () => {
const secret = await getSecretValue(process.env.SECRET_NAME!);
console.log("Fetched secret:", secret);
};
Conclusion
You've now learned how to:
✅ Use Parameters
in template.yml
for dynamic environment configuration
✅ Inject environment variables into our Lambda function
✅ Securely fetch secrets from AWS Secrets Manager
✅ Grant minimal IAM access for secrets usage