I am working on a CDK application that utilizes a Lambda function to monitor changes in the content of a website. My goal is to trigger an SMS notification to a mobile number whenever a change is detected.
Within my AWS CDK project, I have set up a stack that includes the creation of the Lambda function and SNS.
File: lib/lambda_query_website_aws_cdk-stack.ts
import * as cdk from '@aws-cdk/core';
import events = require('@aws-cdk/aws-events');
import targets = require('@aws-cdk/aws-events-targets');
import lambda = require('@aws-cdk/aws-lambda');
import * as sns from '@aws-cdk/aws-sns';
import * as subscriptions from '@aws-cdk/aws-sns-subscriptions';
import fs = require('fs')
export class LambdaQueryWebsiteAwsCdkStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const lambdaFn = new lambda.Function(this, 'Singleton', {
code: new lambda.InlineCode(fs.readFileSync('lambda-handler.py', { encoding: 'utf-8' })),
handler: 'index.main',
timeout: cdk.Duration.seconds(300),
runtime: lambda.Runtime.PYTHON_3_6,
environment: {
'PREV_RESPONSE': ''
}
});
// Runs every 30 minutes from 6:00 to 23:00
// See https://docs.aws.amazon.com/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html
const rule = new events.Rule(this, 'Rule', {
schedule: events.Schedule.expression('cron(0/30 6-23 * * ? *)')
});
rule.addTarget(new targets.LambdaFunction(lambdaFn));
// Create an SNS Topic.
// The producer or publisher is the lambda function ??
//The subscriber or consumer is the sms phone number +15551231234
const myTopic = new sns.Topic(this, 'MyTopic');
myTopic.addSubscription(new subscriptions.SmsSubscription('+15551231234'));
}
}
Below is the code for the lambda function:
File: lambda-handler.py
import os
import urllib.request
url= "https://mywebsite.com"
def main(event, context):
print("I'm running!")
response = urllib.request.urlopen(url)
response_text = response.read()
html = response_text.decode('utf-8')
if os.getenv('PREV_RESPONSE',default="HTML_BODY") != html:
print("There was a change on the web site")
os.environ['PREV_RESPONSE'] = HTML
# TODO:
# Send the SMS notifying about the change
My question is, how can I inform the SNS service to send out the message when needed?
Best regards,