Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This will generate a CSV containing user's names and email addresses if they do not have at least one SMS notification rule.
#!/usr/bin/python
import requests
import sys
import json
#Your PagerDuty API key. A read-only key will work for this.
auth_token = 'API_KEY_HERE'
#The PagerDuty subdomain
pd_subdomain = 'YOUR_PD_SUBDOMAIN'
HEADERS = {
'Authorization': 'Token token={0}'.format(auth_token),
'Content-type': 'application/json',
}
def convert_to_ascii(input):
if isinstance(input, dict):
return {convert_to_ascii(key): convert_to_ascii(value) for key, value in input.iteritems()}
elif isinstance(input, list):
return [convert_to_ascii(element) for element in input]
elif isinstance(input, unicode):
return input.encode('ascii', 'ignore')
else:
return input
def get_user_count():
user_count = requests.get(
'https://{0}.pagerduty.com/api/v1/users'.format(pd_subdomain),
headers=HEADERS,
)
return [user_count.json()['total'], user_count.json()['limit']]
def get_all_users():
total_users = get_user_count()
print("Total number of users: {0}".format(total_users[0]))
file = open('users_without_sms_rule.csv','w`')
for offset in xrange(0, total_users[0]):
if offset % total_users[1] == 0:
user_data = convert_to_ascii(get_users(offset, total_users[1]))
for user in user_data:
no_sms = True
for rule in user['notification_rules']:
if rule['contact_method']['type'] == "SMS":
no_sms = False
if no_sms == True:
file.write("{0}, {1}\n".format(user['name'], user['email']))
def get_users(offset, limit):
params = {
'offset': offset,
'limit': limit
}
users = requests.get(
'https://{0}.pagerduty.com/api/v1/users?include[]=notification_rules'.format(pd_subdomain),
headers=HEADERS,
data=json.dumps(params),
)
return users.json()['users']
def main(argv=None):
if argv is None:
argv = sys.argv
get_all_users()
if __name__=='__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment