Skip to content

Instantly share code, notes, and snippets.

@mickymots
Last active July 2, 2021 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mickymots/74bcc984567b41d66c61e4afb7a6c3b8 to your computer and use it in GitHub Desktop.
Save mickymots/74bcc984567b41d66c61e4afb7a6c3b8 to your computer and use it in GitHub Desktop.
CloudFormation Template to Create a Lambda Fn with SQS Trigger
AWSTemplateFormatVersion: 2010-09-09
Parameters:
SQSName:
Type: String
Default: 'ENTER SQS ARN '
Description: Enter SQS Queue ARN
Sender:
Type: String
Default: 'Enter Senders email'
Description: Sender email
Receiver:
Type: String
Default: 'Enter Receiver email'
Description: Receiver email address.
SlackToken:
Type: String
Default: some token here
Description: Slack Webhook Token
SlackWebhook:
Type: String
Default: >-
https://hooks.slack.com/<ADD_your_Address_here>
Description: Slack Webhook URL
ResultWebhook:
Type: String
Default: >-
https://hooks.slack.com/<ADD_your_Address_here>
Description: URL Result webhook
Resources:
LambdaRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Description: Lambda SES SQS Role
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AmazonSQSReadOnlyAccess'
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaSQSQueueExecutionRole'
MaxSessionDuration: 3600
Policies:
- PolicyName: ses_policy
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'ses:SendEmail'
- 'ses:SendRawEmail'
Resource: '*'
- PolicyName: lambda_cloudwatch_policy
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: 'logs:CreateLogGroup'
Resource: !Join
- ':'
- - 'arn:aws:logs'
- !Ref 'AWS::Region'
- !Ref 'AWS::AccountId'
- '*'
- Effect: Allow
Action:
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
Resource: !Join
- ':'
- - 'arn:aws:logs'
- !Ref 'AWS::Region'
- !Ref 'AWS::AccountId'
- 'log-group:/aws/lambda/SESLambdaFunction:*'
RoleName: LamnbdaSESSQSRole
SQSActionFunction:
Type: 'AWS::Lambda::Function'
Properties:
Role: !GetAtt
- LambdaRole
- Arn
Handler: index.lambda_handler
Code:
ZipFile: >
import urllib3
import boto3
import json
import logging
import os
from botocore.exceptions import ClientError
from base64 import b64decode
from urllib import request, error, parse
logger = logging.getLogger()
logger.setLevel(logging.INFO)
SENDER = os.environ['SENDER_EMAIL']
HOOK_URL = os.environ['SLACK_WEBHOOK_URL']
RECIPIENT = os.environ['RECEIVER_EMAIL']
AWS_REGION = "ca-central-1"
SUBJECT = "Amazon SES Test (SDK for Python)"
BODY_TEXT = "AWS SES MAIL"
BODY_HTML = """<html><head></head><body><p>event_id : {event_id}
event_description : {event_description}</p> <p>Event:
{event}</p></body></html> """
client = boto3.client('ses', region_name=AWS_REGION)
# Send Email Function
def send_email(payload):
logger.debug("send email invoked")
DATA = BODY_HTML.format(event_id=payload['event_id'], event_description=payload['event_description'], event=str(payload))
try:
response = client.send_email(
Destination={'ToAddresses': [RECIPIENT]},
Message={'Body': {'Html': {'Charset': "UTF-8",'Data':DATA}}, 'Subject': {'Charset': "UTF-8",'Data': SUBJECT, },},Source=SENDER,)
except ClientError as e:
logger.error(e.response['Error']['Message'])
else:
logger.info(f"Email sent! Message ID:{response['MessageId']}")
def send_slack(data):
logger.debug('send slack message')
slack_message = json.dumps({"text": str(data)}).encode("utf-8")
try:
http = urllib3.PoolManager()
response = http.request('POST', HOOK_URL, body=slack_message, headers={"Content-Type": "application/json"})
logger.info(response.data)
except error.HTTPError as e:
logger.error("Request failed: %d %s", e.code, e.reason)
except error.URLError as e:
logger.error("Server connection failed: %s", e.reason)
def process_record(data):
logger.debug('process records ---')
logger.debug(str(data))
if 'slack' in data['communication_channel']:
try:
send_slack(data)
except Exception as e:
logger.error('send slack message failed')
elif 'email' in data['communication_channel']:
try:
send_email(data)
except Exception as e:
logger.error('send email message failed')
logger.exception(e)
else:
logger.error('Invalid Communication channel specifiec')
def lambda_handler(event, context):
logger.debug(str(event))
for record in event['Records']:
logger.debug("---- Record ----")
payload = record["body"]
data = json.loads(payload)
process_record(data)
Environment:
Variables:
RECEIVER_EMAIL: !Ref Receiver
SENDER_EMAIL: !Ref Sender
SLACK_WEBHOOK_TOKEN: !Ref SlackToken
SLACK_WEBHOOK_URL: !Ref SlackWebhook
URL_RESULT_WEBHOOK: !Ref ResultWebhook
Runtime: python3.8
SQSLambdaMapper:
Type: 'AWS::Lambda::EventSourceMapping'
Properties:
BatchSize: 10
Enabled: true
EventSourceArn: !Ref SQSName
FunctionName: !GetAtt
- SQSActionFunction
- Arn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment