Passing Resource References to Functions

In this lesson, you will learn how to let SAM configure the environment variables​ for your application.

We'll cover the following

In order to complete the function, you’ll need to tell it which bucket to use (line 8 from the code in the previous lesson). Lambda functions don’t really know about SAM and CloudFormation resources, so the function can’t just ask for the UploadS3Bucket resource. SAM will create the bucket using a randomised name, and you need to tell the Lambda function about the actual value.

You definitely don’t want to hard code a bucket name in the function source, because then SAM can’t automatically manage buckets. You could change the API Gateway resource to stick that information onto the request while it’s passing through the API, for example as an additional header, but that requires messy request transformations. For situations such as this one, it’s best to set a Lambda environment variable.

Environment variables #

Environment variables are textual key-value pairs assigned to a running process. With a Node.js Lambda runtime, you can read them using the standard Node process.env object. SAM lets you configure those values in the template, so it’s easy to pass the actual bucket name to a function based on the logical bucket reference.

Environment variables are great for configuring Lambda functions with references to other resources in the same SAM template. For more complex configuration scenarios, such as rotating secrets and reconfiguring services without redeployment, check out the AWS Systems Manager Parameter Store and AWS Secrets Manager.

It helps to use all uppercase letters for environment variable names to clearly differentiate them from other values, but you can use any naming convention you like. The process-form.js file is updated to look like in the following listing:

Get hands-on with 1200+ tech skills courses.