How to deploy Java to AWS Lambda with Serverless Framework

I've been developing Java in Eclipse so far. However, I recently purchased IntelliJ Idea individually, so I'm consciously trying to use it. However, the problem is that IntelliJ Idea does not have a plug-in equivalent to the "AWS Toolkit" that exists in Eclipse. This was actually a problem. So, by using the Serverless Framework that my neighbor used to deploy Node.js, I can now deploy Java applications to AWS Lambda with a single command without the AWS Toolkit, so I will summarize it. Make an article.

In addition, my execution environment is as follows, but since it is under the internal authentication proxy, the proxy settings are also included in the procedure. Those who have given up on things because of the authentication proxy may see hope.

environment
OS Windows10 Pro

Installation prerequisites(What Java developers probably already have)
JDK Java8
Apache Maven 3.3.9 * 3 or later version does not matter
Java IDE:It doesn't matter

installation of nodist

You can install Node.js as it is, but Node.js is updated quickly and there is a problem of compatibility depending on the version, so install and use nodist which can easily manage the version of Node.js. Download the latest version of nodist from the following. https://github.com/marcelklehr/nodist/releases

image.png

Execute the downloaded exe to install it. By default, it is c: \ program files, but if the directory contains spaces, an error may occur when executing Serverless Framework, so change it to a location that does not include spaces, such as directly under the C drive, and install it. I recommend you to do it.

Install Node.js

Set Proxy settings (only if necessary)

In my case, I have an authentication proxy in my company, so set the following values in the environment variables.

Variable name Variable value Remarks
HTTP_PROXY http://[User name]:[password]@server name:port -
HTTPS_PROXY http://[User name]:[password]@server name:port -

Check the version of Node.js that can be installed

Start a command prompt, enter the following command, and press Enter

e:\nodist>nodist dist

The version of Node.js that can be installed is displayed as below

8.0.0
8.1.0
8.1.1

Specify the version to install

Install in the format nodist + version.

e:\nodist>nodist + 8.9.0
 8.9.0 [===============] 22436/22436 KiB 100% 0.0s
8.9.0

Select the Node.js you want to use

e:\nodist>nodist 8.9.0

Install npm that matches your Node.js

e:\nodist>nodist npm match
npm match
https://codeload.github.com/npm/npm/tar.gz/v5.5.1 [===========    ] 4309/5752 KiB 75% 5.0s

e:\nodist>npm -v
5.5.1

Install Serverless Framework

Now that Node.js and npm have been installed, install the favorite Serverless Framework. Enter npm install -g serverless to install the Serverless Framework on your local PC.

e:\nodist>npm install -g serverless

e:\Nodist\bin\serverless -> e:\Nodist\bin\node_modules\serverless\bin\serverless
e:\Nodist\bin\sls -> e:\Nodist\bin\node_modules\serverless\bin\serverless
e:\Nodist\bin\slss -> e:\Nodist\bin\node_modules\serverless\bin\serverless
npm WARN lifecycle The node binary used for scripts is e:\Nodist\bin\node.exe but npm is using e:\Nodist\v-x64\8.9.0\node.exe itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.
> [email protected] postinstall e:\Nodist\bin\node_modules\serverless\node_modules\spawn-sync
> node postinstall
> [email protected] postinstall e:\Nodist\bin\node_modules\serverless
> node ./scripts/postinstall.js
+ [email protected]
added 251 packages in 177.711s

AWS CLI installation and setup

Since Serverless Framework uses the AWS CLI internally, install the AWS CLI here. Download the installation file from the following site and install it. https://aws.amazon.com/jp/powershell/

