Check website with AWS Lambda using Python 2.7
Create SNS topic
- Go to SNS
- Create Topic
- Topic name: Check_Website
- Display name: checksite
- Subscribe yourself to this topic
Take note of the Topic ARN
Create IAM Policy
- Go to IAM
- Select Policies
- Create Policy
- Service: SNS
- Action: ALL (*)
- Resource: Specific, enter ARN from SNS topic created in previous step
- Review policy
- Name: publish_check_website
- Create Policy
Take note of the Policy ARN
Create the appropriate role
Create Lambda Function
- Go to Lambda
- Select Create Function
- Select Blueprints
- Filter on term, "lambda-canary" and select the blueprint
- Select Configure
- Basic Information
- Name: website-check
- Role: Choosing an existing role
- Existing role: Lambda_SNS
- cloudwatch-events
- Rule: Create a new rule
- Rule name: daily_website_check
- Rule type: schedule expression
- Schedule Expression: cron(0 10 * * ? *) Ref
- Enable trigger
- Create function
Update Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | from __future__ import print_function import os import json import boto3 from botocore.vendored import requests from datetime import datetime from urllib2 import urlopen SITES = os.environ['sites'] # URL of the site to check, stored in the site environment variable, e.g. https://aws.amazon.com EXPECTED = os.environ['expected'] # String expected to be on the page, stored in the expected environment variable, e.g. Amazon SNS_ARN = os.environ['sns_arn'] sites_array = SITES.split(';') expec_array = EXPECTED.split(';') def validate(res,exp): '''Return False to trigger the canary Currently this simply checks whether the EXPECTED string is present. However, you could modify this to perform any number of arbitrary checks on the contents of SITE. ''' return exp in res def lambda_handler(event, context): this_message = "Website Check Script\r\n" this_message = this_message + datetime.now().strftime('%m/%d/%Y %H:%M') this_message = this_message + "(UTC) \r\n" for i in range(len(sites_array)): this_message = this_message + 'Checking ' + sites_array[i] + ": " try: if not validate(urlopen(sites_array[i]).read(),expec_array[i]): raise Exception('Validation failed') except: this_message = this_message + 'Check Failed ' + "\r\n" else: this_message = this_message + 'Check Success ' + "\r\n" url = 'https://icanhazdadjoke.com/' headers = {'Accept': 'text/plain'} r = requests.get(url, headers=headers) print(r.text) this_message = this_message + "\r\b" + r.text + "\r\n" client = boto3.client('sns') response = client.publish( TargetArn=SNS_ARN, Message=this_message, MessageStructure='text' ) |
Update Environment Variables
- Update the keys to as follows:
- Values for expected and sites must be semi-colon separated. List of expected must be any unique string(s) that exists on the page
No comments:
Post a Comment