Skip to content

Commit efc5be3

Browse files
Create Critical P1 Incident from Alert using GlideJsonPath - Pull5 (#2561)
* script.js Automatically create a problem record from incident volume Use case: Automatically create a problem record if a specific Configuration Item (CI) is associated with more than a certain number of incidents within a defined timeframe. Code snippet This code can be placed in a Scheduled Script Execution or an After Insert Business Rule to check new incidents * README.md * Script.js Identify the oldest active incident for each assignment group. This helps managers focus on long-running tickets that may require special attention. * README.md * script.js This example searches a JSON document for all developers listed under the specified path. * README.md * Update README.md * script.js Identify inactive users who still have unresolved incidents. This helps with offboarding processes and ensures incidents aren't left unattended. * README.md * Update script.js * Delete Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/README.md * Delete Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/script.js * Delete Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/README.md * Delete Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/script.js * Delete Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md * Delete Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js * Create script.js * README.md * Delete Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/README.md * Delete Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/script.js * script.js Create Critical P1 Incident from Alert * README.md * Delete Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/README.md * Delete Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/script.js
1 parent e2360c1 commit efc5be3

File tree

2 files changed

+95
-0
lines changed
  • Core ServiceNow APIs/GlideJsonPath/Create Critical P1 Incident from Alert using GlideJsonPath

2 files changed

+95
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
Create Critical P1 Incident from Alert This script provides the server-side logic for a Scripted REST API endpoint in ServiceNow.
2+
It allows external monitoring tools to send alert data via a POST request, which is then used to automatically create a high-priority, P1 incident.
3+
Overview The API endpoint performs the following actions: Receives a JSON Payload: Accepts a POST request containing a JSON payload with alert details (severity, description, source, CI). Parses Data: Uses the GlideJsonPath API to efficiently extract the necessary alert information from the JSON body. Validates Request: Ensures that the severity is CRITICAL and the description is present. It sends an appropriate error response for invalid or incomplete data. Creates Incident: If the data is valid, it creates a new incident record in the incident table. Sets Incident Fields: Automatically populates the incident's short_description, description, source, and sets the impact, urgency, and priority to 1 - High/Critical. Associates CI: If a ci_sys_id is provided in the payload, it links the incident to the correct Configuration Item. Logs Activity: Logs the successful creation of the incident in the system log for tracking and auditing purposes. Responds to Sender: Sends a JSON response back to the external system, confirming success or failure and providing the new incident's number and sys_id. Expected JSON payload The external system should send a POST request with a JSON body structured like this: json { "alert": { "severity": "CRITICAL", "description": "The primary database server is down. Users are unable to log in.", "source": "Dynatrace", "configuration_item": "DB_Server_01", "ci_sys_id": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6" } } Use code with caution.
4+
5+
Installation As a Scripted REST API Resource Create the Scripted REST API: Navigate to System Web Services > Scripted REST APIs.
6+
Click New and fill in the details: Name: CriticalAlertIncident API ID: critical_alert_incident Save the record.
7+
8+
Create the Resource: On the Resources related list of the API record, click New.
9+
Name: PostCriticalIncident HTTP Method: POST Relative Path: / Copy and paste the provided script into the Script field. Configure Security: Ensure appropriate authentication is configured for the API, such as OAuth or Basic Auth, to secure the endpoint. Customization Change Priority/Impact: Modify the grIncident.setValue() lines to set different priority or impact levels based on the payload (e.g., if (severity == 'MAJOR') { grIncident.setValue('priority', 2); }). Add Additional Fields: Extend the script to parse and set other incident fields, such as assignment_group, caller_id, or category, based on data from the incoming payload. Enrich Incident Data: Perform a lookup on the CI to fetch additional information and add it to the incident description or other fields. Handle Different Severity Levels: Add if/else logic to handle different severity values (e.g., MAJOR, MINOR) from the source system, creating incidents with different priorities accordingly.
10+
11+
Dependencies This script requires the GlideJsonPath API, which is available in Jakarta and later releases.
12+
The API endpoint must be secured with appropriate authentication to prevent unauthorized access.
13+
14+
Considerations
15+
16+
Security: This API endpoint is a powerful integration point.
17+
Ensure that it is properly secured and that only trusted sources are allowed to create incidents. Error Handling: The script includes robust error handling for common failures (missing data, insertion failure) but should be extended to handle specific use cases as needed. Testing: Thoroughly test the endpoint with a variety of payloads, including valid data, missing data, and invalid data, to ensure it behaves as expected.
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
try {
2+
// Get the JSON payload from the request body.
3+
var requestBody = request.body.dataString;
4+
5+
// Use GlideJsonPath to parse the JSON payload efficiently.
6+
var gjp = new GlideJsonPath(requestBody);
7+
8+
// Extract key information from the JSON payload.
9+
var severity = gjp.read("$.alert.severity");
10+
var shortDescription = gjp.read("$.alert.description");
11+
var source = gjp.read("$.alert.source");
12+
var ciName = gjp.read("$.alert.configuration_item");
13+
var ciSysId = gjp.read("$.alert.ci_sys_id");
14+
15+
// Validate that mandatory fields are present.
16+
if (!shortDescription || severity != 'CRITICAL') {
17+
response.setStatus(400); // Bad Request
18+
response.setBody({
19+
"status": "error",
20+
"message": "Missing mandatory alert information or severity is not critical."
21+
});
22+
return;
23+
}
24+
25+
// Use GlideRecordSecure for added security and ACL enforcement.
26+
var grIncident = new GlideRecordSecure('incident');
27+
grIncident.initialize();
28+
29+
// Set incident field values from the JSON payload.
30+
grIncident.setValue('short_description', 'INTEGRATION ALERT: [' + source + '] ' + shortDescription);
31+
grIncident.setValue('description', 'A critical alert has been received from ' + source + '.\n\nAlert Details:\nSeverity: ' + severity + '\nDescription: ' + shortDescription + '\nCI Name: ' + ciName);
32+
grIncident.setValue('source', source);
33+
grIncident.setValue('impact', 1); // Set Impact to '1 - High'
34+
grIncident.setValue('urgency', 1); // Set Urgency to '1 - High'
35+
grIncident.setValue('priority', 1); // Set Priority to '1 - Critical'
36+
37+
// If a CI sys_id is provided, set the Configuration Item.
38+
if (ciSysId) {
39+
grIncident.setValue('cmdb_ci', ciSysId);
40+
}
41+
42+
// Insert the new incident record and store its sys_id.
43+
var newIncidentSysId = grIncident.insert();
44+
45+
if (newIncidentSysId) {
46+
// Get the incident number for the successful response.
47+
var incNumber = grIncident.getRecord().getValue('number');
48+
49+
// Log the successful incident creation.
50+
gs.info('Critical P1 incident ' + incNumber + ' created from alert from ' + source);
51+
52+
// Prepare the success response.
53+
var responseBody = {
54+
"status": "success",
55+
"message": "Critical incident created successfully.",
56+
"incident_number": incNumber,
57+
"incident_sys_id": newIncidentSysId
58+
};
59+
response.setStatus(201); // Created
60+
response.setBody(responseBody);
61+
} else {
62+
// Handle database insertion failure.
63+
response.setStatus(500); // Internal Server Error
64+
response.setBody({
65+
"status": "error",
66+
"message": "Failed to create the incident record."
67+
});
68+
}
69+
70+
} catch (ex) {
71+
// Handle any exceptions during processing.
72+
gs.error('An error occurred during critical alert incident creation: ' + ex);
73+
response.setStatus(500);
74+
response.setBody({
75+
"status": "error",
76+
"message": "An internal server error occurred."
77+
});
78+
}

0 commit comments

Comments
 (0)