I want to access environment variables from within my lambda function, however I've been having issues with accomplishing that.
I use serverless to manage the creation and deployment of my lambda functions. Within one of the function definitions in my serverless file I have defined 2 environment variables:
functions:
update-item:
handler: ...
environment:
FUNCTION_NAME: updateItemById
TOPIC_NAME: ${self:custom.topicName}
events: ...
Within my lambda function I access the environment variable TOPIC_NAME like so:
Optional<String> topicName = Optional.of(System.getenv("TOPIC_NAME"));
This code throws an exception every time the lambda function executes because the TOPIC_NAME environment variable doesn't exist. However, I can see that the environment variable exists in:
- The serverless.yml file
- The CloudFormation files that serverless generates
- The CloudFormation files as shown in the AWS console
- The lambda function as shown in the AWS console
Within the lambda function I use a small loop to print out all of the environment variables:
Map<String, String> envVars = System.getenv();
for (String s : envVars.keySet()) {
System.out.println(s + " - " + envVars.get(s));
}
The FUNCTION_NAME environment variable is displayed, however the TOPIC_NAME variable is not. I've tried renaming, adding, and removing environment variables and there is no change to the output of this print loop. I've re-deployed my code numerous times, with and without code changes, with config file changes, I've manually added the environment variable through the console. I've verified that the latest version of the lambda function is running. Nothing I've done has worked.
Based on the behavior it seems like the container that my lambda function is running in is never being refreshed and thus always contains the old environment variables. However, this runs contrary to everything I've read and how I expect lambda containers to work.