AWS-serverless-starter - AWS Lambda serverless stack via Serverless framework

Overview

Serverless app via AWS Lambda, ApiGateway and Serverless framework

Configuration of AWS CLI and IAM user credentials

Hi there. Within this tutorial we'll try to write a simple serverless application using AWS Lambda functions, ApiGateway for triggering the functions and Serverless framework for IaC. Before starting it is worth to note that you will need to have an AWS account for this tutorial. Also, you need to install AWS CLI for working with the AWS environment from your console.

First thing to do is creating a new AWS IAM user. This will make is possible for Programmatic access to the resources in your cloud environment. Creating an IAM user is out of the scope of this tutorial but you can refer to this official guide for this. It is important not to forget to download your newly created IAM user credentials which are the Access and Secret keys.

Neither share them with 3rd party nor push to any remote repository.

After getting the credentials let's configure our local machine for interacting with the AWS environment easily. Firstly we need to install AWS CLI tool. Note that the steps below is a guide for installing CLI tool for MacOS X. For other platforms, check the official doc for installation.

  1. Firstly, install the remote package to your system via
curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
  1. Then, install the downloaded package via
sudo installer -pkg ./AWSCLIV2.pkg -target /

After installation you can verify that by using the aws --version command. Output should be like below

drawing

And the final step of configuration is creating new AWS profile for that. AWS profile or more specifically named profile is an easy way of managing credentials for AWS Command Line Interface.

A named profile is a collection of settings and credentials that you can apply to a AWS CLI command. When you specify a profile to run a command, the settings and credentials are used to run that command. Multiple named profiles can be stored in the config and credentials files.

by AWS

For creating a new profile locally use the command below.

aws configure --profile <profile_name>

It will prompt AWS Access and Secret keys and will save them as a named profile in ~/.aws/credentials file. Here you need to use previously downloaded AWS IAM credentials when creating the user in the previous section

Creating a new serverless application via Serverless framework

Before starting with the very basic application which will be deployed to AWS Lambda functions we need to talk about what Serverless framework is and how to install and use it. Let's look at what others say about it.

Serverless Framework is an open source tool available for building, packaging and deploying serverless applications across multiple cloud providers and platforms like AWS, GCP, Azure, Kubernetes, etc.

from Anuj Kumar

By using simple configuration template Serverless framework makes is extremely easy to create resources on AWS environment and deploy your code there. Enough talking, let's download and create the very first serverless application!

As the Serverless framework is written is JavaScript, you need to have Node.js runtime environment installed. You can check the official website for installing Node.js. It is always safe to use LTS which stands for Long term support version. After installing Node, use the command below to install the Serverless framework

npm install -g serverless

As we are using the -g flag here it means we are installing the package globally. In this case it throws permission error. No worries, simply use the sudo'ed version of the command and insert your root user password. It should be successful this time.

sudo npm install -g serverless

Great!

Next step is creating the very basic project skeleton for our serverless application. Creating an app from scratch is extremely easy. Simply run the command below and use arrow keys to navigate between options.

serverless

Choose the basic Python HTTP option, press enter.

AWS console

It is important to note that Serverless framework is not limited with these options. You can choose many other programming languages and environments. Python and Node.js are simply well-known and mostly used ones.

Next it will ask a name for the project (or simply press enter and proceed with the default name). And the last question asks to which organization this app belongs to. We don't need to specify anything here, so simply choose the skip option and press enter. That's it. Our Python application should be created in the corresponding directory. Now let's look at the files of the app and explore the serverless.yml file which is template file for deployment.

In the directory we'll see 4 files: .gitignore, handler.py, README.md and serverless.yml. As you would imagine most important ones are handler.py and serverless.yml files there.

Firstly, let's explore serverless.yml file. It is simple a template file which will be converted to AWS Cloudformation and used as IaC definition for creating the resourced during the deployment. Please, use Google for getting more info on AWS CloudFormation :)

Let's go top to bottom and explain each line here:

drawing

The first 2 lines are generic ones and give information about the created service name and serverless framework version respectively.

