Let us create a simple Lambda using the Serverless framework:
- Install Serverless in your machine using npm:
npm install -g serverless
- Configure Serverless with user credentials:
serverless config credentials --provider aws --key <access key> --secret <secret access key> --profile serverless-admin
You should get a success message stating that keys were stored under the serverless-admin profile.
The sls command is the shorthand of the Serverless command.
- Create a Lambda function based on Java and Maven:
sls create --template aws-java-maven --path hello-world-java-maven
It creates a hello-world-java-maven folder, with pom.xml and serverless.yml files, and the src folder. You may open this Maven project in your IDE of choice. The auto-generated files looks as shown here in my IDE:
As you can see, Serverless has created a bit more than a simple hello world. Serverless takes care of most of the things we did manually, including creating a role, setting memory, setting timeout, and so on.
Add a user profile and region to serverless.yml. The region is optional if you are using the default region:
Build the jar file with:
mvn clean package
- Deploy the jar file to AWS:
sls deploy -v
You can log in to the AWS console and verify the new Lambda service. From the log statements, you can see that Serverless framework internally makes use of CloudFormation. You can verify the same from AWS Management console.
- Invoke the function from sls:
sls invoke -f hello -l
Option -f specifies the function name, and -l specifies that logs need to be printed to terminal. The function name to invoke is hello and is available in the serverless.yml file. You can see the output and logs on the terminal.
- Checking logs from the CLI:
sls logs -f hello -t
Option -f specifies the function name and -t denotes to tail the logs. You can now run the invoke command from the other terminal and see the logs being printed.
- Now, clean up everything:
sls remove
- Log in to AWS Management console and verify that everything is cleaned up.