-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd-PagerDuty365IncidentNote.ps1
More file actions
508 lines (417 loc) · 19.4 KB
/
Add-PagerDuty365IncidentNote.ps1
File metadata and controls
508 lines (417 loc) · 19.4 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
<#
.SYNOPSIS
Adds a note to an existing PagerDuty incident
.DESCRIPTION
This script adds a note to a PagerDuty incident using the REST API.
Can find incidents by ID, title, or dedup key.
IMPORTANT:
- The UserEmail parameter must be a valid PagerDuty user's email address.
- Search by title only works on incident titles, NOT incident body/description content.
.PARAMETER ApiToken
PagerDuty REST API token (required)
.PARAMETER IncidentId
The ID of the incident to add a note to (required unless using other search methods)
.PARAMETER Note
The content of the note to add (required)
.PARAMETER UserEmail
Email address of the user adding the note (required)
MUST be a valid PagerDuty user email address with appropriate permissions
.PARAMETER FindIncidentByTitle
Switch to search for incident by title instead of using ID
.PARAMETER IncidentTitle
Title or partial title to search for (used with -FindIncidentByTitle)
Note: This searches the incident TITLE only, not the body/description
.PARAMETER FindIncidentByDedupKey
Switch to search for incident by dedup key instead of using ID
.PARAMETER DedupKey
Dedup key from incident creation to search for (used with -FindIncidentByDedupKey)
.PARAMETER IncludeResolved
Include resolved incidents in the search (by default only shows triggered/acknowledged)
.PARAMETER ListIncidents
Just list all available incidents without adding a note
.EXAMPLE
# List all active incidents to find the right ID
.\Add-PagerDutyIncidentNote.ps1 -ApiToken "your_api_token" -ListIncidents -UserEmail "analyst@company.com" -Note "dummy"
.EXAMPLE
# List ALL incidents including resolved
.\Add-PagerDutyIncidentNote.ps1 -ApiToken "your_api_token" -ListIncidents -IncludeResolved -UserEmail "analyst@company.com" -Note "dummy"
.EXAMPLE
# Add note using incident ID directly
.\Add-PagerDutyIncidentNote.ps1 -ApiToken "your_api_token" -IncidentId "P1234567" -Note "SOC investigating" -UserEmail "analyst@company.com"
.EXAMPLE
# Search by title (searches incident titles only, not body content)
.\Add-PagerDutyIncidentNote.ps1 -ApiToken "your_api_token" -FindIncidentByTitle -IncidentTitle "disk space" -Note "Investigation update" -UserEmail "soc@company.com"
.EXAMPLE
# Search including resolved incidents
.\Add-PagerDutyIncidentNote.ps1 -ApiToken "your_api_token" -FindIncidentByTitle -IncidentTitle "alert" -IncludeResolved -Note "Post-mortem note" -UserEmail "soc@company.com"
.NOTES
- API token: Found in PagerDuty under User Settings > API Access Keys
- UserEmail MUST be a valid PagerDuty user email (not just any email address)
- Common error 1008 means "Requester User Not Found" - check the email address
- The script searches incident TITLES only, not body/description content
- Use -ListIncidents to see all available incidents and their IDs
- Use -Verbose for additional debug information
Author: Geoff Tankersley
Version: 2.1
#>
param(
[Parameter(Mandatory=$true)]
[string]$ApiToken,
[Parameter(Mandatory=$false)]
[string]$IncidentId,
[Parameter(Mandatory=$true)]
[string]$Note,
[Parameter(Mandatory=$true)]
[string]$UserEmail,
[Parameter(Mandatory=$false)]
[switch]$FindIncidentByTitle,
[Parameter(Mandatory=$false)]
[string]$IncidentTitle = "",
[Parameter(Mandatory=$false)]
[switch]$FindIncidentByDedupKey,
[Parameter(Mandatory=$false)]
[string]$DedupKey = "",
[Parameter(Mandatory=$false)]
[switch]$IncludeResolved,
[Parameter(Mandatory=$false)]
[switch]$ListIncidents
)
function Add-PagerDutyNote {
param(
[string]$ApiToken,
[string]$IncidentId,
[string]$Note,
[string]$UserEmail
)
$Uri = "https://api.pagerduty.com/incidents/$IncidentId/notes"
# From header is REQUIRED and must be a valid PagerDuty user email
$Headers = @{
"Authorization" = "Token token=$ApiToken"
"Content-Type" = "application/json"
"Accept" = "application/vnd.pagerduty+json;version=2"
"From" = $UserEmail # This is MANDATORY and must be a valid PagerDuty user email
}
$Payload = @{
note = @{
content = $Note
}
}
$JsonPayload = $Payload | ConvertTo-Json -Depth 3
try {
Write-Host "Adding note to incident $IncidentId..." -ForegroundColor Yellow
Write-Host "Note preview: $($Note.Substring(0, [Math]::Min(100, $Note.Length)))$(if($Note.Length -gt 100){'...'})" -ForegroundColor Cyan
Write-Host "From user: $UserEmail" -ForegroundColor Gray
Write-Verbose "Headers: $($Headers | ConvertTo-Json)"
Write-Verbose "JSON Payload: $JsonPayload"
# Make the API call
$Response = Invoke-RestMethod -Uri $Uri -Method Post -Body $JsonPayload -Headers $Headers
Write-Host "✓ Note added successfully!" -ForegroundColor Green
Write-Host "Note ID: $($Response.note.id)" -ForegroundColor Green
Write-Host "Created at: $($Response.note.created_at)" -ForegroundColor Green
Write-Host "Created by: $($Response.note.user.summary)" -ForegroundColor Green
return $Response.note
}
catch {
$StatusCode = $_.Exception.Response.StatusCode
Write-Error "Failed to add note to PagerDuty incident: $StatusCode"
# Error handling
if ($_.ErrorDetails.Message) {
$errorJson = $_.ErrorDetails.Message | ConvertFrom-Json -ErrorAction SilentlyContinue
if ($errorJson) {
Write-Host "API Error:" -ForegroundColor Red
Write-Host " Code: $($errorJson.error.code)" -ForegroundColor Red
Write-Host " Message: $($errorJson.error.message)" -ForegroundColor Red
if ($errorJson.error.errors) {
Write-Host " Details: $($errorJson.error.errors -join ', ')" -ForegroundColor Red
}
# Common error codes
if ($errorJson.error.code -eq 1008) {
Write-Host "`nNote: Error 1008 means 'Requester User Not Found'. Ensure that:" -ForegroundColor Yellow
Write-Host " - The email address '$UserEmail' belongs to a valid PagerDuty user" -ForegroundColor Yellow
Write-Host " - The user has appropriate permissions to add notes to incidents" -ForegroundColor Yellow
}
}
else {
Write-Host "Raw error: $($_.ErrorDetails.Message)" -ForegroundColor Red
}
}
throw
}
}
function Test-PagerDutyApiToken {
param([string]$ApiToken)
$Headers = @{
"Authorization" = "Token token=$ApiToken"
"Accept" = "application/vnd.pagerduty+json;version=2"
}
try {
Write-Host "Testing API token..." -ForegroundColor Yellow
Write-Verbose "Token: $($ApiToken.Substring(0, [Math]::Min(10, $ApiToken.Length)))..."
$Response = Invoke-RestMethod -Uri "https://api.pagerduty.com/abilities" -Method Get -Headers $Headers
Write-Host "✓ API token is valid" -ForegroundColor Green
return $true
}
catch {
Write-Error "API token validation failed: $($_.Exception.Message)"
if ($_.ErrorDetails.Message) {
Write-Host "Error details: $($_.ErrorDetails.Message)" -ForegroundColor Red
}
return $false
}
}
function Find-PagerDutyIncidentByDedupKey {
param(
[string]$ApiToken,
[string]$DedupKey
)
$Headers = @{
"Authorization" = "Token token=$ApiToken"
"Accept" = "application/vnd.pagerduty+json;version=2"
}
Write-Host "Searching for incident with dedup key: '$DedupKey'..." -ForegroundColor Yellow
# Search recent incidents
$Since = (Get-Date).AddDays(-7).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
$Uri = "https://api.pagerduty.com/incidents?since=$Since&limit=100&include[]=first_trigger_log_entries"
try {
$Response = Invoke-RestMethod -Uri $Uri -Method Get -Headers $Headers
Write-Host "Checking $($Response.incidents.Count) recent incidents..." -ForegroundColor Gray
foreach ($incident in $Response.incidents) {
# Check first trigger log entry
if ($incident.first_trigger_log_entry -and
$incident.first_trigger_log_entry.channel -and
$incident.first_trigger_log_entry.channel.details -and
$incident.first_trigger_log_entry.channel.details.dedup_key -eq $DedupKey) {
Write-Host "Found incident: $($incident.id) - $($incident.title)" -ForegroundColor Green
return $incident.id
}
# Incident_key fallback
if ($incident.incident_key -eq $DedupKey) {
Write-Host "Found incident via incident_key: $($incident.id) - $($incident.title)" -ForegroundColor Green
return $incident.id
}
}
# Pagination
$offset = 100
while ($Response.more -and $offset -lt 500) {
$PageUri = "https://api.pagerduty.com/incidents?since=$Since&limit=100&offset=$offset&include[]=first_trigger_log_entries"
$Response = Invoke-RestMethod -Uri $PageUri -Method Get -Headers $Headers
foreach ($incident in $Response.incidents) {
if ($incident.first_trigger_log_entry?.channel?.details?.dedup_key -eq $DedupKey -or
$incident.incident_key -eq $DedupKey) {
Write-Host "Found incident: $($incident.id) - $($incident.title)" -ForegroundColor Green
return $incident.id
}
}
$offset += 100
}
Write-Warning "No incident found with dedup key: '$DedupKey'"
return $null
}
catch {
Write-Error "Failed to search by dedup key: $($_.Exception.Message)"
throw
}
}
function Find-PagerDutyIncident {
param(
[string]$ApiToken,
[string]$IncidentTitle,
[switch]$IncludeResolved
)
$Headers = @{
"Authorization" = "Token token=$ApiToken"
"Accept" = "application/vnd.pagerduty+json;version=2"
}
try {
Write-Host "Searching for incidents..." -ForegroundColor Yellow
Write-Host "Search term: '$IncidentTitle'" -ForegroundColor Gray
Write-Host "Note: Search only works on incident titles, not body content" -ForegroundColor Gray
# Get incidents - try with statuses parameter first
$BaseUri = "https://api.pagerduty.com/incidents"
# Try to get incidents with specific statuses
if (-not $IncludeResolved) {
# Try the proper way with array parameters
$Uri = "${BaseUri}?statuses[]=triggered&statuses[]=acknowledged&limit=100"
Write-Verbose "Trying with status parameters: $Uri"
}
else {
# Get all incidents including resolved
$Uri = "${BaseUri}?limit=100"
}
Write-Verbose "Fetching incidents from: $Uri"
$FilteredIncidents = $null
try {
$Response = Invoke-RestMethod -Uri $Uri -Method Get -Headers $Headers
Write-Host "Retrieved $($Response.incidents.Count) incidents from API" -ForegroundColor Gray
# If we used status filters in the URL, use the results directly
if (-not $IncludeResolved) {
$FilteredIncidents = $Response.incidents
Write-Host "Active incidents from API: $($FilteredIncidents.Count)" -ForegroundColor Gray
}
}
catch {
# If status parameter fails, fall back to getting all and filtering
Write-Verbose "Status parameter failed, falling back to fetch all and filter locally"
$Uri = "${BaseUri}?limit=100"
$Response = Invoke-RestMethod -Uri $Uri -Method Get -Headers $Headers
Write-Host "Retrieved $($Response.incidents.Count) incidents (fallback method)" -ForegroundColor Gray
}
# Apply status filter locally if we haven't already
if ($null -eq $FilteredIncidents) {
if (-not $IncludeResolved) {
$FilteredIncidents = $Response.incidents | Where-Object {
$_.status -eq 'triggered' -or $_.status -eq 'acknowledged'
}
Write-Host "Active incidents after local filtering: $($FilteredIncidents.Count)" -ForegroundColor Gray
# Debug: Show status values we're seeing
$uniqueStatuses = $Response.incidents | Select-Object -ExpandProperty status -Unique
Write-Verbose "Unique status values found: $($uniqueStatuses -join ', ')"
}
else {
$FilteredIncidents = $Response.incidents
}
}
# Show all incidents with their actual titles
if ($FilteredIncidents.Count -gt 0) {
Write-Host "`nShowing all available incidents:" -ForegroundColor Cyan
Write-Host "ID | Status | Title" -ForegroundColor Gray
Write-Host "----------- | ------------ | -----" -ForegroundColor Gray
$FilteredIncidents | ForEach-Object {
$statusColor = switch ($_.status) {
'triggered' { 'Red' }
'acknowledged' { 'Yellow' }
'resolved' { 'DarkGray' }
default { 'Gray' }
}
$titleDisplay = if ($_.title.Length -gt 60) {
$_.title.Substring(0, 57) + "..."
} else {
$_.title
}
Write-Host "$($_.incident_number.ToString().PadRight(11)) | " -NoNewline
Write-Host "$($_.status.PadRight(12))" -ForegroundColor $statusColor -NoNewline
Write-Host " | $titleDisplay"
}
}
# Filter by title if provided
if ($IncidentTitle) {
$MatchingIncidents = $FilteredIncidents | Where-Object {
$_.title -like "*$IncidentTitle*"
}
if ($MatchingIncidents.Count -eq 0) {
Write-Warning "`nNo incidents found with '$IncidentTitle' in the title"
Write-Host "Remember: Search only works on incident titles, not body/description content" -ForegroundColor Yellow
# Suggest using incident number instead
Write-Host "`nTip: You can use the incident ID directly. For example:" -ForegroundColor Cyan
Write-Host " -IncidentId 'P1234567'" -ForegroundColor Gray
return $null
}
elseif ($MatchingIncidents.Count -eq 1) {
$Incident = $MatchingIncidents[0]
Write-Host "`n✓ Found matching incident:" -ForegroundColor Green
Write-Host " ID: $($Incident.id)" -ForegroundColor Green
Write-Host " Title: $($Incident.title)" -ForegroundColor Green
Write-Host " Status: $($Incident.status)" -ForegroundColor Green
return $Incident.id
}
else {
Write-Host "`nMultiple incidents found matching '$IncidentTitle':" -ForegroundColor Yellow
$MatchingIncidents | ForEach-Object {
Write-Host " $($_.id) - $($_.title) [$($_.status)]" -ForegroundColor Cyan
}
# Return the most recent one
$MostRecent = $MatchingIncidents | Sort-Object created_at -Descending | Select-Object -First 1
Write-Host "`nUsing most recent: $($MostRecent.id)" -ForegroundColor Green
return $MostRecent.id
}
}
else {
Write-Host "`nNo search term provided. Please specify an incident ID from the list above." -ForegroundColor Yellow
return $null
}
}
catch {
Write-Error "Failed to search for incidents: $($_.Exception.Message)"
if ($_.ErrorDetails.Message) {
Write-Host "Error details:" -ForegroundColor Red
Write-Host $_.ErrorDetails.Message -ForegroundColor Red
}
throw
}
}
function Get-PagerDutyIncidentInfo {
param(
[string]$ApiToken,
[string]$IncidentId
)
$Uri = "https://api.pagerduty.com/incidents/$IncidentId"
$Headers = @{
"Authorization" = "Token token=$ApiToken"
"Accept" = "application/vnd.pagerduty+json;version=2"
}
try {
$Response = Invoke-RestMethod -Uri $Uri -Method Get -Headers $Headers
return $Response.incident
}
catch {
Write-Error "Failed to get incident info: $($_.Exception.Message)"
return $null
}
}
# Main
Write-Host "`n=== PagerDuty Note Addition Script ===" -ForegroundColor Cyan
Write-Host "User Email: $UserEmail" -ForegroundColor Gray
# Test API token
if (-not (Test-PagerDutyApiToken -ApiToken $ApiToken)) {
Write-Error "API token validation failed. Please check your token."
exit 1
}
try {
# Determine the incident ID using various methods
$ActualIncidentId = $IncidentId
if ($ListIncidents) {
Write-Host "`nListing incidents..." -ForegroundColor Cyan
$null = Find-PagerDutyIncident -ApiToken $ApiToken -IncludeResolved:$IncludeResolved
Write-Host "`nUse one of the incident IDs above with -IncidentId parameter" -ForegroundColor Yellow
exit 0
}
if ($FindIncidentByDedupKey -and $DedupKey) {
Write-Host "`nFinding incident by dedup key..." -ForegroundColor Cyan
$ActualIncidentId = Find-PagerDutyIncidentByDedupKey -ApiToken $ApiToken -DedupKey $DedupKey
if (-not $ActualIncidentId) {
Write-Error "Could not find incident with dedup key: '$DedupKey'"
exit 1
}
}
elseif ($FindIncidentByTitle -and $IncidentTitle) {
Write-Host "`nFinding incident by title..." -ForegroundColor Cyan
$ActualIncidentId = Find-PagerDutyIncident -ApiToken $ApiToken -IncidentTitle $IncidentTitle -IncludeResolved:$IncludeResolved
if (-not $ActualIncidentId) {
Write-Error "Could not find incident matching title: '$IncidentTitle'"
exit 1
}
}
elseif (-not $ActualIncidentId) {
Write-Error "Must provide either -IncidentId, -FindIncidentByTitle with -IncidentTitle, -FindIncidentByDedupKey with -DedupKey, or -ListIncidents"
exit 1
}
# Verify incident exists
Write-Host "`nVerifying incident..." -ForegroundColor Cyan
$IncidentInfo = Get-PagerDutyIncidentInfo -ApiToken $ApiToken -IncidentId $ActualIncidentId
if (-not $IncidentInfo) {
Write-Error "Incident $ActualIncidentId not found"
exit 1
}
Write-Host "✓ Incident verified: $($IncidentInfo.title)" -ForegroundColor Green
Write-Host " Status: $($IncidentInfo.status)" -ForegroundColor Gray
Write-Host " Service: $($IncidentInfo.service.summary)" -ForegroundColor Gray
Write-Host " Created: $($IncidentInfo.created_at)" -ForegroundColor Gray
Write-Host "`nAdding note..." -ForegroundColor Cyan
$Result = Add-PagerDutyNote -ApiToken $ApiToken -IncidentId $ActualIncidentId -Note $Note -UserEmail $UserEmail
Write-Host "`n✓ Script completed successfully!" -ForegroundColor Green
return $Result
}
catch {
Write-Error "Script execution failed: $($_.Exception.Message)"
exit 1
}