Borislav Hadzhiev
Wed Apr 13 2022·2 min read
Photo by Mike Giles
Updated - Wed Apr 13 2022
In order to pass environment variables to a Lambda function, we have to set
the environment
property, when instantiating the function construct.
const myFunction = new NodejsFunction(this, id, { // setting environment variables 👇 environment: { region: cdk.Stack.of(this).region, availabilityZones: JSON.stringify(cdk.Stack.of(this).availabilityZones), myEnvVariable: 'some value', }, runtime: lambda.Runtime.NODEJS_14_X, memorySize: 1024, timeout: cdk.Duration.seconds(5), handler: 'main', entry: path.join(__dirname, `/../src/my-function/index.js`), });
The environment
object is a map of key value pairs of type string
. This
means that we have to call JSON.stringify
on any non-string value that we want
to pass to the lambda function - in this case the array of availability zones.
In our lambda function code we can access the environment variables by using the
process.env
object.
async function main(event) { // accessing environment variables 👇 console.log('region 👉', process.env.region) console.log('availabilityZones 👉', process.env.availabilityZones) console.log('myEnvVariable 👉', process.env.myEnvVariable) return {body: JSON.stringify({message: 'SUCCESS'}), statusCode: 200}; } module.exports = {main};
The result of the function invocation looks like:
We can also verify that the environment variables have been set by opening the Lambda AWS console and clicking on Configuration:
In order to pass environment variables to a Lambda function we have to set the
environment
property on the function construct to a map of key value pairs of
type string.
We are then able to access the environment variables on the process.env
object
in our lambda function.