Skip to content

Instantly share code, notes, and snippets.

@devgrok
Last active March 21, 2019 17:09
Show Gist options
  • Save devgrok/8d543caac621c377948efd162f8ca789 to your computer and use it in GitHub Desktop.
Save devgrok/8d543caac621c377948efd162f8ca789 to your computer and use it in GitHub Desktop.
Create a Private Microservice Using an Application Load Balancer
import json
import logging
import os
from lambdarest import lambda_handler
from slackclient import SlackClient
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# ideally this should be replaced with a call to: secretsmanager.get_secret_value(SecretId=secret_name)
sc = SlackClient(os.environ['SLACK_TOKEN'])
def generic_handler(event, room_id_or_name):
msg = event['body']
hipchat_body = json.loads(msg)
msg_text = hipchat_body['message']
try:
resp = sc.api_call("chat.postMessage", channel="test_room", text=msg_text)
if resp['ok']:
logger.info("Success calling slack")
return {"statusCode": 204, "body": ""}
else:
logger.error("Slack response %s", resp)
return {"statusCode": 500, "body": "Slack response: " + resp}
except Exception as err:
logger.error("Caught error calling slack", err)
return {"statusCode": 500, "body": "" + err}
@lambda_handler.handle("post", path="/v2/<room_id_or_name>/notification")
def room_notification(event, room_id_or_name):
return generic_handler(event, room_id_or_name)
# aws lambda needs to reference code in your project to behave, so redefine reference to handler
the_handler = lambda_handler
# this file contains runtime dependencies (setup.py can used to create development/test dependencies)
requests
slackclient
python-lambdarest>=5.4.0
#!/bin/bash -xe
BASEDIR=$(cd "$(dirname "$0")/.."; pwd)
echo "project directory $BASEDIR"
: ${TARGET_DIR:=${BASEDIR}/tmp}
rm -rf ${TARGET_DIR}
mkdir -p ${TARGET_DIR}
# arg 1 - space separated paths to check
# arg 2 - friendly name for error messages
function findFile() {
for x in $1; do
if [[ -f ${x} ]]; then
echo ${x}
return
fi
done
>&2 echo "Could not find $2 to use"
exit 1
}
# modify this accordingly depending on the name and whether python3.6 (or python3.7 if that's your runtime) is on the path
# here i pull in python 3.6 installed from centos-release-scl-rh
PYTHON=$(findFile "$(which python3.6) /opt/rh/rh-python36/root/usr/bin/python $(which python3)" "python3.6")
PIP=$(findFile "$(which pip3.6) /opt/rh/rh-python36/root/usr/bin/pip3.6 $(which pip3)" "pip3.6")
# newer python doesn't use the virtualenv script, instead uses "python -m venv"
VIRTUALENV="$PYTHON -m venv"
# barfs if aws-sam-cli is installed in venv due to dependencies, so install at user level first
${PIP} install --user aws-sam-cli
export PATH=$(${PYTHON} -m site --user-base)/bin:$PATH
echo "Activating virtualenv"
${VIRTUALENV} venv
if [[ -f venv/bin/activate ]]; then
source venv/bin/activate
else
source venv/Scripts/activate
fi
# update pip and wheel
pip install -U pip wheel
####################################################
# TODO TESTS
# create a setup.py with test dependencies then use:
####################################################
#pip install .[tests]
#py.test
pwd
mkdir -p .aws-sam/build
sam build --debug
if [[ -z "${BUCKET}" ]] || [[ -z "${PREFIX}" ]]; then
>&2 echo "Skipping package and upload step as BUCKET or PREFIX is not set"
exit 1
fi
cd .aws-sam/build
aws cloudformation package \
--template-file template.yaml \
--output-template-file ${TARGET_DIR}/serverless-output.yaml \
--s3-bucket ${BUCKET} \
--s3-prefix ${PREFIX}
echo "to deploy run: (replacing YOUR_SLACK_TOKEN with your token)"
echo "aws cloudformation deploy \
--template-file ${TARGET_DIR}/serverless-output.yaml \
--stack-name hipchat-proxy \
--parameter-overrides \
SlackToken=YOUR_SLACK_TOKEN \
EnvName=${ENV_NAME}"
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
SlackToken:
Type: String
Description: "the token used to call slack"
Resources:
HipchatFunction:
Type: AWS::Serverless::Function
Properties:
Handler: hipchat_proxy.the_handler
Runtime: python3.6
CodeUri: ./
Description: "A simple hipchat to slack convertor"
Timeout: 5
Environment:
Variables:
SLACK_TOKEN: !Ref SlackToken
@sloev
Copy link

sloev commented Mar 6, 2019

https://github.com/trustpilot/python-lambdarest
has been updated to support Application Load Balancer:

from lambdarest import create_lambda_handler

lambda_handler = create_lambda_handler(application_load_balancer=True)

@lambda_handler.handle("get", path="/foo//")
def my_own_get(event, id):
return {"my-id": id}

pip install lambdarest>=5.4.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment