Skip to content

Instantly share code, notes, and snippets.

@Millnert
Forked from lfepp/recurring_maintenance_windows.py
Last active September 29, 2022 13:55
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 Millnert/34b92e70a5dcc35fc252d7728eb559a9 to your computer and use it in GitHub Desktop.
Save Millnert/34b92e70a5dcc35fc252d7728eb559a9 to your computer and use it in GitHub Desktop.
Script to create a number of recurring maintenance windows in PagerDuty
#!/usr/bin/env python3
"""Script to create reoccuring maintenance windows for PagerDuty"""
#
# Copyright (c) 2016, PagerDuty, Inc. <info@pagerduty.com>
# Copyright (c) 2022, BrainMill AB, <info@brainmill.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of PagerDuty Inc nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL PAGERDUTY INC BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Script to create a number of recurring maintenance windows
# CLI Usage: ./recurring_maintenance_windows.py \
# -a <api_key> \
# -e <email> \
# -s <start_date> \
# -d <duration> \
# -f <frequency> \
# -r <repeat> \
# -c <description> \
# -i <service_ids>
#
# api_key: Your PagerDuty API access token
# email: The email address associated with your PagerDuty account
# start_date: The date at which you would like the first mainteance window to occur
# duration: The length of time for the maintenance window in minutes
# frequency: The length of time between recurring maintenance windows in hours
# repeat: The number of times you want this maintenance window to recur
# description: A description for the maintenance window
# service_ids: The unique ID's of services you want to add these maintenance windows to
#
#
# 2022, BrainMill AB: Add logging and argparser.
import argparse
import json
import logging
#import sys
#from datetime import datetime, timedelta
from datetime import timedelta
from pprint import pformat
import requests
import dateutil.parser
def _setup_logging():
""" Configure (global?) logging """
logging.basicConfig(
format="[%(asctime)s.%(msecs).03d - %(levelname)7s - "
"%(filename)15s:%(lineno)-5s - %(funcName)20s()]: %(message)s",
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.DEBUG)
def _setup_argparser():
""" Sets up argparser """
parser = argparse.ArgumentParser(description="Schedule recurring PagerDuty maintenance windows")
# parser.add_argument("-c", "--conffile", action="store",
# default=DEFAULT_CONFFILE,
# help="Base directory to output to. Default: %s" %
# DEFAULT_CONFFILE)
parser.add_argument("-a", "--apikey", action="store", required=True,
help="Your PagerDuty API key.")
parser.add_argument("-e", "--email", action="store", required=True,
help="Your email address associated with your PagerDuty account.")
parser.add_argument("-s", "--start_date", action="store", required=True,
help="The date at which you would like the first maintenance window "
"to occur.")
parser.add_argument("-d", "--duration", action="store", required=True,
help="The length of time for the maintenance window in minutes.")
parser.add_argument("-f", "--frequency", action="store", required=True,
help="The length of time between recurring maintenancew windows in hours.")
parser.add_argument("-r", "--repeat", action="store", required=True,
help="The number of times you want this maintenance window to recur.")
parser.add_argument("-c", "--description", action="store", required=True,
help="A description of the maintenance window.")
parser.add_argument("-i", "--service_id", action="store", required=True, nargs='+',
help="The unique ID of services you want to add these maintenance "
"windows to. Can be repeated.")
return parser
def _parse_args(parser):
""" Run the parser and process the supplied args.
Returns dict with options """
args = vars(parser.parse_args())
logging.debug("opts (parse_args()")
logging.debug(pformat(args))
confs = {}
confs['apikey'] = args['apikey']
confs['email'] = args['email']
confs['start_date'] = args['start_date']
confs['duration'] = args['duration']
confs['frequency'] = args['frequency']
confs['repeat'] = args['repeat']
confs['description'] = args['description']
confs['service_id'] = args['service_id']
logging.debug('resulting conf')
logging.debug(pformat(confs))
return confs
def create_maintenance_windows(opts):
"""Creates maintenance windows"""
headers = {
'Authorization': 'Token token=' + opts.get('apikey'),
'Content-type': 'application/json',
'Accept': 'application/vnd.pagerduty+json;version=2',
'From': opts.get('email')
}
services_list = []
if isinstance(opts.get('service_id'), list):
for service in opts.get('service_id'):
services_list.append({
'id': service,
'type': 'service_reference'
})
else:
services_list.append({
'id': opts.get('service_id'),
'type': 'service_reference'
})
start = dateutil.parser.parse(opts.get('start_date'))
end = start + timedelta(minutes=int(opts.get('duration')))
for _ in range(0, int(opts.get('repeat'))):
payload = {
'maintenance_window': {
'type': 'maintenance_window',
'start_time': start.isoformat(),
'end_time': end.isoformat(),
'description': opts.get('description'),
'services': services_list
}
}
logging.info("Creating a %s minute maintenance window starting at %s",
opts.get('duration'), opts.get('start'))
logging.debug("Payload:")
logging.debug(pformat(payload))
req = requests.post('https://api.pagerduty.com/maintenance_windows',
headers=headers, data=json.dumps(payload))
if req.status_code == 201:
logging.info("Maintenance window with ID %s was successfully created",
req.json()['maintenance_window']['id'])
else:
logging.error("""Error: maintenance window creation failed!
Status code: %s
Response: %s
Exiting...""", str(req.status_code), req.text)
start = start + timedelta(hours=int(opts.get('frequency')))
end = end + timedelta(hours=int(opts.get('frequency')))
def main():
"""Main method"""
_setup_logging()
parser = _setup_argparser()
opts = _parse_args(parser)
create_maintenance_windows(opts)
if __name__ == '__main__':
main()
@Millnert
Copy link
Author

Python3, argparser, logging version of the original at https://gist.github.com/lfepp/32afebc59aa4b88a733bcc1b4f7236f9

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