Skip to content

Instantly share code, notes, and snippets.

@Deconstrained
Last active October 18, 2018 16:16
Show Gist options
  • Save Deconstrained/d18810f7a4b5d675a7c1676450c07b0f to your computer and use it in GitHub Desktop.
Save Deconstrained/d18810f7a4b5d675a7c1676450c07b0f to your computer and use it in GitHub Desktop.
Sample code for a Splunk plugin to submit PagerDuty impact metrics, but only when there's an open incident
#!/usr/bin/env python
"""
Sample code for a theoretical Splunk plugin to record an observed value as a
PagerDuty Impact Metric, and only during incidents triggered via Splunk
Requires pdpyras:
https://pagerduty.github.io/pdpyras/
"""
import json
import pdpyras
import sys
import datetime.datetime as datetime
srv_id = '' # Service ID here
metric_id = '' # Business impact metric ID here
api_key = '' # REST API key here
integration_id = '' # ID of the Splunk integration
# i.e. /services/{srv_id}/integrations/{integration_id}
# Go to the service's integrations tab and click on the integration's name to
# view this URL and the integration ID
def get_busines_metric(result):
# Your custom code here
# e.g. return result["somefieldname"]
return 1
def main():
# Check service:
session = pdpyras.APISession(api_key)
has_splunk_incident = False
for i in session.iter_all('incidents', params={
'service_ids[]':[srv_id],
'statuses[]':['triggered', 'acknowledged']
}):
alerts = list(session.iter_all(i['self']+'/alerts'))
if integration_id in [a['integration']['id'] for a in alerts]:
has_splunk_incident = True
break
if not has_splunk_incident:
return 0
payload = json.loads(sys.stdin.read())
result = payload.getdefault('result', None)
if result:
metric = get_business_metric(result)
now = datetime.strftime(datetime.now(), '%Y-%m-%dT%H:%M:%S%z')
response = session.post(
'/business_impact_metrics/%s/observations'%metric_id,
json={'observation':{"value": metric}, timestamp:now}
)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment