Skip to content

Local Development

ganmath edited this page Apr 8, 2025 · 1 revision

step-by-step guide with a detailed sample for building an AWS Lambda in Java, orchestrated using AWS Step Functions, and deployed using the AWS SAM CLI.


🧰 Tools & Technologies Used

  • Java 17 (can use 11 or 8 too)
  • AWS Lambda
  • AWS Step Functions
  • AWS SAM CLI
  • Maven
  • AWS CLI
  • Docker (for build)
  • IAM Roles

📦 Step 1: Install Prerequisites

Install the following:


🧱 Step 2: Create a New SAM App

sam init
  • Template: AWS Quick Start Templates
  • Runtime: java17
  • Package Type: Zip
  • Application Name: stepfunction-java-app
  • Example: Hello World Example

📁 Folder Structure

stepfunction-java-app/
├── events/
├── src/
│   └── main/java/helloworld/
│       ├── App.java              # Entry point
│       └── HelloWorldHandler.java
├── template.yaml                 # SAM template
├── pom.xml

🧑‍💻 Step 3: Create Lambda Functions

We'll create two functions: StartFunction and ProcessFunction.

A. StartFunction.java

package helloworld;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

import java.util.HashMap;
import java.util.Map;

public class StartFunction implements RequestHandler<Map<String,Object>, Map<String,String>> {

    @Override
    public Map<String, String> handleRequest(Map<String, Object> event, Context context) {
        Map<String, String> output = new HashMap<>();
        output.put("status", "started");
        output.put("inputValue", event.getOrDefault("inputValue", "default").toString());
        return output;
    }
}

B. ProcessFunction.java

package helloworld;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

import java.util.Map;

public class ProcessFunction implements RequestHandler<Map<String,String>, String> {

    @Override
    public String handleRequest(Map<String, String> event, Context context) {
        return "Processed input value: " + event.get("inputValue");
    }
}

📝 Step 4: Update template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Step Function with Java Lambdas

Resources:
  StartFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: .
      Handler: helloworld.StartFunction
      Runtime: java17
      MemorySize: 512
      Timeout: 10

  ProcessFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: .
      Handler: helloworld.ProcessFunction
      Runtime: java17
      MemorySize: 512
      Timeout: 10

  MyStateMachine:
    Type: AWS::Serverless::StateMachine
    Properties:
      Definition:
        StartAt: Start
        States:
          Start:
            Type: Task
            Resource: !GetAtt StartFunction.Arn
            Next: Process
          Process:
            Type: Task
            Resource: !GetAtt ProcessFunction.Arn
            End: true
      Role: !GetAtt StepFunctionRole.Arn

  StepFunctionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: states.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: LambdaInvokePolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - lambda:InvokeFunction
                Resource: "*"

🔨 Step 5: Build and Deploy

Build

sam build

Deploy

sam deploy --guided

Answer the prompts:

  • Stack Name: StepFunctionJavaStack
  • Region: us-east-1 (or your preferred one)
  • Confirm changes before deploy: Y
  • Allow SAM to create IAM roles: Y

🚀 Step 6: Test the State Machine

After deployment:

aws stepfunctions start-execution \
  --state-machine-arn <ARN_FROM_DEPLOY_OUTPUT> \
  --input '{"inputValue": "Test123"}'

You can also test via the AWS Console (Step Functions > Executions).


📓 Notes

🔁 Why Use Step Functions?

  • Orchestrate multiple Lambdas with retry, parallel, choice, etc.
  • Visual workflows
  • Makes microservices coordination easier

🔐 IAM Role Tips

  • Ensure your state machine's IAM role has lambda:InvokeFunction permissions
  • Keep Lambda execution roles with least privilege

🧪 Unit Testing (Optional)

Use junit and mockito in pom.xml to write unit tests for handler logic.


🪜 Next Steps

  • Add choice, parallel, or map states in Step Functions
  • Integrate DynamoDB, SQS, or SNS within the flow
  • Use EventBridge to trigger Step Functions on events

Clone this wiki locally