Search code examples
amazon-web-servicesaws-lambdaaws-sam-cliaws-sam

AWS SAM: java8/gradle app fails with ClassNotFound when deployed (but runs fine locally)


Description:

A java8 app runs locally after doing sam build; sam local invoke... but fails with ClassNotFound exception when deployed using sam package; sam deploy

Steps to reproduce the issue:

  1. Initialise a Java8/gradle app: sam init -r java8 -d gradle && cd sam-app
  2. Run sam build: sam build --use-container
  3. Observe that the function runs successfully locally (this fails with the same ClassNotFound exception without the sam build above): sam local invoke HelloWorldFunction --no-event
  4. Package + deploy:
sam package --template-file template.yaml --output-template-file packaged.yaml --s3-bucket <some bucket name>
sam deploy --template-file packaged.yaml  --stack-name java8-gradle-test --capabilities CAPABILITY_IAM --region eu-west-2 --no-fail-on-empty-changeset
  1. In AWS Lambda console, find the function java8-gradle-test-HelloWorldFunction-..., add an arbitrary test event and click test

Observed result:

Execution result: failed

Logs:

START RequestId: a5e25d74-4a0d-4763-b7a7-383aeede5c82 Version: $LATEST
Class not found: helloworld.App: java.lang.ClassNotFoundException
java.lang.ClassNotFoundException: helloworld.App
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)

END RequestId: a5e25d74-4a0d-4763-b7a7-383aeede5c82
REPORT RequestId: a5e25d74-4a0d-4763-b7a7-383aeede5c82  Duration: 58.33 ms  Billed Duration: 100 ms     Memory Size: 128 MB Max Memory Used: 69 MB  

Expected result:

The same successful response as when I ran sam local invoke for this function.


There seems to be some unexpected difference between what's happening with sam local invoke and with sam package, with the latter not picking up artifacts from sam build.


Solution

  • Solved! This is fixed by using sam package --output-template-file packaged.yaml --s3-bucket <some bucket name> instead, ie not specifying the template file. Obviously sam local invoke was picking up the built one, but I wasn't allowing sam package to. See explanation on https://github.com/awslabs/aws-sam-cli/issues/978