The next block defines the generic properties of the Cloud vendor. In this case it is AWS (could be GCP or Azure too). The property runtime indicates which Python version will be used in our serverless stack. Although AWS lambda function fully supports Python version 3.9, default version of Python in Serverless framework is 3.8. We can simply use 3.9 instead without any issue.

And the last block defines the functions. It can be seen that as we have newly created project, we have only a function named hello. Path defines the path in which our corresponding function will receive an event and be invoked. And method shows the HTTP method which is expected by our API Gateway.

Next, let's explore the very first Python file which will be invoked after deploy to the AWS environment.

drawing

We can see that is it very basic Python function which receives 2 parameter and returns a response. One of the received parameter is called event and will play the role of request object if you are familiar with web development. But, I'll not dive into them and they are out of context here.

Let's deploy this function and invoke it via publicly available URL provided by AWS using AWS API Gateway. Deploying the application via Serverless framework is as easy as running a command with multiple optional parameters

serverless deploy --verbose --config serverless.yaml --aws-profile <your_aws_profile>

Here we see some parameters and they needs to be explained. First parameter is the --verbose or -v flag which tells Serverless framework CLI to show us the each process as a step clearly. --config is used to tell which config file or template should be used as input. It is worth to mention that if you have only one template file (like we have currently :)), using this parameter would not make sense and could be ignored. But if you have complex setup and multiple environments such as serverless.stage.yml, serverless.prod.yml and serverless.dev.yml, using --config and specifiying the input file explicitly makes absolute sense.

And the last parameter is --aws-profile which specifys the locally created AWS CLI user and Serverless framework in this case will grab and use those saved credentials from your local .aws directory. It removes the hassle of dealing with multiple IAM user credentials.

Finally, let's input the command and press enter.

As we are using the verbose parameter, we can see the detail of each step during the deployment. It is worth to note here that although we have defined only Lambda functions in the IaC template, AWS will create many other resources and update some automatically which are important such as AWS ApiGateway, Aws Logs etc.

Example output from deployment:

drawing

After the initial deployment steps, a newly directory with the name .serverless will be created where your application files reside. As we have mentioned earlier Serverless framework uses AWS Cloudformation behind the scene to create resources. And the template files for Cloudformation will be saved under this directory.

Let's open Postman to invoke our function. You can use any client to for that, even browser. But I prefer Postman here. And the result of our deployed Python function is

drawing

Let's change the response to something simpler, re-deplpoy and invoke function again.

Copy the code below and put it in handler.py file.

import json
from datetime import datetime

def hello(event, context):
    body = {
        "message": "Hello world",
        "author": "Bakhtiyar Garashov",
        "invoked_at": str(datetime.now())
    }

    response = {"statusCode": 200, "body": json.dumps(body)}

    return response

Let's copy the url and use browser this time for triggering the function

drawing

And as a final step, if you don't want to get a huge bill after some time (:D), run the command below to destroy all the created resourced

serverless remove --verbose --config serverless.yml --aws-profile <profile>

If you are having issue with using AWS it is always possible to invoke the Serverless functions locally. For example,

serverless invoke local --function hello 

Here we are saying to the Serverless framework that invoke the function with the name 'hello' locally. And:

drawing

That's it. Next time we'll see how to write serverless CRUD application which uses AWS DynamoDb (NoSQL database managed by AWS) as the storage.

Stay tuned...

Owner
Bəxtiyar
MSc student @UniTartu
Bəxtiyar
Project for the discipline of Visual Data Analysis at EMAp FGV.

Analysis of the dissemination of fake news about COVID-19 on Twitter This project was the final work for the discipline of Visual Data Analysis of the

Giovani Valdrighi 2 Jan 17, 2022
pymobiledevice fork with more recent coding standards and many more features

Description Features Installation Usage Sending your own messages Lockdown messages Instruments messages Example Lockdown services com.apple.instrumen

255 Dec 28, 2022
python3.5+ hubspot client based on hapipy, but modified to use the newer endpoints and non-legacy python

A python wrapper around HubSpot's APIs, for python 3.5+. Built initially around hapipy, but heavily modified. Check out the documentation here! (thank

