38,39 €
Build, secure, and deploy a real-world serverless application and explore the exciting world of cloud offerings including Azure, Google Cloud, and IBM Cloud
Managing physical servers will be a thing of the past once you’re able to harness the power of serverless computing. If you’re already prepped with the basics of serverless computing, Serverless Programming Cookbook will help you take the next step ahead. This recipe-based guide provides solutions to problems you might face while building serverless applications.
You'll begin by setting up Amazon Web Services (AWS), the primary cloud provider used for most recipes. The next set of recipes will cover various components to build a Serverless application including REST APIs, database, user management, authentication, web hosting, domain registration, DNS management, CDN, messaging, notifications and monitoring. The book also introduces you to the latest technology trends such as Data Streams, Machine Learning and NLP. You will also see patterns and practices for using various services in a real world application. Finally, to broaden your understanding of Serverless computing, you'll also cover getting started guides for other cloud providers such as Azure, Google Cloud Platform and IBM cloud.
By the end of this book, you’ll have acquired the skills you need to build serverless applications efficiently using various cloud offerings.
For developers looking for practical solutions to common problems while building a serverless application, this book provides helpful recipes. To get started with this intermediate-level book, knowledge of basic programming is a must.
Heartin Kanikathottu is a senior software engineer and blogger with around 11 years of IT experience. He is currently working as a Senior Member of Technical Staff at VMware. He has previously worked with companies including Software AG, SAP Ariba and TCS. He has a masters degree in cloud computing and bachelors degree in computer science. He has completed 10 professional certifications on the areas of cloud computing, coding and design from companies including AWS, Pivotal, Oracle, Microsoft, IBM and Sun. He likes to share his technical knowledge through his blogs such as CloudMaterials and JavaJee. He also likes to mentor juniors and take technical sessions at work, meetups and conferences.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 430
Veröffentlichungsjahr: 2019
Copyright © 2019 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Merint MathewsAcquisition Editor: Karan SadawanaContent Development Editor: Anugraha ArunagiriTechnical Editor: Divya VadhyarCopy Editor: Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Rekha NairGraphics: Tom ScariaProduction Coordinator: Deepika Naik
First published: January 2019
Production reference: 1310119
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78862-379-7
www.packtpub.com
To my wife, Sneha; baby girl, June Grace; mother, Dr. Gresamma Mathew; and above all, God almighty.
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Heartin Kanikathottu is a senior software engineer and blogger with around 11 years of IT experience. He is currently working as a Senior Member of Technical Staff at VMware. He has previously worked with companies including Software AG, SAP Ariba and TCS. He has a masters degree in cloud computing and bachelors degree in computer science. He has completed 10 professional certifications on the areas of cloud computing, coding and design from companies including AWS, Pivotal, Oracle, Microsoft, IBM and Sun. He likes to share his technical knowledge through his blogs such as Heartin.tech, CloudMaterials.com and JavaJee.com. He also likes to mentor juniors and take technical sessions at work, meetups and conferences.
Sneha Thomas is a full stack developer with 8 years of IT experience. She considers herself to be an excellent UI developer with good backend skills. She has worked on technologies such as Angular, Java, Spring, Hibernate, databases and various web technologies such as HTML, JavaScript and CSS. She also has good knowledge of the cloud platforms such as AWS and Google Cloud Platform. She has got a masters degree with specialization in cloud computing and a bachelors degree in electronics and communications. During her free times she like to experiment with new technologies and write blogs on JavaJee.com.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Serverless Programming Cookbook
Dedication
About Packt
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Getting Started with Serverless Computing on AWS
Introduction
Getting started with the AWS platform
Getting ready
How to do it...
How it works...
AWS Identity and Access Management (IAM) 
Amazon CloudWatch
Multi-Factor Authentication (MFA)
There's more...
See also
Your first AWS Lambda
Getting ready
Code repository usage guidelines
How to do it...
How it works...
About the parent POM
Lambda roles
Lambda runtimes
Extra dependencies
There's more...
Other ways to create Lambda functions from the management console
Other ways to deploy code in a Lambda function
Passing JSON to and from Lambda handler
See also
Your first Lambda with AWS CLI
Getting ready
Configuring AWS CLI
Creating S3 bucket
Note for Windows users
How to do it...
How it works...
Creating a role and attaching a policy
Lambda memory-size and timeout
S3 Bucket and Key
Cleaning up
There's more...                          
See also
Your first Lambda with Amazon CloudFormation
Getting ready
Set up the project and S3 bucket
Understanding YAML and JSON
How to do it...
Cleaning up roles, policy, and Lambda
How it works...
There's more...
CloudFormation Template Components
Resource component
Intrinsic functions
CloudFormation Designer
Additional benefits of CloudFormation 
Cloud Formation alternatives
See also
Using AWS SDK, Amazon CloudFormation, and AWS CLI with Lambda
Getting ready
How to do it...
Creating the POJOs for requests and response.
How it works...
There's more...
Pseudo-parameters
See also
Dev Practices – dependency injection and unit testing
Getting ready
Code refactoring
How to do it...
How it works...
There's more...
See also
Your first Lambda with serverless framework
Getting ready
How to do it...
How it works...
There's more...
See also
Building Serverless REST APIs with API Gateway
Introduction
Building your first API using the AWS CLI
Getting ready
How to do it...
How it works...
HTTP essentials
REST essentials
Parts of a URL
There's more...
See also
Building your first API using Amazon CloudFormation
Getting ready
How to do it...
How it works...
There's more...
See also
Building your first API with Lambda integration
Getting ready
How to do it...
Creating the Lambda
Creating a REST API with AWS CLI commands
Creating a REST API with a CloudFormation template
How it works...
CLI commands
CloudFormation template components
There's more...
See also
Building and testing your first POST API method
Getting ready
How to do it...
Creating the API with CLI commands
Creating the API with a CloudFormation template
Testing with Postman 
How it works...
Passthrough behavior
There's more...
See also
Mapping requests and responses with mapping templates
Getting ready
How to do it...
Mapping requests
Mapping responses
Creating the API using CLI commands
Creating the API with a CloudFormation template
Testing the API
How it works...
Mapping templates and variables
Using #set
There's more...
The Apache Velocity Language
JSONPath expressions
See also
Validating request payloads with models
Getting ready
How to do it...
The request data format
Creating the API with CLI commands
The CloudFormation template
Testing the API
How it works...
There's more...
See also
Lambda and API with proxy integration
Getting ready
How to do it...
Creating a Lambda function for proxy integration
Deploying the Lambda
Creating the Proxy API with CLI commands
Creating the API using CloudFormation templates
How it works...
The greedy path, the ANY HTTP method, and proxy integration
RequestStreamHandler versus RequestHandler
The input and output format of a Lambda function for proxy integration
There's more...
See also
Data Storage with Amazon DynamoDB
Introduction
Your first DynamoDB table
Getting ready
How to do it...
Creating a table using CLI commands
Creating a table using a CloudFormation template
How it works...
DynamoDB data model 
Data model limits
DynamoDB keys and partitions
Read and write capacity units
Waiting for asynchronous operations
Other ways to create tables
There's more...
DynamoDB features
DynamoDB general limitations 
Local and global secondary indexes
See also
Throughput provisioning examples
Getting ready
How to do it...
Scenario 1
Scenario 2
Scenario 3
How it works...
Strongly consistent reads versus eventually consistent reads
Limits on throughput updates within a day
There's more...
See also
Working with data from the CLI
Getting ready
How to do it...
Adding items
Reading items
Updating items
Deleting items
How it works...
Add, update, and delete operations
Reading data from DynamoDB
return-consumed-capacity
There's more...
See also
Using the DynamoDB SDK from Lambda
Getting ready
How to do it...
How it works...
AmazonDynamoDB client versus DynamoDB wrapper client
IAM policy and actions
Single Lambda versus multiple Lambdas
There's more... 
See also
Creating tables from Lambda
Getting ready
How to do it...
How it works...
There's more...
See also
Adding data items from Lambda
Getting ready
How to do it...
How it works...
There's more...
See also
Reading data from Lambda
Getting ready
How to do it...
How it works...
There's more...
See also
Application Security with Amazon Cognito
Introduction
Creating a Cognito user pool
Getting ready
How to do it...
Creating Cognito user pool with AWS CLI
Creating Cognito user pool with CloudFormation template
How it works...
Generating and using JSON templates with CLI commands
AliasAttributes versus UsernameAttributes
There's more...
See also
Server-side authentication flow
Getting ready
How to do it...
Creating Cognito user pool client
Creating a Cognito user pool client with AWS CLI
Creating a Cognito user pool client with CloudFormation template
Server-side authentication flow
How it works...
Server-side, client-side, and custom authentication flows
Secure Remote Password protocol
The access token, refresh token, and ID token
ADMIN_NO_SRP_AUTH versus USER_PASSWORD_AUTH
There's more...
See also
Client-side authentication flow
Getting ready
How to do it...
Creating a Cognito user pool client
Creating a Cognito user pool client with AWS CLI
Creating a Cognito user pool client with CloudFormation template
Client-side authentication flow
How it works...
There's more...
See also
User sign-up flow with Cognito
Getting ready
How to do it...
User sign-up with self-confirmation
User sign-up with admin confirmation
How it works...
There's more...
See also
Working with groups
Getting ready
How to do it...
How it works...
There's more...
See also
Integrating Cognito with the API gateway
Getting ready
How to do it...
The AWS CLI
The CloudFormation template
How it works...
Claim-based identity
There's more...
See also
User sign-up with SMS verification and MFA
Getting ready
How to do it...
Creating the user pool
Creating a Cognito user pool client with AWS CLI
Creating a Cognito user pool client with CloudFormation template
User sign-up with SMS and MFA verification
How it works...
There's more...
See also
Web Hosting with S3, Route53, and CloudFront
Introduction
Setting up an S3 static website
Getting ready
How to do it...
AWS CLI commands
The CloudFormation template
How it works...
There's more...
See also
Setting up CloudFront for an S3 website
Getting ready
How to do it...
AWS CLI commands
Understanding the DistributionConfig defaults in the response
The CloudFormation template
How it works...
There's more...
See also
Registering a domain name with Route 53
Getting ready
How to do it...
Registering a domain with AWS CLI commands
How it works...
Hosted zones
There's more...
Registering a domain from AWS Management Console
See also
Using domains registered with other registrars
Getting ready
How to do it...
AWS CLI commands
The CloudFormation template
How it works...
DNS propagation
There's more...
Steps for configuring DNS from the AWS Management Console
See also
Using custom domains with S3 static websites
Getting ready
How to do it...
AWS CLI commands
The CloudFormation template
How it works...
There's more...
See also
Using custom domain names with CloudFront
Getting ready
How to do it...
AWS CLI commands
The CloudFormation template
The CloudFront distribution stack
The RecordSet stack
How it works...
There's more...
Using HTTPS to secure your domain URL
Disabling and deleting a CloudFront distribution
See also
Using HTTPS with a CloudFront domain
Getting ready
How to do it...
Associating a certificate with a domain using AWS CLI commands
Associating a certificate with a domain using CloudFormation template
How it works...
Server Name Identification (SNI)
There's more...
See also
Messaging and Notifications with SQS and SNS
Introduction
Your first SQS queue (AWS CLI + CloudFormation)
Getting ready
How to do it...
Creating an SQS queue
AWS CLI commands
The CloudFormation template
Sending and receiving data (AWS CLI)
How it works...
There's more...
See also
Creating an SQS queue and sending messages with SDK (Java)
Getting ready
How to do it...
Lambda project code (Java)
Provisioning and testing the Lambda (AWS CLI)
How it works...
There's more...
See also
Receiving and sending SQS messages in batches with SDK (Java)
Getting ready
How to do it...
Lambda project code (Java)
Setting up queues and data
Provisioning and testing the Lambda (AWS CLI)
How it works...
There's more...
See also
Invoking the Lambda with an SQS event (Java)
Getting ready
How to do it...
Lambda project code (Java)
Setting up queues and data
Provisioning the Lambda (AWS CLI)
Testing the Lambda (AWS CLI)
How it works...
There's more...
See also
Your first SNS topic for email and SMS (AWS CLI + CloudFormation)
Getting ready
How to do it...
Creating an SNS topic
AWS CLI 
The CloudFormation template
Creating email and SMS subscriptions (AWS CLI)
SMS subscription
Email subscription 
Publishing a message
How it works...
There's more...
See also
Publishing to an SNS topic with SDK (Java)
Getting ready
How to do it...
Lambda project code (Java)
Provisioning and testing the Lambda (AWS CLI)
How it works...
There's more...
See also
Invoking a Lambda with SNS events (Java)
Getting ready
How to do it...
Lambda project code (Java)
Provisioning the Lambda (AWS CLI)
Testing the Lambda (AWS CLI)
How it works...
There's more...
See also
Redshift, Amazon ML, and Alexa Skills
Introduction
Your first Kinesis data stream (AWS CLI)
Getting ready
How to do it...
Step 1 - Creating a Kinesis data stream
Using AWS CLI
Using the CloudFormation template
Step 2 - Adding and retrieving data
How it works...
Kinesis shard iterator types
There's more...
See also
Writing data into Kinesis Stream with SDK (Java)
Getting ready
How to do it...
Step 1 - Creating the Lambda project (Java)
Step 2 - Provisioning and testing Lambda (AWS CLI)
How it works...
There's more...
See also
Invoking Lambda with Kinesis events (Java)
Getting ready
How to do it...
Step 1 - Creating a Lambda project (Java)
Step 2 - Provisioning and testing Lambda (AWS CLI)
How it works...
There's more...
See also
Using Amazon ML for binary classification (AWS CLI)
Getting ready
How to do it...
How it works...
Types of models
DataSource object
Receiver Operating Characteristic and Area Under the ROC
There's more...
See also
Building and testing an Alexa skill (Java for Lambda, CLI for Alexa skill)
Getting ready
Installing and configuring the ASK CLI
Configuring ask-cli for the first time
How to do it...
Step 1 - Creating the Lambda project (Java)
Step 2 - Provisioning Lambda (AWS CLI)
Step 3 - Building an Alexa skill with ASK CLI
How it works...
Alexa skill invocation basics
Explaining the Lambda project (Java)
Explaining the ASK CLI steps
There's more...
Voice app platforms
See also
Monitoring and Alerting with Amazon CloudWatch
Introduction
Checking logs, insights, and metrics (Console)
Getting ready
How to do it...
Step 1: Logging in to the CloudWatch dashboard
Logs
Log insights
Metrics
How it works...
Log groups
Log streams
Log insights
Metrics
There's more...
See also
Your first custom metric (AWS CLI)
Getting ready
How to do it...
Step 1–Create a simple metric without dimensions 
Step 2—Add dimensions to metric data
How it works...
There's more...
See also
Setting up CloudWatch alarms (AWS CLI)
Getting ready
How to do it...
How it works...
There's more...
See also
CloudWatch alarms with dimensions (AWS CLI)
Getting ready
How to do it...
How it works...
There's more...
See also
Using CloudWatch metric log filters
Getting ready
How to do it...
Creating metric filters from AWS CLI
Creating metric filters from the console
How it works...
There's more...
See also
Serverless Programming Practices and Patterns
Introduction
Enabling CORS for the API and testing with CodePen
Getting ready
Getting familiar with CodePen
How to do it...
How it works...
There's more...
See also
Implementing and testing Cognito operations with the JavaScript SDK
Getting ready
Download the amazon-cognito-identity.min.js file
Create an S3 bucket and upload the amazon-cognito-identity.min.js file
Creating a Cognito user pool and client
How to do it...
How it works...
There's more...
See also
Federated identity with Amazon Cognito
Getting ready
How to do it...
Step 1 - Configuring Google Plus
Step 2 - Creating and Configuring an Identity Pool
Step 3 - Preparing and uploading code files
Preparing the index.html file
Deploying and testing the index.html file
How it works...
There's more...
See also
Creating SSL/TLS certificate with ACM
Getting ready
How to do it...
AWS CLI Commands
CloudFormation Template
How it works...
There's more...
See also
Fan-in and fan-out architectural patterns with AWS
Getting ready
How to do it...
Scenario 1 - Pub-Sub with multiple producers and consumers
Scenario 2 - Parallel processing without duplicates
Scenario 3 - Streaming real-time data for processing
Scenario 4 - Streaming real-time data for storing
How it works...
Real-world example scenarios
Scenario 1 - Pub-Sub scenario with multiple producers and consumers
Scenario 2 - Parallel processing 
Scenario 3 - Streaming real-time data for processing
Scenario 4 - Streaming real-time data for storage
There's more...
Building a full stack web application on AWS
See also
Other Cloud Providers
Introduction
Your first Serverless application in Azure 
Getting ready
How to do it...
Deploying the function to Azure
Getting function info from UI and verifying the deployment
How It works...
There's more...
See also
Your first serverless application on Google Cloud Platform
Getting ready
How to do it...
How it works...
There's more...
See also
Your first Serverless application on IBM cloud
Getting ready
How to do it...
How It works...
There's more...
See also
Other Books You May Enjoy
Leave a review - let other readers know what you think
Managing physical servers will be a thing of the past once you're able to harness the power of Serverless computing. This recipe-based guide provides solutions to problems you might face while building Serverless applications.
You'll begin by setting up Amazon Web Services (AWS), the primary cloud provider used for most recipes. The next set of recipes will teach you about the components you need to build a Serverless web application, such as REST APIs, database, user management, authentication, domain registration, DNS management, website hosting, and CDN. The book also provides you with a fresh perspective by introducing you to the latest technology trends with recipes based on messaging, notifications, data analytics, machine learning, and NLP. Further, the book contains recipes on DevOps practices such as logging and monitoring. AWS discussion ends with some real-world practices and patterns. Finally, to broaden your understanding of Serverless computing, you'll also cover getting started guides for other cloud providers, such as Azure, Google Cloud Platform, and IBM cloud.
The Serverless architecture allows you to build and run applications and services without having to manage the necessary infrastructure, which reduces expenditure and improves scalability. In this book, you will learn how to harness Serverless technology to reduce production time, minimize cost, and gain the freedom to customize your code, all without hindering functionality.
By the end of this book, you'll have acquired the skills you need to build Serverless applications efficiently using various public cloud offerings.
This book is aimed at developers looking for practical solutions to common problems encountered while building a Serverless application, providing helpful recipes to solve these problems. To get started with this intermediate-level book, knowledge of basic programming is a must.
Chapter 1, Getting Started with Serverless Computing on AWS, covers building Serverless applications with AWS Lambda. We will also get familiar with AWS IAM and AWS CloudFormation, two services that we will be using a lot in the coming chapters.
Chapter 2, Building Serverless REST APIs with API Gateway, will show you how to create reliable and scalable API Gateway REST APIs. Some of the API Gateway functionality, such as Cross Origin Resource Sharing (CORS), will be covered later.
Chapter 3, Data Storage with Amazon DynamoDB, contains recipes for Amazon DynamoDB, a fully managed NoSQL database, integrating DynamoDB with AWS Lambda, along with some example scenarios and solutions for throughput provisioning.
Chapter 4, Application Security with Amazon Cognito, covers how to use Amazon Cognito for user signup, user login, and user management. We will cover real-world applications of Cognito, such as federated logins, in a later chapter.
Chapter 5, Web Hosting with S3, Route53, and CloudFront, outlines recipes related to hosting a website, including registering domain names, hosting a static website with Amazon S3, attaching a custom domain for our S3 bucket, and using CloudFront CDN.
Chapter 6, Messaging and Notifications with SQS and SNS, discusses how Amazon SQS and Amazon SNS are generally used for interprocess communications within Serverless applications. We will also see how these services can be triggered in AWS Lambda.
Chapter 7, Redshift, Amazon ML, and Alexa Skills, explores how the following services can bring value to Serverless computing in the areas of analytics and natural language processing, covering Amazon Kinesis, Amazon Machine Learning, and Amazon Alexa Skill Sets.
Chapter 8, Monitoring and Alerting with Amazon CloudWatch, discusses monitoring and alerting, both of which are essential DevOps practices. We will also see CloudWatch alarms, CloudWatch metrics, and CloudWatch metric log filters.
Chapter 9, Serverless Programming Practices and Patterns, explores some patterns and practices for Serverless applications within the AWS platform. We will see how some of the services covered previously interact together, and how they are implemented in real-world projects.
Chapter 10, Other Cloud Provider Services, provides a basic understanding and some getting started guides for Serverless computing with a few other cloud providers. The main intention of this section is to explore the popular alternatives and learn to do quick setups for proof-of-concept demonstrations.
Readers should be familiar with Java, Maven, Git, and Unix/Mac terminal or the Windows Command Prompt. To work with the JavaScript recipes you also need to be familiar with JavaScript. Additional links are provided within the See more section of the recipes to explain the prerequisite technologies. To make best use of the book you should first read the book from beginning until the end, at least once. After this, or along with reading the book, you may execute the code provided within the code files following the directions given within the book, and within the repository's readme files. Example codes should specify names or IDs. You will have to replace them with the name and ID that you create. Finally, you should build the projects on your own following the book's content.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Serverless-Programming-Cookbook. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
Resources
:
MyFirstRestAPI
:
Type
: AWS::ApiGateway::RestApi
Properties
:
Name
: Greeting API
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
GreetingResource: Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref MyFirstRestAPI ParentId: !GetAtt MyFirstRestAPI.RootResourceId
Any command-line input or output is written as follows:
aws apigateway create-resource \
--rest-api-id c82tpsb7ka \
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
This chapter will cover the following topics:
Getting started with the AWS platform
Your first AWS Lambda
Your first Lambda with AWS CLI
Your first Lambda with Amazon CloudFormation
Using AWS SDK, Amazon CloudFormation, and AWS CLI with Lambda
Dev practices: dependency injection and unit testing
Your first Lambda with Serverless framework
Cloud computing introduced a pay-per-use model and abstracted physical servers with virtual machines and managed services. Cloud computing execution models include Infrastructure as a Service (IaaS), Platform as a service (PaaS), Software as a Service (SaaS), and Serverless computing (or Function as a Service (FaaS)).
IaaS provides services that form the basic building blocks of cloud computing, such as virtual machines, storage, network, and so on. PaaS provides platforms on which we can develop applications such as execution runtime, databases, web servers, and so on. Saas provides completed software that we can use for various needs such as Gmail's email service.
Serverless computing allows us to run functions (code) without worrying about servers and pay only for the time we execute code. Despite the name, servers are still present, however, the provider does all the server management including starting and stopping them to serve requests, patching and more. Serverless computing comes roughly in between PaaS and SaaS.
Amazon provides you with Free Tier to get started with AWS on production quality servers. Free Tier provides you with free access to many services and features with decent limits.
To work with AWS Free Tier, you need a decent computer, a reasonable internet connection, a working credit card, and basic knowledge of computers and the internet.
Let's get started on the AWS platform by creating a Free Tier account. We will then do some basic IAM settings as suggested by AWS. Finally, we will also create a billing alarm to keep track of any unexpected costs. If you already have a working account with basic setup done, you may skip this part of the recipe:
Go to
https://aws.amazon.com
and create a new Free Tier account (if you do not already have one) as follows:
Provide login credentials.
Provide personal information such as address, phone number, and other required details, if you have selected
Personal account
, or
Corporate information
if you have selected company account.
Provide credit card details.
Proceed with telephonic verification.
Select
Basic plan
for Free Tier account with community support (or select a paid plan if you want to).
After logging in for the first time, it is recommended that you complete the basic Identity and Access Management (IAM) security settings listed under the Security Status heading. If you have previously logged in, the options might not be displayed as shown next. If so, you need to manually go to IAM service from the Services dropdown.
Click on
Activate Multi-Factor Authentication (MFA) on your root account
and do as follows:
Click
Manage
.
Select
A Virtual MFA Device
.
Click
Continue
on the message for installing an MFA-compatible application (assuming you have installed Google Authenticator along with barcode scanner, or any similar applications).
Scan the barcode shown on screen using Google Authenticator, and enter two consecutive codes for confirmation.
Click on
Create individual IAM users
and do as follows:
Enter
Username
.
Select Access Type
(
Programmatic access and AWS Management Console access
).
Download the credentials
.csv
file to a secure area in your local machine. You will not be able to download it later, but you can regenerate it.
Click on
Use groups
to assign permissions and assign
some random permissions.
Click on
Apply an IAM password policy
to s
et up a basic password policy.
IAM dashboard should now show all security status items as green:
Create a billing alarm to have a check on accidental costs:
Go to
My Billing Dashboard
(by clicking the drop-down arrow near to your name).
Under
Alerts and Notifications
, click on
Enable Now
to
Monitor your estimated charges
.
After going to
Preferences
, select
Receive Billing Alerts
and click on
Manage Billing Alerts
link within the contents, which will take you to CloudWatch.
Click on
Billing
and create an alarm.
If you followed all previous steps successfully, you are ready to get started with further recipes in this book.
Most of the steps in this recipe are self-explanatory and similar to registering for any other paid online service. The following are the important AWS services and concepts that were introduced in this recipe.
IAM enables secure access to AWS resources. IAM supports standard security concepts such as users, groups, roles, and permissions. The user is an individual who wants to use AWS services. Users can be added to groups. Users and groups are assigned with permissions. Roles are used by a service (for example, Amazon Ec2) for accessing other services.
Amazon CloudWatch is a service that helps in monitoring your applications, responding to changes (such as performance changes and billing alarms), optimizing resource utilization, and providing you a unified view of the health of services in your account.We will see more use cases of Amazon CloudWatch in later recipes.
Multi-Factor Authentication provides additional levels of authentication. In addition to passwords, it also requires you to authenticate using a token generated by a virtual or physical authenticator. It is a good practice to set up MFA even for personal accounts, as the password is the same as the e-commerce portal and Prime Video.
The following are some of the common AWS services that are used in building Serverless applications on the AWS:
AWS Lambda
lets you write code without configuring any server.
Amazon API Gateway
lets you create REST APIs without coding.
Amazon Simple Storage Service
(
S3
) is an object store that helps you store and retrieve data. S3 can also be used for hosting
single-page applications
(
SPA
) such as an angular or react application.
Amazon DynamoDB
is a scalable NoSQL database.
Amazon CloudFront
is a
Content Delivery Network
(
CDN
) service.
Amazon CloudWatch
is a service to monitor your applications and respond to changes.
AWS CloudFormation
templates written in JSON or YAML can be used to provision and model our infrastructure.
AWS Identity and Access Management
(
IAM
) provides access control for AWS resources.
Amazon Cognito
helps you build access control for your application with features such as user sign-up, sign-in, and more.
Other services
can be used alongside these services for advanced use cases, such as natural language processing (for example, Alexa Skills kit, and Lex), Analytics (Amazon Kinesis Streams), Machine Learning (Amazon Machine Learning), and so on.
Apart from using the AWS management console from a browser, we can also interact with AWS services from AWS CLI (command line) and AWS SDK (programmatic access). Except for the first few recipes, we will mostly focus on using Amazon CloudWatch with AWS CLI for modeling and provisioning our infrastructure.
https://aws.amazon.com/getting-started
AWS Lambda is the core service in AWS for building serverless applications. You can run code without provisioning servers. You pay only for the time you run your code, unlike EC2 where you pay for the time the server is up. Lambda also takes care of high availability. You can invoke Lambdas from other AWS services, console, or AWS CLI.
In this recipe, we will create a Lambda in Java and deploy it using the AWS management console. In the next recipe, we will also explore AWS CLI to deploy Lambda. In later recipes and chapters, we will see how we can automate most of the deployment tasks using Amazon CloudWatch templates similar to how most enterprise projects do.
To follow the example in this recipe, you need a working AWS account. You should also set up Java Development Kit (JDK) and Maven in your local machine. I am currently using Java 8 and Maven 3.5.4.
Example projects in this book uses a maven parent project, serverless-cookbook-parent-aws-java.The versions of libraries used within each Lambda project (for example, aws.sdk.version) are defined in the parent project POM file.
It is a good idea to create a folder within your operating system to manage the code files for this book. I will use a folder with the name serverless. You need to make sure that you can execute the following commands from this folder:
javac -version
mvn -version
You can set up the parent project inside our parent folder (serverless in my case) by executing the following commands from the command line:
Clone
our book's Github repository:
git clone https://github.com/PacktPublishing/Serverless-Programming-Cookbook.git
Go inside the repository folder, go inside our project-specific parent project, and run
mvn clean install
:
cd Serverless-Programming-Cookbook
cd serverless-cookbook-parent-aws-java
mvn clean install
Each chapter has a directory of its own (for example, Chapter 01). Inside the chapter's directory there will be sub-directories for each recipe. The recipe specific directory has names corresponding to the recipe's title. For example, the directory for this chapter, recipe titled Your first Lambda is your-first-lambda.
Inside the recipe's directory, there will be a directory for storing all resources including the AWS CLI commands called resources. Long AWS CLI commands are split into multiple lines for better readability using the \ symbol. If you are using a Windows machine you can use the ^ symbol instead of the \ symbol in the code files or make a single line command without the \ symbol.
The recipe's directory also contains a sub-directory for each Lambda project. You need to run mvn clean package for generating the Lambda JAR from within this directory. The Lambda JAR is generated within the target directory inside this directory. Every Lambda project inherits from the common Lambda parent project's directory serverless-cookbook-parent-aws-java and hence needs to be built before any Lambda project, following the steps outlined in the previous section.
The following are the in detail information about the role and functionality of Lambda plays and concepts that were introduced in this recipe.
Example projects in this book use the Maven parent project serverless-cookbook-parent-aws-java that defines the dependency versions for our examples. The actual dependencies are defined within each example project to help you understand the dependencies needed for each use case. All dependency definitions are shown within comments in the parent POM for quick reference.
Our parent project serverless-cookbook-parent-aws-java is also dependent on two open source projects: simple-starter-parent-java for the common Java dependencies, and simple-starter-build-tools for the common build file, such as the code style plugin definitions.
In this recipe, we selected the Create new role from template(s) and did not select any policy. The basic permissions required (logging to CloudWatch) are added by default. We can also choose an existing role or create a custom role.
AWS Lambda supports various runtimes, such as C# (.NET Core 1.0), C# (.NET Core 2.0), C# (.NET Core 2.1), Go 1.x, Java 8, Node.js 4.3, Node.js 6.10, Node.js 8.10, Python 2.7, and Python 3.6. Inline code editing is only allowed for Node.js and Python.
Our parent project,serverless-cookbook-parent-aws-java, defines a few more dependencies than I have. You can download them automatically through Maven (these projects are already available in Maven Central) or set these up manually in your local machine (to examine or modify) by executing the following commands from the command line.
Go inside the parent folder (
serverless
in my case) and clone
the
simple-starter-build-tools
project:
git clone https://github.com/heartin/simple-starter-build-tools.git
Go inside the project folder and run
mvn clean install
, as follows:
cd
simple-starter-build-tools
mvn clean install
Go back to the parent folder (
serverless
in my case) and clone the
simple-starter-parent-java
project:
git clone https://github.com/heartin/simple-starter-parent-java.git
Go inside the project folder and run
mvn clean install
:
cd
simple-starter-parent-java
m
vn clean install
The following are the in detail information about the other ways to create Lambda and to deploy its functions:
Apart from the Author from scratch option, we can create Lambdas using Blueprints and Serverless Application Repository. Blueprints allow you to choose a preconfigured template as a starting point. Currently, blueprints are available only for Node.js and Python. Serverless Application Repository allows you to find and deploy Serverless apps developed by developers, companies and partners on AWS.
In this recipe, we developed our code outside AWS and uploaded it to our AWS Lambda function as a JAR file. You can also upload the file to Amazon S3 by selecting Code entry type as Upload a file from Amazon S3, and providing the S3 link. For some languages such as Node.js and Python, you can also write the code inline within the Lambda function.
