1""" 2Library for interacting with PagerDuty API 3 4.. versionadded:: 2014.7.0 5 6:configuration: This module can be used by specifying the name of a 7 configuration profile in the minion config, minion pillar, or master 8 config. 9 10 For example: 11 12 .. code-block:: yaml 13 14 my-pagerduty-account: 15 pagerduty.subdomain: mysubdomain 16 pagerduty.api_key: F3Rbyjbve43rfFWf2214 17""" 18 19import logging 20 21import salt.utils.http 22import salt.utils.json 23from salt.version import __version__ 24 25log = logging.getLogger(__name__) 26 27 28def query( 29 method="GET", 30 profile_dict=None, 31 url=None, 32 path="api/v1", 33 action=None, 34 api_key=None, 35 service=None, 36 params=None, 37 data=None, 38 subdomain=None, 39 client_url=None, 40 description=None, 41 opts=None, 42 verify_ssl=True, 43): 44 """ 45 Query the PagerDuty API 46 """ 47 user_agent = "SaltStack {}".format(__version__) 48 49 if opts is None: 50 opts = {} 51 52 if isinstance(profile_dict, dict): 53 creds = profile_dict 54 else: 55 creds = {} 56 57 if api_key is not None: 58 creds["pagerduty.api_key"] = api_key 59 60 if service is not None: 61 creds["pagerduty.service"] = service 62 63 if subdomain is not None: 64 creds["pagerduty.subdomain"] = subdomain 65 66 if client_url is None: 67 client_url = "https://{}.pagerduty.com".format(creds["pagerduty.subdomain"]) 68 69 if url is None: 70 url = "https://{}.pagerduty.com/{}/{}".format( 71 creds["pagerduty.subdomain"], path, action 72 ) 73 74 if params is None: 75 params = {} 76 77 if data is None: 78 data = {} 79 80 data["client"] = user_agent 81 82 # pagerduty.service is not documented. While it makes sense to have in 83 # some cases, don't force it when it is not defined. 84 if "pagerduty.service" in creds and creds["pagerduty.service"] is not None: 85 data["service_key"] = creds["pagerduty.service"] 86 data["client_url"] = client_url 87 if "event_type" not in data: 88 data["event_type"] = "trigger" 89 if "description" not in data: 90 if not description: 91 data["description"] = "SaltStack Event Triggered" 92 else: 93 data["description"] = description 94 95 headers = { 96 "User-Agent": user_agent, 97 "Authorization": "Token token={}".format(creds["pagerduty.api_key"]), 98 } 99 if method == "GET": 100 data = {} 101 else: 102 headers["Content-type"] = "application/json" 103 104 result = salt.utils.http.query( 105 url, 106 method, 107 params=params, 108 header_dict=headers, 109 data=salt.utils.json.dumps(data), 110 decode=False, 111 text=True, 112 opts=opts, 113 ) 114 115 return result["text"] 116 117 118def list_items(action, key, profile_dict=None, api_key=None, opts=None): 119 """ 120 List items belonging to an API call. Used for list_services() and 121 list_incidents() 122 """ 123 items = salt.utils.json.loads( 124 query(profile_dict=profile_dict, api_key=api_key, action=action, opts=opts) 125 ) 126 ret = {} 127 for item in items[action]: 128 ret[item[key]] = item 129 return ret 130