Snippets

JimD Python script to schedule PagerDuty Maintenance via AWS Lambda/Cloudwatch

Created by JimD last modified
#!/usr/bin/python3
# Python script to create reoccurring PagerDuty Maintenance Window and scheduled via AWS Cloudwatch/Lambda Function
# Tested with Python 3.5.1
#
# You will need to intall python requests module
# %python_home%\Scripts\pip install requests
# https://pypi.python.org/pypi/requests/2.9.1
#
# February 27, 2016
#
# 3/20/16 - Added abiltiy to schedule maintenance on a single specific day of the upcoming week
import requests
import json
import datetime
import pytz

class PdMaintenanceWindow:
    """PagerDuty Maintenance Windows

    This class allows you to setup reoccurring maintenance windows using the PagerDuty API

    """
    __url='https://{ENTER SUBDOMAIN HERE}.pagerduty.com/api/v1/maintenance_windows' #Your PagerDuty URL
    __description='Reoccurring Routine Scheduled Maintenance' #Description of the maintanence
    __requester='' #The PagerDuty User that created the maintenace, will default to 'API' if not specified
    __timezone=pytz.timezone('ENTER TIMEZONE HERE') #Your timezone, required to set current date/time to match your timezone

    def __init__(self, apiToken, services, startDay, startTime, minutes):
        """
        :param apiToken: The PagerDuty API tocken generated from your account
        :param services: The service IDs
        :param startDay: The day maintenance begins, 0=Mon,1=Tue,2=Wed,3=Thu,4=Fri,5=Sat,6=Sun,*="daily"
        :param startTime: The time maintenance begins
        :param minutes: The duration of maintenance
        :return:
        """
        self.apiToken = apiToken
        self.services = services
        self.startDay = startDay
        self.startTime = startTime
        self.minutes = minutes

    def CreateWeeklySchedule(self):
        """
        Creates the daily maintenance schedule

        The function will create the next 7 days of maintenance beginning tomorrow from the date it is run.

        :raises: A runtime error if a http 201 "created" is not returned.
        """
        nextDay = 1
        if (self.startDay == '*'):
            loop = 7
        else:
            loop = 1
            d = datetime.datetime.now(self.__timezone)
            d += datetime.timedelta(days=nextDay)
            while d.weekday() != int(self.startDay):
                d += datetime.timedelta(days=1)
                nextDay += 1

        startTime = datetime.datetime.now(self.__timezone).replace(hour=self.startTime.hour,minute=self.startTime.minute,second=0,microsecond=0)
        for i in range(loop):
            startTime += datetime.timedelta(days=nextDay)
            endTime = startTime
            endTime += datetime.timedelta(minutes=self.minutes)
            headers = {'Content-type': 'application/json','Authorization': 'Token token='+self.apiToken}
            payload = ({
                       "maintenance_window": {
                         "start_time": startTime.isoformat(),
                         "end_time": endTime.isoformat(),
                         "description": self.__description,
                         "service_ids": self.services
                       },
                       "requester_id": self.__requester
                     })

            r = requests.post(self.__url, data=json.dumps(payload), headers=headers)
            if r.status_code != 201:
                raise RuntimeError("API call failed, status code: " + str(r.status_code))

#Handler Name must match AWS Lambda Handler Configuration
def lambda_handler(event, context):
    apiToken = "ENTER PAGERDUTY API TOKEN HERE"
    ## Create weekly service schedule 1
    PdMaintenanceWindow(apiToken,["ENTER SERVICES HERE"],"ENTER DAY HERE",datetime.time("ENTER HOUR HERE","ENTER MINUTE HERE"),"ENTER DURATION HERE").CreateWeeklySchedule()
    ## Create weekly service schedule 2
    PdMaintenanceWindow(apiToken,["ENTER SERVICES HERE"],"ENTER DAY HERE",datetime.time("ENTER HOUR HERE","ENTER MINUTE HERE"),"ENTER DURATION HERE").CreateWeeklySchedule()
    return "success"

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.