Skip to content

Instantly share code, notes, and snippets.

@PerStirpes
Created March 5, 2019 08:33
Show Gist options
  • Save PerStirpes/9def34ef104552b50d45955fa431cd4a to your computer and use it in GitHub Desktop.
Save PerStirpes/9def34ef104552b50d45955fa431cd4a to your computer and use it in GitHub Desktop.
Export LaunchDarkly audit logs to CSV
#!/usr/bin/env python3
"""
Requirements:
pip install requests python-dateutil
"""
import dateutil.parser as dp
import csv
import sys
from optparse import OptionParser
import requests
BASE_URL = 'https://app.launchdarkly.com'
parser = OptionParser()
parser.add_option("-f", "--filename", dest="filename", default="ld_audit_log.txt", help="filename to write")
parser.add_option("-k", "--api-key", dest="api_key", help="LaunchDarkly API key")
parser.add_option("-a", "--after", dest="after", default=None, help="A date when to export the logs from (ISO-8601)")
(options, args) = parser.parse_args()
if not options.api_key:
print("Please supply an API key.")
sys.exit(1)
def get_items(url):
headers = {'Authorization': options.api_key}
try:
r = requests.get(BASE_URL + url, headers=headers)
r.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error calling LaunchDarkly API")
print(str(e))
return [], None
res = r.json()
n = res['_links']['next']['href'] if '_links' in res and 'next' in res['_links'] else None
return res.get('items', []), n
all_items = []
next_ = '/api/v2/auditlog?limit=20'
if options.after:
next_ += f"&after={int(dp.parse(options.after).timestamp() * 1000)}"
while (True):
print(next_)
items, next_ = get_items(next_)
all_items.extend(items)
if next_ is None:
break
rows = []
for i in [item for item in all_items if item.get('kind', None) == 'flag']:
row = {
'user': i['member']['email'],
'flag': i['name'],
'description': i['description'].rstrip(),
}
rows.append(row)
with open(options.filename, 'w') as f:
w = csv.DictWriter(f, rows[0].keys())
w.writeheader()
w.writerows(rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment