aws cli: Invoking a Lambda and tailing the log output

If you invoke a Lambda and include the —log-type Tail param, you’ll get a bunch of encoded output like:

{
    "StatusCode": 200,
    "LogResult": "MDIxLTA3LTE4IDAzOjAzOjU...

To decode it to readable output, you need to pipe it into a base64 util to decode, like:

aws lambda invoke local --region us-west-1 --function-name your-function-name --log-type Tail | base64 -d

This is covered in the docs here.

aws cli : Listing Lambda functions and filtering with jq

‘aws lambda list-functions’ returns function details in your current region, but the info is sometimes too verbose when you’re looking for a list of names:

{
    "Functions": [
{
    "FunctionName": "example1",
    "FunctionArn": "arn:aws:lambda:us-west-2:111111111:function:example1",
    "Runtime": "java8",
    "Role": "arn:aws:iam::111111111:role/example-role",
    "Handler": "package.YourHandler::myHandler",
    "CodeSize": 3381385,
    "Description": "",
    "Timeout": 6,
    "MemorySize": 1024,
    "LastModified": "2021-01-13T08:18:33.727+0000",
    "CodeSha256": "aaabbbccc=",
    "Version": "$LATEST",
    "TracingConfig": {
      "Mode": "PassThrough"
    },
    "RevisionId": "aa-bb-cc-dd"
  },
  {
    "FunctionName": "example2",
    "FunctionArn": "arn:aws:lambda:us-west-2:111111111:function:example2",
    "Runtime": "java8",
    "Role": "arn:aws:iam::111111111:role/example-role",
    "Handler": "package.YourHandler2::myHandler",
    "CodeSize": 3381385,
    "Description": "",
    "Timeout": 6,
    "MemorySize": 1024,
    "LastModified": "2021-01-13T08:18:33.727+0000",
    "CodeSha256": "aaabbbccc=",
    "Version": "$LATEST",
    "TracingConfig": {
      "Mode": "PassThrough"
    },
    "RevisionId": "aa-bb-cc-dd"
  }
]
}

Passing this into JQ you can filter to display any of the properties easily with patterns like:

aws lambda list-functions | jq '.Functions[].FunctionName

Serverless Framework: AWS Lambdas with scheduled events and parameters

To configure an AWS Lambda to get triggered by a CloudWatch event, you can use the ‘schedule’ event in your config:

functions:
  your-function-name:
    handler: your.Handler
    timeout: 30
    events:
      - schedule:
          rate: rate(12 hours)
          input:
            puzzles : "2"
            targetGivens : "20"

You can also pass parameters from the CloudWatch event when your Lambda is invoked by listing them under ‘input’ (this is optional if your Lambda doesn’t take any parameters).

There schedule config is covered in the docs here, but there doesn’t seem to be any official docs for input, but I found this in a reply to a question here.

Creating a Serverless framework project with Java Lambdas

The Serverless.com cli gives 2 Lambda project type options for new projects – Node,js and Python:

% serverless  
 Serverless: No project detected. Do you want to create a new one? Yes
 Serverless: What do you want to make? 
   AWS Node.js 
   AWS Python 
 ❯ Other 

If you select Other, it prompts you to create a project using a template:

Run “serverless create --help” to view available templates and create a new project from one of those templates.

The ‘create –help’ option tells you to run with the –template option and provides a long list of supported project types. Since I’m using Maven with Java, I’ll use the aws-java-maven option:

serverless create --template 

Since I already had a Maven pom.xml in place as a starting point for my Lambdas in this test project, the serverless cli warns that it won’t overwrite the existing file. I’m not familiar with what additional dependencies the aws-maven-template will add, so I renamed my pom.xml and reran the ‘serverless create’ cli and generated a new pom.xml.

Looking in the new file, there’s a similar and expected use of the Maven Shade plugin to bundle a ‘fat jar’ and other dependencies for Log4J and the addition of Jackson for json parsing.

There’s also a couple of extra Classes generated too that I wasn’t expecting, but they match up with the example code in the serverless docs (article here), so there’s a ApiGatewayResponse class that I wasn’t familiar with (from building AWS Lambdas with Java by hand and not using the API Gateway Lambda Proxy feature).

As a test, I looked into creating a couple of Java Lambdas not using the generated Classes just to confirm that there’s nothing Serverless framework specific that needs to be used. As it turns out, the default usage of the APIGateway Lambda Proxy feature the Lambda runtime is is expecting to map a json payload into the handler parameters and similarly for the response payload. For testing I just wanted to pass a couple of String request params on a GET request. So for my first test I got the following exception:

An error occurred during JSON parsing: java.lang.RuntimeExceptionjava.lang.RuntimeException: An error occurred during JSON parsingCaused by: java.io.UncheckedIOException: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: lambdainternal.util.NativeMemoryAsInputStream@4cf777e8; line: 1, column: 78] (through reference chain: java.util.LinkedHashMap["headers"])Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: lambdainternal.util.NativeMemoryAsInputStream@4cf777e8; line: 1, column: 78] (through reference chain: java.util.LinkedHashMap["headers"])    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)  

At this point I got distracted with a wide range of Java Lambda together with the API Gateway Lambda Proxy specific issues which I covered in a separate post here.

Long story short, the Serverless config for a Java Lambda enables the API Gateway Lambda Proxy feature by default, which means your Lambda impl needs to have a POJO class for it’s return type that matches exactly what API Gateway expects, so the Lambda to API Gateway Proxy integration can map the return value to the expected JSON structure. You can build this yourself to match what is described in the docs (link above) or just use the provided class generated by the aws-java-lambda template. The generated class ApiGatewayResponse is exactly what you need, so rather than reinventing the wheel I changed to use this generated class as the return value from my Java Lambda handler and now it works as expected.

My handler now looks like this:

public class MyHandler implements RequestHandler, ApiGatewayResponse> {

    @Override public ApiGatewayResponse handleRequest(Map<String, Object> input, 
        Context context) {
    }
}

Note that in order to receive parameters from incoming requests via API Gateway proxy, the first parameter needs to be a Map<String, Object>.

This is the first time I’ve used API Gateway Lambda Proxy with Java Lambdas. Previously the JavaLambdas I’ve built took advantage of API Gateway mapping any parameters to your Lambda automatically using Jackson to a POJO parameter on your Handler method, and even handing a POJO return type serializing that to a JSON response for you. I’ll come back and do some comparisons between these two approaches later.

To deploy your Java Lambda using serverless it’s the same as with Node.js Lambdas or any other supported runtime:

serverless deploy

To test calling your Java Lamdba function locally as if it’s deployed to AWS, use

serverless invoke local --function functionName

where functionName is what to defined your handler as in your serverless.yml.

By default the generated ApGatewayResponse class doesn’t have a toString() so you’ll see the response to your local test print something like:

com.serverless.ApiGatewayResponse@9301672

but you can add a toString() to help with testing locally (this is mentioned in the docs here).

The servless.com framework saves a lot of time in automating the deployment and configuration of your Lambdas and is well worth a look.