After installation, start powershell as an administrator and execute ʻaws configure`. Predefine the values to use for AWS Lambda uploads. If the value has already been set, it will be written as [**** BG4A] as shown below, and if you do not want to change it, you can avoid entering the item by pressing the Enter key without entering it.

PS E:\awscli> aws configure
AWS Access Key ID [****************BG4A]:Enter your AWS Access Key ID and press Enter
AWS Secret Access Key [****************BsCe]:Enter your AWS Secret Access Key and press Enter
Default region name [us-west-2]: us-east-1
Default output format [None]: json

The AWS Access Key ID and AWS Secret Access Key can be issued from the following URL on AWS. It is only necessary to have the authority to access all services with administrator authority, but if not, ask the administrator to properly grant the authority. https://console.aws.amazon.com/iam/home?#/users

Java application creation

Automatically generate Java development directory using Serverless Framework

Create an appropriate directory, move to that directory, enter serverless create --template aws-java-maven, and press the Enter key.

E:\>cd workspace
E:\workspace>mkdir serverlesssample
E:\workspace>cd serverlesssample
E:\workspace\serverlesssample>serverless create --template aws-java-maven
Serverless: Generating boilerplate...
 _______                             __
|   _   .-----.----.--.--.-----.----|  .-----.-----.-----.
|   |___|  -__|   _|  |  |  -__|   _|  |  -__|__ --|__ --|
|____   |_____|__|  \___/|_____|__| |__|_____|_____|_____|
|   |   |             The Serverless Application Framework
|       |                           serverless.com, v1.23.0
 -------'

Serverless: Successfully generated boilerplate for template: "aws-java-maven"
Serverless: NOTE: Please update the "service" property in serverless.yml with your service name

Set up an authentication proxy for the build (only if needed)

If a PC exists under Authentication Proxy, a connection error will occur during build, so enter the host name, port, ID, and password in the following format in maven settings.xml. Register both HTTP and HTTPS.

settings.xml


<proxies>
 <proxy>
   <id>optional-1</id>
   <active>true</active>
   <protocol>http</protocol>
   <host>hostname</host>
   <port>port</port>
   <username>ID</username>
   <password>password</password>
   <nonProxyHosts>localhost</nonProxyHosts>
 </proxy>
 <proxy>
   <id>optional-2</id>
   <active>true</active>
   <protocol>https</protocol>
   <host>hostname</host>
   <port>port</port>
   <username>ID</username>
   <password>password</password>
   <nonProxyHosts>localhost</nonProxyHosts>
 </proxy>
</proxies> 

Jar file packaging

The jar file you upload to AWS Lambda should be consolidated, including the dependent jars. Therefore, describe the following plugin in pom.xml.

pom.xml


       <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-shade-plugin</artifactId>
          <version>2.3</version>
          <configuration>
            <createDependencyReducedPom>false</createDependencyReducedPom>
          </configuration>
          <executions>
            <execution>
              <phase>package</phase>
              <goals>
                <goal>shade</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>

Then, from the DOS prompt, change to the directory where pom.xml exists and execute mvn package shade: shade.

E:\workspace\serverlesssample>mvn package shade:shade

If the build and packaging are successful, a jar file will be created under the target directory.

Deploy to AWS Lambda

Fix serverless.yml

In order to deploy using the serverless framework, you need to modify serverless.yml in part. Since the values set in the AWS CLI are used for the region to be released and the ID used for the deploy, there is no need to modify the configuration file. In the case of a rudimentary application, it seems to work with the following definition.

serverless.yml


service: sevice-name  #Decide and describe the service name yourself

provider:
  name: aws
  runtime: java8
  stage: prod

package:
  artifact: target/alexa-skills-kit-samples-1.0.jar #Define the jar generated by the above procedure

functions:
  AlexaSkillsRecipe: #Describe the Function name
    handler: jp.co.saison.lambda.alexa.recipe.RecipeSpeechletRequestStreamHandler #Describe the handler including the package

environment: #Describe Key and Value for the items you want to set in the environment variable of lambda
  ALEXA_APP_ID: ******
  RAKUTEN_APP_ID: *******

Deploy using Serverless

Start PowerShell as an administrator and change to the directory where you placed serverless.yml. Running serverless deploy -v will deploy the target jar to AWS Lambda.

E:\workspace\serverlesssample>serverless deploy -v
Serverless: Packaging service...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
CloudFormation - UPDATE_IN_PROGRESS - AWS::CloudFormation::Stack - 
CloudFormation - UPDATE_IN_PROGRESS - AWS::Lambda::Function - 
CloudFormation - UPDATE_COMPLETE - AWS::Lambda::Function - 
CloudFormation - UPDATE_COMPLETE_CLEANUP_IN_PROGRESS - AWS::CloudFormation:
CloudFormation - UPDATE_COMPLETE - AWS::CloudFormation::Stack - arima-prod

Checking lambda on AWS

You can check whether the deployment was performed correctly by searching by the name of the Lambda function from the following URL. https://console.aws.amazon.com/lambda/

The above is how to deploy a Java application using Serverless Framework. AWS Lambda already has many uses. The following books are relatively new and practical, so I recommend you to find out what kind of usage is effective. Practice AWS Lambda ~ A new application platform that realizes "serverless" ~

Recommended Posts

How to deploy Java to AWS Lambda with Serverless Framework
How to use Java framework with AWS Lambda! ??
How to deploy a container on AWS Lambda
How to use Java API with lambda expression
How to use Java lambda expressions
How to deploy a kotlin (java) app on AWS fargate
Install gem in Serverless Framework and AWS Lambda with Ruby environment
How to compile Java with VsCode & Ant
[Java] How to compare with equals method
How to use BootStrap with Play Framework
How to deploy
AWS Lambda with Java starting now Part 1
You can do it right away with Serverless Framework Serverless on AWS (API + Lambda [java] is easy to set up)
How to deploy to AWS using NUXTJS official S3 and CloudFront? With docker-compose
Getting Started with Micronaut 2.x ~ Native Build and Deploy to AWS Lambda ~
[Java] How to test for null with JUnit
Deploy Java web app to Azure with maven
[Java] Summary of how to abbreviate lambda expressions
Deploy Rails to ECS Fargate with AWS Copilot
How to deploy a system created with Java (Wicket-Spring boot) to an on-campus server
How to call functions in bulk with Java reflection
Submit a job to AWS Batch with Java (Eclipse)
[Java] How to omit spring constructor injection with Lombok
[Java] How to encrypt with AES encryption with standard library
How to build Java development environment with VS Code
[Java] How to start a new line with StringBuilder
Get started with serverless Java with the lightweight framework Micronaut!
Use Lambda Layers with Java
[Java] How to use Map
[AWS] How to check logs
How to lower java version
[Java] How to use Map
How to uninstall Java 8 (Mac)
Java to play with Function
Java --How to make JTable
How to use java Optional
How to deploy on heroku
How to minimize Java images
How to write java comments
How to use java class
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to display Wingdings
[Java] Introduction to lambda expressions
[Java] How to use string.format
How to number (number) with html.erb
How to use Java Map
How to update with activerecord-import
How to set Java constants
Connect to DB with Java
Connect to MySQL 8 with Java
How to use Java variables
Build AWS Lambda with Quarkus
How to convert Java radix
[Java] How to implement multithreading
[Java] How to use Optional ①
How to initialize Java array
How to decompile apk file to java source code with MAC
Serverless Framework template to schedule start / stop EC2 on Lambda
How to use trained model of tensorflow2.0 with Kotlin / Java
Regularly post imaged tweets on Twitter with AWS Lambda + Java