Skip to content

Instantly share code, notes, and snippets.

@ryanhoskin
Last active August 8, 2023 19:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ryanhoskin/333c66da3fa17b8f671086fd7db4dc35 to your computer and use it in GitHub Desktop.
Save ryanhoskin/333c66da3fa17b8f671086fd7db4dc35 to your computer and use it in GitHub Desktop.
Export a list of your PagerDuty users to a CSV file
#Export a list of all users to a CSV file.
#This script is not supported by PagerDuty.
#!/usr/bin/env python
import datetime
import requests
import sys
import csv
#Your PagerDuty API key. A read-only key will work for this.
AUTH_TOKEN = 'YOUR_API_KEY'
#The API base url, make sure to include the subdomain
BASE_URL = 'https://YOUR_SUBDOMAIN.pagerduty.com/api/v1'
csvfile = "users.csv"
HEADERS = {
'Authorization': 'Token token={0}'.format(AUTH_TOKEN),
'Content-type': 'application/json',
}
user_count = 0
def get_user_count():
global user_count
count = requests.get(
'{0}/users'.format(BASE_URL),
headers=HEADERS
)
user_count = count.json()['total']
def get_users(offset):
global user_count
params = {
'offset':offset
}
all_users = requests.get(
'{0}/users'.format(BASE_URL),
headers=HEADERS,
params=params
)
print "Exporting all users to " + csvfile
for user in all_users.json()['users']:
with open(csvfile, "a") as output:
writer = csv.writer(output, lineterminator='\n')
writer.writerow( [user['id']] + [user['email']] + [user['name']])
def main(argv=None):
if argv is None:
argv = sys.argv
get_user_count()
for offset in xrange(0,user_count):
if offset % 25 == 0:
get_users(offset)
if __name__=='__main__':
sys.exit(main())
@Fi-007
Copy link

Fi-007 commented Apr 5, 2022

im using python 3 and xrange function is making it error out for me. are you having this issue as well? any workaround?

@davi020
Copy link

davi020 commented May 19, 2022

@Fi-007 - xrange will work only on python2 version. If you are using python3, go for range instead of range. I created some easy code to get the same list of users In csv format - Checkout - https://gist.github.com/Johnsonkdavid/4600580d2e9c01854c97fd1fca63f733

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