Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load property file from classpath in AWS lambda java

I have written AWS lambda function in that i want to read database connection details from property file and which in my classpath, but I am not able to load that file.Here is my code:

InputStream input = DBConfiguartion.class.getResourceAsStream("appsettings");

        Reader r = new InputStreamReader(input, "UTF-8");
        Properties prop = new Properties();
        prop.load(r);

If I run this code through normal java console application that time it is working, but whenever i run it as AWS lambda function then InputStream is coming null.

like image 703
Mahesh Avatar asked Feb 12 '16 06:02

Mahesh


People also ask

Can AWS Lambda access local files?

You can configure a function to mount an Amazon Elastic File System (Amazon EFS) file system to a local directory. With Amazon EFS, your function code can access and modify shared resources safely and at high concurrency.

Can I store a file in Lambda?

You can now control the amount of ephemeral storage a function gets for reading or writing data, allowing you to use AWS Lambda for ETL jobs, ML inference, or other data-intensive workloads. With increased AWS Lambda ephemeral storage, you get access to a secure, low-latency ephemeral file system up to 10 GB.


2 Answers

You are only one character off. Here's a working example that I have to do the same thing:

InputStream is = DBConfiguartion.class.getResourceAsStream("/lambda.properties");
Properties properties = new Properties();
properties.load(is);

This works with the following maven file structure when building the deployment jar:

  • project
  • project/src/main/java
  • project/src/main/java/com/something/DBConfiguartion.java -
  • project/src/main/resources
  • project/src/main/resources/lambda.properties
like image 56
bclemenzi Avatar answered Oct 22 '22 10:10

bclemenzi


As you want to load a properties file you can use the ResourceBundle to load the properties.

String version = ResourceBundle.getBundle("lambda").getString("version");

It's not the same as loading file as an InputStream, but this worked for me. In a maven project the file would need to be located at:

  • project/src/main/resources/lambda.properties

I have a simple Hello-World Lambda which reads the current version from a properties file on github.

like image 22
Udo Held Avatar answered Oct 22 '22 11:10

Udo Held