forked from demisto/content
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration-test.yml
More file actions
609 lines (533 loc) · 28.2 KB
/
integration-test.yml
File metadata and controls
609 lines (533 loc) · 28.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
commonfields:
id: PagerDuty v2
version: 123
name: PagerDuty v2
display: PagerDuty v2
category: Messaging
image: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAAmCAYAAAAP4F9VAAAPuklEQVR4AezQsQAAAAACsPKXjqF/Q1g4AQBAFaxdqwBvKtvWx+LaNk3dvbiMFB4uY7hed3d3d3e/4+7uLkhhilwcakPd4p5j719tAmkmzIf06c067K/Jztal/1qH86OeYI/uxhP//NFAaKCo2FQ8+L6GD3wL3THmfzkJbwS6z2NYlmRV5kJSaEZA9JeFJJuDvk/V2kEpyPYGe/mwGOagPDJtN2UC7gv1ncewLDkNTm4oPDitN9RbKnCCNa7Ep0zA7d5Tl7WOtH7PFR3Tz3XMe3GuY/5P0K1MiYBZ5nzOmSUDb1A1nCai5bQM/oY5hlOnau2RyHDhKd+Ja4ZCQ4xD5wjU2xqmbG0hKAbOY1iW+kK9UUCWpFWxEPKUra3jdWEoUETLaw1GwRjYNbRj6gSMxZgk1dhqjXpB36zIijHFRbAqo8Tt+tzj+OxPndxgbSjeObyjTsNq5MnIjWVlRpFFJd6Jr8NMBioyFnGuiGs6y7L2tL3Cufq8o/gczTRvMDSg9YuB0rHoKM+zPEOkqApbaakK4uNApjmIa9xIZGQGzmlL7qXiEVVJmJM3t4swVHLscHTItmd4t1OURQZnY+iJyTHFIBh0iLs66qPpPMfLQ6HB6hO+k5U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HISPyXSOwUvLcyHPYdaqKRcbCjpxMudVwVYrwaNRyMh/7cIGLF4wUuDL67Wcpo3lfNYPNRPoHNF8crrV5asSnGJWfpu27fmPXH68atRWCLhTuYeAcFE1ROY5fez8mY9LcCHxwEQorzMC6gSScx/A+GFwQje4nhQekyHgSxIRf9oman8ri01W39Cb1WYLKXwLidQYiqNGwWDnCrgCbjAioQVkOlcv7R42Z/Rqwh4U/MaBDwoyZLOorXsZ/4bCKjz9TJThV1geTkNiNBLcPr9FL7c9dcjf05TuCw5jYXHS00lTwGfiJPLuCrHs1yk0FD4L6D72075TinUz+J/XDD/fylL3AWOz1JWwFnKCjhLWQFnKSvgLGUFnKX/BJsiJ1QqG3uJAAAAAElFTkSuQmCC
description: Alert and notify users using PagerDuty
configuration:
- display: API Key
name: APIKey
defaultvalue: ""
type: 4
required: true
- display: Service Key (for triggering events only)
name: ServiceKey
defaultvalue: ""
type: 0
required: false
script:
script: |
''' IMPORTS '''
import os
import json
import requests
import datetime
''' GLOBAL VARS '''
# Pagerduty API works only with secured communication.
USE_SSL = True
API_KEY = demisto.params()['APIKey']
SERVICE_KEY = demisto.params()['ServiceKey']
SERVER_URL = "https://api.pagerduty.com/"
DEFAULT_HEADERS = {
'Authorization': 'Token token=' + API_KEY,
'Accept': 'application/vnd.pagerduty+json;version=2'
}
'''SUFFIX ENDPOINTS'''
GET_SCHEDULES_SUFFIX = "schedules/"
CREATE_INCIDENT_SUFFIX = "incidents"
ON_CALL_BY_SCHEDULE_SUFFIX = "schedules/{0}/users"
ON_CALLS_USERS_SUFFIX = "oncalls?include%5B%5D=users"
USERS_NOTIFICATION_RULE = "users/{0}/notification_rules"
GET_INCIDENTS_SUFFIX = "incidents?include%5B%5D=assignees"
USERS_CONTACT_METHODS_SUFFIX = "users/{0}/contact_methods"
'''CONTACT_METHOD_TYPES'''
SMS_CONTACT_TYPE = "sms_contact_method"
EMAIL_CONTACT_TYPE = "email_contact_method"
PHONE_CONTACT_TYPE = "phone_contact_method"
PUSH_CONTACT_TYPE = "push_notification_contact_method"
CONTACT_METHODS_TO_HUMAN_READABLE = {
'': 'Unknown',
SMS_CONTACT_TYPE: 'SMS',
PUSH_CONTACT_TYPE: 'Push',
EMAIL_CONTACT_TYPE: 'Email',
PHONE_CONTACT_TYPE: 'Phone'
}
'''TABLE NAMES'''
SCHEDULES = "All Schedules"
TRIGGER_EVENT = 'Trigger Event'
USERS_ON_CALL = 'Users On Call'
CONTACT_METHODS = "Contact Methods"
USERS_ON_CALL_NOW = 'Users On Call Now'
NOTIFICATION_RULES = "User notification rules"
'''TABLE HEADERS'''
CONTACT_METHODS_HEADERS = ['ID', 'Type', 'Address']
NOTIFICATION_RULES_HEADERS = ["ID", "Type", "Urgency", "Notification timeout(minutes)"]
SCHEDULES_HEADERS = ["ID", "Name", "Today", "Time Zone", "Escalation Policy", "Escalation Policy ID"]
USERS_ON_CALL_NOW_HEADERS = ["ID", "Email", "Name", "Role", "Color", "User Url", "Avatar Url", "Time Zone"]
INCIDENTS_HEADERS = ["ID", "Incident Number", "Created On", "Status", "Html Url", "Service ID", "Service Name", "Service Html Url", "Assigned To User",
"Escalation Policy", "Escalation Policy ID", "Trigger Details Html Url", "Trigger Type", "Last Status Change On", "Last Status Change By",
"Number Of Escalations", "Resolved By User", "Assigned To", "Summary"]
''' HELPER FUNCTIONS '''
def http_request(method, url_suffix, params_dict):
url = SERVER_URL + url_suffix
LOG('running %s request with url=%s\theaders=%s\nparams=%s' % (method, url, DEFAULT_HEADERS, json.dumps(params_dict)))
try:
res = requests.request(method,
url,
verify=USE_SSL,
params=params_dict,
headers=DEFAULT_HEADERS,
)
res.raise_for_status()
return res.json()
except Exception, e:
LOG(e)
raise(e)
def test_module():
try:
get_on_call_now_users_command()
except Exception, e:
raise Exception(e.message)
demisto.results("ok")
def extract_on_call_user_data(users):
"""Extact data about user from a given schedule."""
outputs = []
contexts = []
for i, user in enumerate(users):
output = {}
context = {}
output['ID'] = user.get('id')
output['Name'] = user.get('name')
output['Role'] = user.get('role')
output['Color'] = user.get('color')
output['Email'] = user.get('email')
output['User Url'] = user.get('html_url')
output['Time Zone'] = user.get('time_zone')
output['Avatar Url'] = user.get('avatar_url')
context['ID'] = output['ID']
context['Role'] = output['Role']
context['Email'] = output['Email']
context['Username'] = output['Name']
context['DisplayName'] = output['Name']
outputs.append(output)
contexts.append(context)
return {
'Type': entryTypes['note'],
'Contents': outputs,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(USERS_ON_CALL, outputs, USERS_ON_CALL_NOW_HEADERS),
'EntryContext': {
'PagerDutyUser(val.ID==obj.ID)': contexts
}
}
def extract_on_call_now_user_data(oncalls, table_name):
"""Extract the user data from the oncalls json."""
outputs = []
contexts = []
for i in xrange(len(oncalls)):
output = {}
context = {}
data = oncalls[i]
user = data.get('user')
output['ID'] = user.get('id')
output['Name'] = user.get('name')
output['Role'] = user.get('role')
output['Color'] = user.get('color')
output['Email'] = user.get('email')
output['User Url'] = user.get('html_url')
output['Time Zone'] = user.get('time_zone')
output['Avatar Url'] = user.get('avatar_url')
context['ID'] = output['ID']
context['Role'] = output['Role']
context['Email'] = output['Email']
context['Username'] = output['Name']
context['DisplayName'] = output['Name']
escal_level = data.get('escalation_level', 1)
outputs.insert(escal_level - 1, output)
contexts.insert(escal_level - 1, context)
return {
'Type': entryTypes['note'],
'Contents': outputs,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(table_name, outputs, USERS_ON_CALL_NOW_HEADERS),
'EntryContext': {
'PagerDutyUser(val.ID==obj.ID)': contexts
}
}
def extract_incidents_data(incidents):
"""Extact data about incidents."""
outputs = []
for i, incident in enumerate(incidents):
output = {}
output['ID'] = incident.get('id')
output['Status'] = incident.get('status')
output['Html Url'] = incident.get('html_url')
output['Created On'] = incident.get('created_at')
output['Incident Number'] = incident.get('incident_number')
output['Service ID'] = incident.get('service', {}).get('id')
output['Service Name'] = incident.get('service', {}).get('summary')
output['Service Html Url'] = incident.get('service', {}).get('html_url')
if len(incident.get('assignments', [])) > 0:
output['Assigned To User'] = incident['assignments'][0].get('assignee', {}).get('name')
else:
output['Assigned To User'] = '-'
output['Escalation Policy ID'] = incident.get('escalation_policy', {}).get('id')
output['Escalation Policy'] = incident.get('escalation_policy', {}).get('summary')
output['Trigger Type'] = incident.get('first_trigger_log_entry', {}).get('summary')
output['Trigger Details Html Url'] = incident.get('first_trigger_log_entry', {}).get('html_url')
output['Last Status Change On'] = incident.get('last_status_change_at')
output['Last Status Change By'] = incident.get('last_status_change_by', {}).get('summary')
output['Number Of Escalations'] = incident.get('number_of_escalations')
if output['Status'] == "resolved":
output['Resolved By User'] = output.get('Last Status Change By')
else:
output['Resolved By User'] = '-'
output['Assigned To'] = output['Assigned To User'] ###### This field is a duplicate, not sure why it's needed, should I delete?
output['Summary'] = incident.get('summary')
outputs.append(output)
return {
'Type': entryTypes['note'],
'Contents': outputs,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(USERS_ON_CALL, outputs, INCIDENTS_HEADERS),
'EntryContext': {
'PagerDuty.Incidents(val.id==obj.id)': incidents
}
}
def extract_all_schedules_data(schedules):
"""Extract the data about all the schedules."""
outputs = []
contexts = []
for i in range(len(schedules)):
output = {}
context = {}
data = schedules[i]
output['ID'] = data.get('id')
output['Name'] = data.get('name')
output['Time Zone'] = data.get('time_zone')
output['Today'] = datetime.datetime.today().strftime('%Y-%m-%d')
escalation_policies = data.get('escalation_policies', [])
if len(escalation_policies) > 0:
output['Escalation Policy ID'] = escalation_policies[0].get('id')
output['Escalation Policy'] = escalation_policies[0].get('summary')
context['escalation_policies'] = [{}, ]
context['escalation_policies'][0]['name'] = output['Escalation Policy']
context['escalation_policies'][0]['id'] = output['Escalation Policy ID']
else:
output['Escalation Policy'] = "-"
output['Escalation Policy ID'] = "-"
context['id'] = output['ID']
context['name'] = output['Name']
context['today'] = output['Today']
context['time_zone'] = output['Time Zone']
outputs.append(output)
contexts.append(context)
return {
'Type': entryTypes['note'],
'Contents': outputs,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(SCHEDULES, outputs, SCHEDULES_HEADERS),
'EntryContext': {
'PagerDuty.Schedules(val.id==obj.id)': contexts,
}
}
def create_new_incident(author, title, description='No description'):
"""Create a new incident in the PagerDuty instance."""
url = SERVER_URL + CREATE_INCIDENT_SUFFIX
headers = DEFAULT_HEADERS.copy()
headers['From'] = author
headers['Content-Type'] = "application/json"
payload = {
"incident": {
"type": "incident",
"title": title,
"service": {
"id": SERVICE_KEY,
"type": "service_reference"
},
"body": {
"type": "incident_body",
"details": description
}
}
}
res = requests.post(url, headers=headers, data=json.dumps(payload), verify=USE_SSL)
res.raise_for_status()
return res.json()
def extract_new_event_data(response):
"""Extract the data from the response of creating a new command."""
output = {}
output['Status'] = response.get('incident', {}).get('status')
output['Incident Key'] = response.get('incident', {}).get('incident_key')
return {
'Type': entryTypes['note'],
'Contents': output,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(TRIGGER_EVENT, output),
'EntryContext': {
'PagerDuty.Event(val.id==obj.id)': output
}
}
def extract_users_contact_methods(user_contact_methods):
"""Extract all the contact methods of a given user."""
outputs = []
contexts = []
contact_methods = user_contact_methods.get('contact_methods')
for contact_method in contact_methods:
output = {}
output['ID'] = contact_method.get('id')
output['Type'] = CONTACT_METHODS_TO_HUMAN_READABLE[contact_method.get('type', '')]
country_code = str(contact_method.get("country_code" ,""))
address = contact_method.get('address', "")
output['Address'] = country_code + address
outputs.append(output)
contexts.append(contact_method)
return {
'Type': entryTypes['note'],
'Contents': outputs,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(CONTACT_METHODS, outputs, CONTACT_METHODS_HEADERS),
'EntryContext': {
'PagerDuty.Contact_methods(val.id==obj.id)': contexts,
}
}
def extract_users_notification_role(user_notication_role):
"""Extract the notification role of a given user."""
outputs = []
notification_rules = user_notication_role.get('notification_rules')
for notification_rule in notification_rules:
output = {}
output['ID'] = notification_rule.get('id')
output['Type'] = notification_rule.get('type', '')
output['Urgency'] = notification_rule.get('urgency')
output['Notification timeout(minutes)'] = notification_rule.get('start_delay_in_minutes')
outputs.append(output)
return {
'Type': entryTypes['note'],
'Contents': outputs,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(NOTIFICATION_RULES, outputs, NOTIFICATION_RULES_HEADERS),
'EntryContext': {
'PagerDuty.Notification_rules(val.id==obj.id)': notification_rules,
}
}
'''COMMANDS'''
def get_incidents_command(since=None, until=None, status=None, sortBy=None):
"""Get incidents command."""
param_dict = {}
if since is not None:
param_dict["since"] = since
if until is not None:
param_dict["until"] = until
if status is not None:
param_dict["status"] = status
if sortBy is not None:
param_dict["sortBy"] = sortBy
res = http_request('GET', GET_INCIDENTS_SUFFIX, param_dict)
return extract_incidents_data(res.get("incidents",[]))
def submit_event_command(author, title, description=None):
"""Create new event."""
if SERVICE_KEY is None:
raise Exception("You must enter a ServiceKey at the integration parmaters to process this action.")
res = create_new_incident(author, title, description)
return extract_new_event_data(res)
def get_all_schedules_command():
"""Get all the schedules."""
res = http_request('GET', GET_SCHEDULES_SUFFIX, {})
schedules = res.get('schedules', [])
return extract_all_schedules_data(schedules)
def get_on_call_users_command(scheduleID, since=None, until=None):
"""Get the list of user on call in a from scheduleID"""
param_dict = {}
if since is not None:
param_dict["since"] = since
if until is not None:
param_dict["until"] = until
url = ON_CALL_BY_SCHEDULE_SUFFIX.format(scheduleID)
users_on_call = http_request('GET', url, param_dict)
return extract_on_call_user_data(users_on_call.get('users', []))
def get_on_call_now_users_command():
"""Get the list of users that are on call now."""
users_on_call_now = http_request('GET', ON_CALLS_USERS_SUFFIX, {})
oncalls = users_on_call_now.get('oncalls', {})
return extract_on_call_now_user_data(oncalls, USERS_ON_CALL_NOW)
def get_users_contact_methods_command(UserID):
"Get the contact methods of a given user."
user_contact_methods = http_request('GET', USERS_CONTACT_METHODS_SUFFIX.format(UserID), {})
return extract_users_contact_methods(user_contact_methods)
def get_users_notification_command(UserID):
"Get the notification rule of a given user"
user_notication_role = http_request('GET', USERS_NOTIFICATION_RULE.format(UserID), {})
return extract_users_notification_role(user_notication_role)
''' EXECUTION CODE '''
LOG('command is %s' % (demisto.command(), ))
try:
if demisto.command() == 'test-module':
test_module()
elif demisto.command() == 'PagerDutyIncidents':
demisto.results(get_incidents_command(**demisto.args()))
elif demisto.command() == 'PagerDutySubmitEvent':
demisto.results(submit_event_command(**demisto.args()))
elif demisto.command() == 'PagerDutyGetUsersOnCall':
demisto.results(get_on_call_users_command(**demisto.args()))
elif demisto.command() == 'PagerDutyGetAllSchedules':
demisto.results(get_all_schedules_command(**demisto.args()))
elif demisto.command() == 'PagerDutyGetUsersOnCallNow':
demisto.results(get_on_call_now_users_command(**demisto.args()))
elif demisto.command() == 'PagerDutyGetContactMethods':
demisto.results(get_users_contact_methods_command(**demisto.args()))
elif demisto.command() == 'PagerDutyGetUsersNotification':
demisto.results(get_users_notification_command(**demisto.args()))
except Exception, e:
LOG(e.message)
LOG.print_log()
raise
type: python
subtype: python2
commands:
- name: PagerDutyGetAllSchedules
arguments:
- name: query
description: Show only the schedules whose name matches the query
- name: requesterID
description: The user id of the user making the request. This will be used to
generate the calendar private urls. This is only needed if you are using token
based authentication.
outputs:
- contextPath: PagerDuty.Schedules
description: schedules
type: string
description: Receive all schedules from PagerDuty
- name: PagerDutyGetUsersOnCall
arguments:
- name: scheduleID
required: true
default: true
description: (default and mandatory) The unique identifier of the schdule
- name: since
description: The start of the date range Using ISO 8601 Representation. E.g.
!PagerDutyGetUsersOnCall since=2011-05-06T17:00Z
- name: until
description: The end of the date range
outputs:
- contextPath: PagerDutyUser.id
description: User's ID
type: string
- contextPath: PagerDutyUser.Emails
description: Email of user
type: string
- contextPath: PagerDutyUser.Username
description: Username of person
type: string
- contextPath: PagerDutyUser.DisplayName
description: Display name of person
type: string
- contextPath: PagerDutyUser.Role
description: Display role of person
type: string
description: Returns the names and details of on call users at a certain time
or by specific schedule
- name: PagerDutyGetUsersOnCallNow
arguments:
- name: query
description: show only the names matching the query
outputs:
- contextPath: PagerDutyUser.ID
description: User's ID
type: string
- contextPath: PagerDutyUser.Email
description: Email of user
type: string
- contextPath: PagerDutyUser.Username
description: Username of person
type: string
- contextPath: PagerDutyUser.DisplayName
description: Display name of person
type: string
- contextPath: PagerDutyUser.Role
description: Role of person
type: string
description: Returns the names and details of current on call personnel
- name: PagerDutyIncidents
arguments:
- name: status
auto: PREDEFINED
predefined:
- triggered
- acknowledged
- resolved
description: Returns only the incidents currently in the passed status(es).
Valid status options are triggered,acknowledged, and resolved
- name: since
description: Beginning date and time. Using ISO 8601 Representation. E.g. PagerDutyIncidents
since=2011-05-06T17:00Z
- name: sortBy
description: 'Used to specify both the field you wish to sort the results on,
as well as the direction (ascending/descending) of the results.See more https://developer.pagerduty.com/documentation/rest/incidents/list '
- name: until
description: Last date and time. Using ISO 8601 Representation. E.g. PagerDutyIncidents
until=2016-05-06T13:00Z
outputs:
- contextPath: PagerDuty.Incidents
description: All incidents
description: Shows incidents in PagerDuty
- name: PagerDutySubmitEvent
arguments:
- name: author
required: true
description: The email address of a valid user associated with the account making
the request.
- name: title
required: true
description: The name of the incident you create
- name: description
description: A short description of the problem
outputs:
- contextPath: PagerDuty.Event
description: Event data
description: Creates a new event/incident in PagerDuty
- name: PagerDutyGetContactMethods
arguments:
- name: UserID
required: true
description: 'ID of the wanted user '
outputs:
- contextPath: PagerDuty.Contact_methods.address
description: The address of the user
type: string
- contextPath: PagerDuty.Contact_methods.id
description: ID of the contact method
type: string
- contextPath: PagerDuty.Contact_methods.type
description: The type of the current contact method
type: string
description: Get the contact methods of a given user
- name: PagerDutyGetUsersNotification
arguments:
- name: UserID
required: true
description: ID of the wanted user
outputs:
- contextPath: PagerDuty.Notification_rules.PagerDuty.Notification_rules.start_delay_in_minutes
description: The delay time for notifying the user
type: string
- contextPath: PagerDuty.Notification_rules.PagerDuty.Notification_rules.urgency
description: The urgency of the notification
type: string
- contextPath: PagerDuty.Notification_rules.id
description: The id of the notification rule
type: string
description: Get the users notification rules
runonce: false
hidden: false
tests:
- PagerDuty Test