Deploy flask app to lambda using github-actions and serverless

Nitesh Rijal
2 min readDec 29, 2022

--

Hey, folks. In this blog we are going to learn about how to deploy a simple flask app to lambda using serverless and github actions.

For more about serverless click here.

We are going to use wsgi for this project also without further a do let’s begin

Keep in mind that you need to have python 3.8 for this deployment.

Install the required packages

pip install flask
npm i -g serverless

At first create a folder for me I will create a simple-flask-app

inside it make a python file called app.py

from flask import Flask, request, render_template
app= Flask(__name__)
@app.route('/')
def main():
return render_template("index.html")
if __name__=='__main__':
app.run()

Now create directory called templates and make a file called index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
Yoooooo!!! <h1is>This is from flask </h1>
</body>
</html>

Your directory structure should look like this

    app.py
└── templates
└── index.html

Now create a action script to deploy on the server to do that create a folder called .github make another folder called workflows and create a file called deploy.yml inside it.

Your directory structure should look like this

├── .github
│ └── workflows
│ └── deploy.yml

inside deploy.yml file

name: Deploy the code
on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v3
with:
python-version: "3.8"
- uses: aws-actions/setup-sam@v2
- uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{secrets.AWS_ACCESS_KEY_ID}}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: us-west-2
- name: Install Serverless Framework
run: npm i -g serverless
- name: Install plugins
run: serverless plugin install -n serverless-python-requirements
- name: Install serverless wsgi
run: serverless plugin install -n serverless-wsgi
- name: serverless package
run: serverless package
- name: Deploy to Lambda
run: serverless deploy

Now create a serverless.yml in the root directory file which contains

service: simple-flask-app

plugins:
- serverless-python-requirements
- serverless-wsgi

custom:
wsgi:
app: app.app
packRequirements: false
pythonRequirements:
dockerizePip: true

package:
exclude:
- node_modules/**
- venv/**

provider:
name: aws
runtime: python3.8
stage: prod
region: us-west-2

functions:
app:
handler: wsgi.handler
events:
- http: ANY /
- http: 'ANY {proxy+}'

the full folder structure should look like this

now push the changes add aws secrets in the github settings or you can use github cli now you are ready to go.

--

--

No responses yet