By using Amazon API Gateway, it’s possible to quickly create serverless microservices backed by Lambda. We’ll review one such deployment and use the AWS Serverless Application Model (SAM) to deploy it.

Introduction

With ever-growing cloud systems, many companies have opted to move away from monoliths into a distributed architecture composed of microservices. AWS allows the development of such services without the need to manage the underlying server infrastructure.

We’ll go over an infrastructure-as-code (IaC) approach to deploying one such service using SAM. The deployment will assume that a virtual private cluster (VPC) is already in place and that only VMs on specific subnets within the cluster should be able to access the private service. We’ll also assume that the developer already has the necessary AWS SAM tools installed locally.

1. Files and Folders

my-microservice/
├── cmd/
│   ├── debug.sh
│   └── deploy.sh
├── src/
│   ├── index.js
│   └── package.js
├── .gitignore 
├── test-event.json
└── template.yaml

The cmd folder will contain our helper scripts for the deploying and local debugging of our function, as shown below:

debug.sh: Runs the function on the local computer using test-event.json as input.

#!/bin/bash

script_path=$(cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P)
sam local invoke \  
  --event ${script_path}/../test-event.json \  
  --template-file ${script_path}/../template.yaml

deploy.sh: Deploys the service to AWS.

#!/bin/bash

## exit when any command fails
set -e
script_path=$(cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P)
sam deploy \  
  --template-file ${script_path}/../template.yaml \  
  --stack-name my-microservice \  
  --capabilities CAPABILITY_IAM \  
  --guided

The src folder will contain Lambda’s source code. In this case, it consists of Node index.js and package.json files. However, the same technique that will be shown here would work with any of the other supported Lambda languages as well.

package.json

{  
  "name": "my-lambda-code",  
  "version": "1.0.0",  
  "description": "AWS Lambda function for microservice",  
  "main": "index.js",  
  "scripts": {    
    "test": "echo \"Error: no test specified\" && exit 1"  
  },  
  "author": "",  
  "license": "ISC",  
  "dependencies": {},  
  "devDependencies": {}
}

#api #programming #aws #serverless #aws-lambda

Private Serverless REST APIs With AWS Lambda Using SAM
1.85 GEEK