Getting Started with Serverless and AWS
Tags: aws, serverless
Published: 2022-05-01 17:07:26

This is my first ever blog. I hope you find it valuable.

![Project 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yopsfhch5wa1m0diwixw.jpg)

## Setting up the Workstation 

- Install **Node.js** - [Download Node.js](https://nodejs.org/en/download/) in my case - Windows Installer .msi 64-bit on workstation 
- Install Serverless [Download Serverless Getting Started](https://www.serverless.com/framework/docs/getting-started) on workstation - `npm install -g serverless`
- Root user or root equivalent user access in AWS


---

## Create an IAM Role - AWS Service
Access key will enable serverless to connect with AWS 

- Go to **IAM -> Create users -> Add a user name: jayp1_serverless -> Select AWS access type -> Select AWS credential type -> Access key - Programmatic access** 

<u>Description</u>: > Access Key - Programmatic Access - Enables an access key ID and secret access key for the AWS API, CLI, SDK, and other development tools.
- Setup serverless configuration to connect with AWS `serverless config credentials --provider aws --key <access-key> --secret <secret-key>` 
 
- Create a directory: `mkdir aws_2022 && cd aws_2022` and initialize Serverless project `serverless`
* Choose **AWS-Python-Starter**
* Name it default 
* Deploy - Yes 

```bash
C:\Users\jp\Documents\aws_2022>serverless

Creating a new serverless project

? What do you want to make? AWS - Python - Starter
? What do you want to call this project? aws-python-project

✔ Project successfully created in aws-python-project folder

? Do you want to login/register to Serverless Dashboard? No

? Do you want to deploy now? (Y/n) y
? Do you want to deploy now? Yes

Deploying aws-python-project to stage dev (us-east-1)

× Stack aws-python-project-dev failed to deploy (78s)
Environment: win32, node 16.14.2, framework 3.12.0, plugin 6.2.1, SDK 4.3.2
Docs:        docs.serverless.com
Support:     forum.serverless.com
Bugs:        github.com/serverless/serverless/issues

Error:
CREATE_FAILED: IamRoleLambdaExecution (AWS::IAM::Role)
API: iam:GetRole User: arn:aws:iam::673040272970:user/jayp1_serverless is not authorized to perform: iam:GetRole on resource: role aws-python-project-dev-us-east-1-lambdaRole because no identity-based policy allows the iam:GetRole action

View the full error: https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stack/detail?stackId=arn%3Aaws%3Acloudformation%3Aus-east-1%3A673040272970%3Astack%2Faws-python-project-dev%2F6669ede0-c3c3-11ec-9584-0a8914e80a47
```

- Note the IamRole error , to fix is to update the role permissions by giving the **access key user - jayp1_serverless**. 
- Go to **IAM -> Users -> jayp1_serverless -> Add Permissions -> Choose Attach existing policy directly**

![IamRole Policy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pz08vp0xwe2htnzg755c.png)

```bash
Creating a new serverless project

? What do you want to make? AWS - Python - Starter
? What do you want to call this project? aws-python-project-2022

✔ Project successfully created in aws-python-project-2022 folder

? Do you want to login/register to Serverless Dashboard? No

? Do you want to deploy now? (Y/n) Y
? Do you want to deploy now? Yes

Deploying aws-python-project-2022 to stage dev (us-east-1)

✔ Service deployed to stack aws-python-project-2022-dev (111s)

functions:
  hello: aws-python-project-2022-dev-hello (1.7 kB)

What next?
Run these commands in the project directory:

serverless deploy    Deploy changes
serverless info      View deployed endpoints and resources
serverless invoke    Invoke deployed functions
serverless --help    Discover more commands
```

- Go to **Lambda -> Functions -> aws-python-project-2022-dev-hello (filename-stage-function)** - try to check in default region - **N.Virginia** 
 
![Lambda Python Hello](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/77y0fcpc9b6nxxfppxtj.png)

 ![Inside lambda hello](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4prvgnhxrycu80fdt86.png)
 
- Invoke lambda function on local workstation `serverless invoke --function hello`

```bash
C:\Users\jp\Documents\aws_2022>cd aws-python-project-2022

C:\Users\jp\Documents\aws_2022\aws-python-project-2022>serverless invoke --function hello
{
    "statusCode": 200,
    "body": "{\"message\": \"Go Serverless v3.0! Your function executed successfully!\", \"input\": {}}"
}
```

- Digging deep into folder stack of serverless project 
![folder stack](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/my1pb0joybyhut14o16d.png)

- There are two concerned files for developer - **handler.py** and **serverless.yml**  

 * **handler.py** contains a function hello which returns a json message.
```python
import json


def hello(event, context):
    body = {
        "message": "Go Serverless v3.0! Your function executed successfully!",
        "input": event,
    }

    return {"statusCode": 200, "body": json.dumps(body)}
```

 * **serverless.yml** is generated or created automatically while we create a serverless project. To understand serverless YML keywords [Serverless Framework - AWS Lambda Guide](https://www.serverless.com/framework/docs/providers/aws/guide/intro)

```yaml
service: aws-python-project-2022

frameworkVersion: '3'

provider:
  name: aws
  runtime: python3.8

functions:
  hello:
    handler: handler.hello
 
```

 * service - project configuration file 
 * provider : which cloud provider in our case its AWS 
    * name : aws 
    * runtime : python3.8
![Serverless Provider](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/atcw5s689a6eka4sbxq4.png)

 
---

## Deploying a new lambda function in desired region

Create a new lambda function **getting_started** in new  handler file **application.py** which will be deployed in Mumbai `region: ap-south-1`

- Create a function - getting started in **application.py**

 ```python
import json


def getting_started(event, context):
    body = {
        "message": "Go Serverless v3.0! Getting Started with Serverless \
             execution!",
        "event": event,
    }

    return {"statusCode": 200, "body": json.dumps(body)}
```

- Modify **serverless.yml** 

```yaml
service: aws-python-project-2022

frameworkVersion: '3'

provider:
  name: aws
  runtime: python3.8
  region: ap-south-1

functions:
  hello:
    handler: handler.hello
  getting_started:
    handler: application.getting_started
```

- Deploy changes on AWS `serverless deploy` 

![Lambda Functions Mumbai](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oip1b6wqsglkr48p1syk.png)

* Invoke getting_started on workstation `serverless invoke --function getting_started` 
```bash
C:\Users\jp\Documents\aws_2022\aws-python-project-2022>serverless invoke --function getting_started
{
    "statusCode": 200,
    "body": "{\"message\": \"Go Serverless v3.0! Getting Started with Serverless              execution!\", \"event\": {}}"
}
```

---

## API Gateway and AWS Lambda through Serverless Framework

- *Event - Http - GET** Method will invoke `getting_started` function

- Setting up the APIs in API Gateway events under function and listing one such event `-http` with `path: /data` and `method: GET`

```yaml
functions:
  hello:
    handler: handler.hello
  getting_started:
    handler: application.getting_started
    events:
      - http:
          path: /data
          method: GET
```
- Deploy the changes on AWS `serverless deploy` notice the **endpoint**

```bash

C:\Users\jp\Documents\aws_2022\aws-python-project-2022>serverless deploy

Deploying aws-python-project-2022 to stage dev (ap-south-1)

✔ Service deployed to stack aws-python-project-2022-dev (48s)

endpoint: GET - https://ni5xsk9f08.execute-api.ap-south-1.amazonaws.com/dev/data
functions:
  hello: aws-python-project-2022-dev-hello (2 kB)
  getting_started: aws-python-project-2022-dev-getting_started (2 kB)

Improve API performance – monitor it with the Serverless Dashboard: run "serverless"
```

- Checking the endpoint: https://ni5xsk9f08.execute-api.ap-south-1.amazonaws.com/dev/data

![GET dev data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r6osme37ssz0p8nz36sn.png)
 
- Go to **API Gateway -> Select Mumbai region -> APIs** 

![API Gateway GET Method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ejz5320vo0y0vwsjmdx.png)
 
- Check the invocation counts, error logs etc. in **Monitor** in Lambda console. 
![Metric Logs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ol6mkkqsjwskdlp16gh8.png)