Reputation: 543
I have a lambda function with environment variables defined like the following in the cloud formation template.
Parameters:
Parameter1: { Type: String }
Resources:
LambdaFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: "Function"
CodeUri: // relevant parameters
Handler: handler::handlerequest
Role: //Role
Runtime: java8
Timeout: 300
Environment:
Variables:
refParamter1:
Ref: Parameter1
My code for the handle request is as follows:
String referenceParameter = System.getenv("refParamter1");
System.out.println("Referenced Paramter "+ referenceParameter );
When I deploy this and trigger my lambda it gives me the null
for the printed referenceParameter
.
Is using System.getenv
incorrect when referencing environment variables in lambda?
There is a similar question : CloudFormation - Access Parameter from Lambda Code for python but doesn't give any answer for Java
This is the question with the answer which suggests to use System.getenv
: Accessing AWS Lambda environment variables in Java code
Upvotes: 1
Views: 1812
Reputation: 543
The indentation was wrong in the Lambda function and the yml depends on the indentation it has not taken the environment variables into account.
Parameters:
Parameter1: { Type: String }
Resources:
LambdaFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: "Function"
CodeUri: // relevant parameters
Handler: handler::handlerequest
Role: //Role
Runtime: java8
Timeout: 300
Environment:
Variables:
refParamter1:
Ref: Parameter1
Upvotes: 1
Reputation: 78
If I am correct you are trying to reference a parameter from the resource, then your syntax is wrong, try this:
Environment:
Variables:
refParamter1: !Ref Parameter1
The environment variables definition is an array of key:value, you can see the documentation here https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-environment.html
When deploying make sure to go to the lambda console and check that it correctly appears under environments variables in your function UI, and then you can use:
String referenceParameter = System.getenv("refParamter1");
To access your variable.
Cheers
Upvotes: 1