Jacobi Petrucciani 140 Dec 21, 2022
Library written in Python that wraps Halo Infinite API.

haloinfinite Library written in Python that wraps Halo Infinite API. Before start It's unofficial, reverse-engineered, neither stable nor production r

Miguel Ferrer 4 Dec 28, 2022
Represents a Lavalink client used to manage nodes and connections.

lavaplayer Represents a Lavalink client used to manage nodes and connections. setup pip install lavaplayer setup lavalink you need to java 11* LTS or

HazemMeqdad 37 Nov 21, 2022
A feishu bot daily push arxiv latest articles.

arxiv-feishu-bot We develop A simple feishu bot script daily pushes arxiv latest articles. His effect is as follows: Of course, you can also use other

huchi 6 Apr 06, 2022
Low-level, feature rich and easy to use discord python wrapper

PWRCord Low-level, feature rich and easy to use discord python wrapper Important Note: At this point, this library API is considered unstable and can

MIguel Lopes 1 Dec 26, 2021
Nft-maker - Create your own NFT!

nft-maker How to If you're going to use this program, change the pictures in the "images" folder. All images must be of the same resolution and size.

Georgii Arakelian 4 Mar 13, 2022
Python Capfire API wrapper

General CampfireAPI based on Campfire web. Install pip install Campfire-API Quickstart Use it without login: from campfire_api import CampfireAPI cf

Ghost 0 Jan 03, 2022
:globe_with_meridians: A Python wrapper for the Geocodio geolocation service API

Py-Geocodio Python wrapper for Geocodio geocoding API. Full documentation on Read the Docs. If you are upgrading from a version prior to 0.2.0 please

Ben Lopatin 84 Aug 02, 2022
Plataforma para atendimento a outras empresas que necessitam de atendimento técnico.

Plataforma para atendimento a outras empresas que necessitam de atendimento técnico. É possível que os usuarios de empresas parceiras registrem solici

Kelvin Alisson Cantarino 2 Jun 29, 2022
Schedule Twitter updates with easy

coo: schedule Twitter updates with easy Coo is an easy to use Python library for scheduling Twitter updates. To use it, you need to first apply for a

wilfredinni 46 Nov 03, 2022
Yes, it's true :revolving_hearts: This repository has 301 stars.

Yes, it's true! Inspired by a similar repository from @RealPeha, but implemented using a webhook on AWS Lambda and API Gateway, so it's serv

511 Dec 30, 2022
An automated bot for twitter using Tweepy!

Tweeby An automated bot for twitter using Tweepy! About This bot will look for tweets that contain certain hashtags, if found. It'll send them a messa

Ori 1 Dec 06, 2021
Implement backup and recovery with AWS Backup across your AWS Organizations using a CI/CD pipeline (AWS CodePipeline).

Backup and Recovery with AWS Backup This repository provides you with a management and deployment solution for implementing Backup and Recovery with A

AWS Samples 8 Nov 22, 2022
A telegram bot to monitor the latest NFT price on BSC.

NFT_Monitor This is a telegram bot for monitoring price and ranking of NFT on Binance Smart Chain. Can fetch latest ranking and price in real time. .P

Niko Pang 10 Oct 09, 2022
A tool to build scripts to toggle between minimal & default services in Windows based on user defined lists.

A tool to build scripts to toggle between minimal & default services in Windows based on user defined lists.

AMIT 29 Jan 01, 2023
Botto - A discord bot written in python that uses the hikari and lightbulb modules to make this bot

❓ About Botto Hi! This is botto, a discord bot written in python that uses the h

3 Sep 13, 2022
OGE-2022-na-Python - Solving problems in python for the OGE 2022

OGE-2022-na-Python Решение задачек на питоне для ОГЭ 2022 Тут разобраны разные в

Slava 0 Oct 14, 2022
Twitch Points Miner for multiple accounts with Discord logging

Twitch Points Miner for multiple accounts with Discord logging Creator of the Twitch Miner -- PLEASE NOTE THIS IS PROBABLY BANNABLE -- Made on python

8 Apr 27, 2022