How to Set Environment Variables in Lambda Function in Java

Posted By : Abhishek Sharma | 16-Sep-2018

INTRODUCTION:-  AWS Lambda may be a serverless figure service that runs your code in response to events and mechanically manages the underlying figure resources for you. you'll be able to use AWS Lambda to increase different AWS services with custom logic or produce your own back-end services that operate at AWS scale, performance, and security. we will additionally check the lambda perform surroundings variable through sam-cli. For setting the surroundings variable we will screw in 2 ways that.

1) Define the variable in Java Code:-  First, we have to define the environment variable in our java code which we want to access it through the yaml file.

public Connection sqlConnection() {
		String host = System.getenv("dbHost");
		String port = System.getenv("dbPort");
		String dbName = System.getenv("dbName");
		String username = System.getenv("dbUsername");
		String password = System.getenv("dbPassword");
		try {
			System.out.println(":: host ::" + host + ":: port ::" + port + ":: dbName ::" + dbName + ":: username ::"
					+ username + ":: password ::" + password);
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://" + host + ":" + port + "/" + dbName;
			Connection connection = DriverManager.getConnection(url, username, password);
			String sqlQuerry = " sql querry";
			Statement stmt = connection.createStatement();
			stmt.executeUpdate(sqlQuerry);
			System.out.println(":: database connection created ::");
			return connection;

		} catch (Exception e) {
			return null;
		}
	}

 

System provides the  read-only access to environment variables with getenv . we have to pass the environment variable name which we have to access in the get env method. 

System.getenv("variableName");

 

we have to define the value of that environment variable in the template.yaml file when we run our program in sam-cli. In our template.yaml file we have to give the name of lambda handler function name. and the path of our jar file.

AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS Lambda Sample Project

Resources:

  Products:
    Type: AWS::Serverless::Function
    Properties:
      Handler: "lambda function handler name"
      CodeUri: ./target/"jar_file_name".jar
      Runtime: java8
      Timeout: 300
      Environment:
        Variables:
          ENVIRONMENT: "test"
          dbHost: "ip"
          dbPort: "port"
          dbName: "name"
          dbUsername: "username"
          dbPassword: "password"
      Events:
        ListProducts:
          Type: Api
          Properties:
            Path: /upload
            Method: post

 

or we can do it in another way we just define the variable in the template.yaml file and give their value in JSON  file. create a config.json file. first, we have to define the name of our function name in JSON file and then in that function name we have to give the value of that environment variable which is then accessed through the system.getenv function.

{
  "Products":{
       dbHost: "ip",
          dbPort: "port",
          dbName: "name",
          dbUsername: "username",
          dbPassword: "password"
  }
}

 

To run the lambda function through sam-cli we use this following command with JSON file:-

sam local invoke "Products" -e event_file.json --env-vars env.json

 

To run the lambda function through sam-cli we use this following command without JSON file:-

sam local invoke "Products" -e event_file.json

About Author

Author Image
Abhishek Sharma

Abhishek is a Java Developer and worked on servlet, JSP, collection, JDBC and now working on Spring boot. He has certification of core java from Aptech Pitampura.

Request for Proposal

Name is required

Comment is required

Sending message..