/aws-lambda-python-template

AWS Lambda + Python Template for local development by using python-lambda-local and lambda-uploader

Primary LanguagePython

Lambda + Python Template

Preparation

Create IAM role

Create IAM role attached below policies and copy Arn

  • AWSLambdaExecute
  • AmazonS3ReadOnlyAccess

Required

You need below on local machine

  • aws-cli >= 1.18.X
  • Python >= 3.8

Upload Check Target Domains File to S3

  • Edit json file data/sample_config.json
  • Upload to S3 Bucket

Setup

Setup for Lambda

Set Lambda config files

cp functions/lambda.json.sample functions/lambda.json

Edit functions/lambda.json for your env

{
  ...

  "region": "ap-northeast-1",
  "role": "arn:aws:iam::************:role/iam-role-lambda-development",
  "variables": {
    "CONFIG_S3_BUCKET_NAME": "your-config-bucket-name",
    "CONFIG_S3_OBJECT_PATH": "your-config-bucket-file-path.json"
  }
}

Local development

Setup

Set config files

cp env.sh.sample env.sh

Edit env.sh for your local env

#!/bin/bash

export AWS_PROFILE="yuor-aws-profile-name"
export AWS_DEFAULT_REGION="ap-northeast-1"
...

Apply enviroment variables

# At project root dir
source env.sh

Setup venv

 python3 -m venv .
. bin/activate

Install pip packages

pip install -r requirements.txt
pip install -r functions/requirements.txt -t functions_lib

Execute on local

Execute lambda function on local

cd functions
python-lambda-local -t 30 -l ../functions_lib -f lambda_handler lambda_function.py event.json

Options

  • -t : timeout (seconds)
  • -l : libraries dir

Upload to Lambda

cd functions
lambda-uploader -r requirements.txt

Trigger setting on Lambda Console

Add trigger on Lambda console