DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. AWS Lambda for Beginners

AWS Lambda for Beginners

Check out Mashooq Badar's introduction to Amazon's Lambda service with code samples.

Mashooq Badar user avatar by
Mashooq Badar
·
May. 17, 16 · Tutorial
Like (7)
Save
Tweet
Share
7.08K Views

Join the DZone community and get the full member experience.

Join For Free

AWS Lambda is a compute service from Amazon. It makes deployment and provisioning very simple and fits very well with microservices-based architecture. You can find out more about AWS Lambda here. Currently, supported platforms are JVM, Node.js, and Python.

The programming model for the lambdas consists of Handler, Context Object, Logging, and Exceptions. These are described here. Lambda must not hold state because they are brought up and down and replicated as needed. Persistent state should be stored in a service that is outside the lifecycle of the lambda such as Amazon DynamoDB, S3 etc.

Image title


First of all follow the instructions here to setup an AWS Account and AWS Command-line Interface and note down your account id.

Step 1: The Code

The most basic lambda will look like the following in Python:

def lambda_handler(event, context):
  return "Hello World!"

Or like the following in Java:

package example;

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

public class Hello {
    public String lambdaHandler(String event, Context context) {
        return "Hello World!";
    }
}

You can follow the, somewhat lengthy, instructions here to deploy this function … but that’s no fun! Let’s do it DevOps style ;)

Paste the above Python code in a file called helloworld.py. If you want to use the Java version then follow the instructions here to build your lambda and create a deployment package using Maven.

Step 2: The Role

Create a trust.json file . The trust allows our function to assume the role of an AWS Lambda.

In trust.json we are allowing the function to assume the role of a lambda.amazonaws.com service, otherwise the infra will not allow our function to run.

{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "",
    "Effect": "Allow",
    "Principal": {
      "Service": "lambda.amazonaws.com"
    },
    "Action": "sts:AssumeRole"
  }]
}

Step 3: The Deployment

Create the following script (deploy.sh). Note: the script assumes that you have the AWS_ACCOUNT_ID environment variable set.

#!/bin/bash

### Create the lambda package
zip -j helloworld.zip *.py

### Create the role for the lambda to assume
role="helloworld_exec_role"
trust="trust.json"
aws iam create-role --role-name $role --assume-role-policy-document file://$trust
aws iam update-assume-role-policy --role-name $role --policy-document file://$trust

### Create the lambda function
function_name="helloworld"
handler_name="helloworld.lambda_handler"
package_file=helloworld.zip
runtime=python2.7
aws lambda create-function \
  --function-name $function_name \
  --handler $handler_name \
  --runtime $runtime \
  --memory 512 \
  --timeout 60 \
  --role arn:aws:iam::${AWS_ACCOUNT_ID}:role/$role \
  --zip-file fileb://$package_file

Or for Java:

#!/bin/bash

### Create the lambda package
mvn package

### Create the role for the lambda to assume
role="helloworld_exec_role"
trust="trust.json"
aws iam create-role --role-name $role --assume-role-policy-document file://$trust
aws iam update-assume-role-policy --role-name $role --policy-document file://$trust

### Create the lambda function
function_name="helloworld"
handler_name="example.Hello::lambdaHandler"
package_file="target/lambda-java-example-1.0-SNAPSHOT.jar"
runtime="java8"
aws lambda create-function \
  --function-name $function_name \
  --handler $handler_name \
  --runtime $runtime \
  --memory 512 \
  --timeout 60 \
  --role arn:aws:iam::${AWS_ACCOUNT_ID}:role/$role \
  --zip-file fileb://${package_file}

Make the script executable chmod +x deploy.sh and deploy your lambda ./deploy.sh. You may get the following error: "The role defined for the function cannot be assumed by Lambda." This is because the role has not been replicated through in the Amazon infra. Just run the deploy script again. It will complain that the role already exists but this time the lambda creation should pass. In the future we will look at a status check to make sure that the role has been fully created before we deploy the function.

Step 5: The Execution!

Invoke your lambda with the below command. You should see the result in the file called output.txt

aws lambda invoke --invocation-type RequestResponse --function-name helloworld --payload '[""]' output.txt

Step 6: The Cleanup

To delete the lambda function and then the role paste the following in delete.sh

#!/bin/bash
role="helloworld_exec_role"
function_name="helloworld"
aws lambda delete-function --function-name $function_name
aws iam delete-role --role-name $role

Then make the script executable chmod +x delete.sh and execute ./delete.sh

Step 7: Relax... You Have Arrived ;)

... and wait for the next post on AWS frolics.

This article was first published on the Codurance blog.

AWS AWS Lambda

Published at DZone with permission of Mashooq Badar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Submit a Post to DZone
  • DZone's Article Submission Guidelines
  • The 5 Books You Absolutely Must Read as an Engineering Manager
  • How To Handle Secrets in Docker

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: