Skip to content

Instantly share code, notes, and snippets.

@piyoki
Last active February 11, 2023 13:48
Show Gist options
  • Save piyoki/88baf7b3c75380382ff3d530c64ac4cd to your computer and use it in GitHub Desktop.
Save piyoki/88baf7b3c75380382ff3d530c64ac4cd to your computer and use it in GitHub Desktop.
AWS Lambda + Serverless Framework Demo
ARG FUNCTION_DIR="/function"
### Production Stage ###
FROM python:slim-bullseye as staging-image
# Include global args in this stage of the build
ARG FUNCTION_DIR
# Set working directory to function root
WORKDIR ${FUNCTION_DIR}
# Copy dependency definition
COPY ./requirements.txt .
# Install dependencies
RUN pip3 install -r requirements.txt
RUN pip3 install awslambdaric
# Set up default environment variables
ENV ENV=staging
# Copy source code
COPY app/ .
ENTRYPOINT ["python3", "-m", "awslambdaric"]
CMD ["handler.lambda_handler"]
# serverless.yml
---
service: sample-api-function
custom:
sharedBucketName: <custom bucket name> # the bucket resource has to be already present in the account
githubAppSecretArn: arn:aws:secretmanager:eu-west-2:<aws account id>:secret:<secret id e.g. my-secret-4hBip>
provider:
name: aws
stage: ${opt:stage, "staging"} # default: staging
architecture: x86_64
apiGateway:
metrics: true
region: <aws region>
memorySize: 1024
timeout: 100
profile: saml
deploymentBucket:
name: ${self:custom.sharedBucketName}
ecr:
scanOnPush: true
images:
latest: # image tag to be built
path: / # path of docker context
file: ci/${opt:stage, "staging"} # dockerfile location
iam: # optional iam field
role:
statements:
# IAM role to allow lambda to retrive secret from SecretManager
- Effect: Allow
Action:
- secretmanager:GetSecretValue
Resource: ${self:custom.githubAppSecretArn}
vpc:
# assign vpc subnets and securityGroups
securityGroupIds:
- sg-<sg id>
subnetIds: # vpc subnet ids
- subnet-<subnet id>
environment:
# in-app environment variables
AWS_GITHUB_APP_SECRET_ARN: ${self:custom.githubAppSecretArn}
# define lambda fucntion
functions:
app:
description: A sample serverless application that can perform api-like operations
image:
name: latest
command:
- handler.lambda_handler # wsgi is the python file name, lambda_handler is the function within that python scrip as entrypoint
events:
- http: ANY /api/v1/health # assume you have a health api endpoint
- http: ANY /api/v1/stats # assume you have a stats api endpoint
timer:
description: A sample serverless application that can perform api-like operations (Cron)
image:
name: latest # reference the image tag from above
command:
- timer.lambda_handler # timer is the python file name, lambda_handler is the function within that python scrip as entrypoint
events:
- eventBridge:
schedule: rate(60 minutes)
import json
import time
import logging
class Logger:
def __new__(cls, *args, **kwargs):
cls._logger = super().__new__(cls)
logging.root.serLevel(logging.NOTSET)
handler = logging.StreamHandler()
handler.setLevel(logging.NOTSET)
handler.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s: %(message)s")
)
cls._logger.addHandler(handler)
return cls._logger
def lambda_handler(event, context):
"""Lambda entry for AWS EventBridge use case"""
try:
logger = Logger()
logger.info("Received event from AWS EventBridge!")
logger.info("Proceeding request...")
# YOUR BUSINESS LOGIC GOES HERE
start_count = time.per_counter()
logger.info("hello world!")
result = ""
logger.info(f"Duration - {time.perf_couter() - start_count} seconds.")
logger.info(f"Done.")
# BUSINESS LOGIC ENDS
return = {
"statusCode": 200,
"body": json.dumps({"result": "ok", "result": result})
}
except Exception as e:
logger.error(e)
return {
"statusCode": 500,
"body": json.dumps({"error": "Ops, something goes wrong."})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment