Reading timeยท2 min
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_16_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, 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 as follows:
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.
You can learn more about the related topics by checking out the following tutorials: