From 2da9254ab1a15fbaf6851c7a84f9b46c81711023 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 01:17:01 +0530 Subject: [PATCH 01/24] 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 --- .../script.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/script.js diff --git a/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/script.js b/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/script.js new file mode 100644 index 0000000000..dcec063918 --- /dev/null +++ b/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/script.js @@ -0,0 +1,13 @@ +var incidentCheck = new GlideAggregate('incident'); + incidentCheck.addQuery('cmdb_ci', current.cmdb_ci); // Or any specific CI + incidentCheck.addQuery('opened_at', '>', 'javascript:gs.minutesAgoStart(60)'); + incidentCheck.addAggregate('COUNT'); + incidentCheck.query(); + + if (incidentCheck.next() && parseInt(incidentCheck.getAggregate('COUNT')) > 5) { + var problem = new GlideRecord('problem'); + problem.initialize(); + problem.short_description = 'Multiple incidents reported for CI: ' + current.cmdb_ci.getDisplayValue(); + problem.cmdb_ci = current.cmdb_ci; + problem.insert(); + } From c9315ec134f33bba9be4a53522c89b6c36965d1d Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 01:18:16 +0530 Subject: [PATCH 02/24] README.md --- .../README.md | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/README.md diff --git a/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/README.md b/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/README.md new file mode 100644 index 0000000000..6f7afc5eac --- /dev/null +++ b/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/README.md @@ -0,0 +1,37 @@ +Key features +Automatic problem creation: The script uses a GlideAggregate query to count the number of incidents opened for a specific CI. +Time-based threshold: Problems are only created if more than five incidents are opened within a 60-minute window. +Targeted incidents: The script focuses on incidents related to the same CI, making it effective for identifying recurring infrastructure issues. +Customizable conditions: The number of incidents and the time frame are easily configurable within the script. +Efficient performance: The use of GlideAggregate ensures the database is queried efficiently, minimizing performance impact. + +How it works +The script is designed to be executed as a server-side script, typically within a Business Rule. When an incident is inserted or updated, the script performs the following actions: +Queries incidents: It executes a GlideAggregate query on the incident table. +Sets conditions: The query is filtered to count all incidents that meet the following conditions: +Same CI: The incident's cmdb_ci matches the cmdb_ci of the current record. +Within the last hour: The opened_at time is within the last 60 minutes. +Evaluates count: After the query is run, the script checks if the count of matching incidents exceeds the threshold (in this case, 5). +Creates problem: If the threshold is exceeded, a new problem record is initialized. +The short_description is automatically populated with a descriptive message. +The cmdb_ci is linked to the new problem record. +The new record is then inserted into the database. +Implementation steps +Create a Business Rule: +Navigate to System Definition > Business Rules. +Click New. +Configure the Business Rule: +Name: Auto Create Problem from Multiple Incidents +Table: Incident [incident] +Advanced: true +When to run: Select after and check the Insert and Update checkboxes. This ensures the script runs after an incident has been saved. +Filter conditions: Optionally, you can add conditions to limit when the script runs (e.g., cmdb_ci is not empty). +Add the script: +Navigate to the Advanced tab. +Copy and paste the script into the Script field. +Customize (optional): +Number of incidents: Change the > 5 value to adjust the threshold. +Time frame: Adjust the gs.minutesAgoStart(60) value to change the time window. +Other conditions: If you need to check for specific incident statuses or categories, add more addQuery lines to the GlideAggregate call. +Save the Business Rule. +Customization examples From 5d17de8e7e9d72872248c773dba953dce931a82a Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 01:30:06 +0530 Subject: [PATCH 03/24] Script.js Identify the oldest active incident for each assignment group. This helps managers focus on long-running tickets that may require special attention. --- .../script.js | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/script.js diff --git a/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/script.js b/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/script.js new file mode 100644 index 0000000000..4aabd461b1 --- /dev/null +++ b/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/script.js @@ -0,0 +1,11 @@ +var ga = new GlideAggregate('incident'); + ga.addActiveQuery(); + ga.addAggregate('MIN', 'opened_at'); + ga.groupBy('assignment_group'); + ga.query(); + + while (ga.next()) { + var group = ga.assignment_group.getDisplayValue(); + var oldestIncidentDate = ga.getAggregate('MIN', 'opened_at'); + gs.info("Oldest open incident for " + group + " was created on: " + oldestIncidentDate); + } From c8c2e0642d42fc32b0393416020c9305fac204cd Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 01:32:57 +0530 Subject: [PATCH 04/24] README.md --- .../README.md | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/README.md diff --git a/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/README.md b/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/README.md new file mode 100644 index 0000000000..722a45ac02 --- /dev/null +++ b/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/README.md @@ -0,0 +1,92 @@ +ServiceNow Script: Find Oldest Open Incidents per Group +This script leverages GlideAggregate to efficiently find the oldest active incident for each assignment group. This is a powerful tool for monitoring and reporting on potential service level agreement (SLA) risks and improving incident management processes. +Overview +The script performs the following actions: +Initializes GlideAggregate: Creates an aggregate query on the incident table. +Filters Active Incidents: Uses addActiveQuery() to restrict the search to only open (active) incidents. +Aggregates by Minimum Date: Finds the minimum (MIN) opened_at date, which represents the oldest record. +Groups by Assignment Group: Groups the results by the assignment_group to get a separate result for each team. +Iterates and Logs: Loops through the query results and logs the assignment group and the opening date of its oldest open incident. +How to use +This script is intended to be used in a server-side context within a ServiceNow instance. Common use cases include: +Scheduled Job: Run this script on a regular schedule (e.g., daily) to generate a report on aging incidents. +Script Include: Incorporate the logic into a reusable function within a Script Include, allowing other scripts to call it. +Fix Script: Execute the script as a one-off task to perform an analysis. +Script +javascript +(function findOldestIncidents() { + var ga = new GlideAggregate('incident'); + ga.addActiveQuery(); + ga.addAggregate('MIN', 'opened_at'); + ga.groupBy('assignment_group'); + ga.query(); + + while (ga.next()) { + var group = ga.assignment_group.getDisplayValue(); + var oldestIncidentDate = ga.getAggregate('MIN', 'opened_at'); + gs.info("Oldest open incident for " + group + " was created on: " + oldestIncidentDate); + } +})(); +Use code with caution. + +Installation +As a Scheduled Job +Navigate to System Definition > Scheduled Jobs. +Click New and select Automatically run a script of your choosing. +Name the job (e.g., Find Oldest Open Incidents). +Set your desired frequency and time. +Paste the script into the Run this script field. +Save and activate the job. +As a Script Include +Navigate to System Definition > Script Includes. +Click New. +Name it (e.g., IncidentHelper). +API Name: global.IncidentHelper +Script: +javascript +var IncidentHelper = Class.create(); +IncidentHelper.prototype = { + initialize: function() { + }, + + findOldestIncidents: function() { + var ga = new GlideAggregate('incident'); + ga.addActiveQuery(); + ga.addAggregate('MIN', 'opened_at'); + ga.groupBy('assignment_group'); + ga.query(); + + var results = []; + while (ga.next()) { + var group = ga.assignment_group.getDisplayValue(); + var oldestIncidentDate = ga.getAggregate('MIN', 'opened_at'); + results.push({ + group: group, + oldestIncidentDate: oldestIncidentDate + }); + } + return results; + }, + + type: 'IncidentHelper' +}; +Use code with caution. + +You can then call this function from other scripts. For example: +javascript +var helper = new IncidentHelper(); +var incidents = helper.findOldestIncidents(); +for (var i = 0; i < incidents.length; i++) { + gs.info("Oldest open incident for " + incidents[i].group + " was created on: " + incidents[i].oldestIncidentDate); +} +Use code with caution. + +Customization +Change the output: Modify the gs.info() line to instead write to a custom log, send an email, or create a report. +Refine the query: Add more addQuery() statements to filter incidents by other criteria, such as priority or category. +Change the aggregate: Use MAX instead of MIN to find the newest incident in each group. +Get incident details: To get the actual incident record (e.g., its number), you would need to perform a secondary GlideRecord query based on the aggregated data. +Dependencies +This script uses standard ServiceNow APIs (GlideAggregate, gs). No external libraries are required. +Support +For any questions or issues, please open an issue in this repository. From 14244d8b6541501ee7a8ae74854231812e3550a7 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 01:47:20 +0530 Subject: [PATCH 05/24] script.js This example searches a JSON document for all developers listed under the specified path. --- .../GlideJsonPath/GlideJsonPath Reader Example/script.js | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js diff --git a/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js b/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js new file mode 100644 index 0000000000..ddfd540a46 --- /dev/null +++ b/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js @@ -0,0 +1,2 @@ +var v = new GlideJsonPath('{"lib":{"jsonpath":{"cricket":{"name":"India","players":["Rohit","Dhoni","Kholi"]}}}}'); +var l = v.read("$['lib']['jsonpath']['cricket']['players'][*]"); From 45c645dde25e769504a7857ba941cc06d67d3d8c Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 01:51:09 +0530 Subject: [PATCH 06/24] README.md --- .../GlideJsonPath Reader Example/README.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md diff --git a/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md b/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md new file mode 100644 index 0000000000..1b05e5aa11 --- /dev/null +++ b/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md @@ -0,0 +1,42 @@ +Parse JSON with GlideJsonPath +This script demonstrates how to use the GlideJsonPath API in ServiceNow to parse a complex JSON string and extract specific data. In this example, it efficiently retrieves an array of player names from a nested JSON structure representing cricket team information. +Overview +The script performs the following actions: +Initializes GlideJsonPath: A new instance of GlideJsonPath is created, passing the target JSON string as a parameter. +Reads data with JSONPath: The read() method is called with a JSONPath expression to extract the desired data. The expression "$['lib']['jsonpath']['cricket']['players'][*]" navigates to the array of players: +$ represents the root of the JSON object. +['lib'], ['jsonpath'], and ['cricket'] use bracket notation to traverse the nested object structure. +['players'] accesses the array of player names. +[*] is a wildcard that returns all elements in the players array. +Stores the result: The extracted array of player names is stored in the l variable. +Use case +This script is useful in scenarios where you need to parse JSON data returned from a REST API call or an integration. By using GlideJsonPath, you can quickly and efficiently extract specific pieces of information without writing complex code to traverse the entire JSON object manually. +How to use +This script is intended for use in a server-side context within ServiceNow, such as a Script Include or Business Rule. +Example: Script Include +javascript +var CricketJsonParser = Class.create(); +CricketJsonParser.prototype = { + initialize: function() { + }, + + getPlayers: function() { + var jsonString = '{"lib":{"jsonpath":{"cricket":{"name":"India","players":["Rohit","Dhoni","Kholi"]}}}}'; + var v = new GlideJsonPath(jsonString); + var playerNames = v.read("$['lib']['jsonpath']['cricket']['players'][*]"); + + // At this point, `playerNames` is a JavaObject array. + // You can log it or process it further. + gs.info("Extracted players: " + JSON.stringify(playerNames)); + + return playerNames; + }, + + type: 'CricketJsonParser' +}; +Use code with caution. + +Customization +JSON Data: Replace the hardcoded jsonString with the variable that holds your JSON data (e.g., the body of a REST response). +JSONPath Expression: Modify the JSONPath expression in the read() method to extract different data from your JSON structure. +Result Handling: The read() function returns a JavaObject array, not a standard JavaScript array. If you need to use JavaScript array methods (like forEach), you may need to convert it. From 3edf0bcc88e628349a36d23e68c7cb30efb057e9 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 01:53:44 +0530 Subject: [PATCH 07/24] Update README.md --- .../GlideJsonPath/GlideJsonPath Reader Example/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md b/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md index 1b05e5aa11..8106a2c022 100644 --- a/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md +++ b/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md @@ -1,5 +1,6 @@ Parse JSON with GlideJsonPath This script demonstrates how to use the GlideJsonPath API in ServiceNow to parse a complex JSON string and extract specific data. In this example, it efficiently retrieves an array of player names from a nested JSON structure representing cricket team information. + Overview The script performs the following actions: Initializes GlideJsonPath: A new instance of GlideJsonPath is created, passing the target JSON string as a parameter. From fa78c36b29ca1af659fe6c8a2d8406b2b3ff63b5 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 02:01:43 +0530 Subject: [PATCH 08/24] script.js Identify inactive users who still have unresolved incidents. This helps with offboarding processes and ensures incidents aren't left unattended. --- .../script.js | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/script.js diff --git a/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/script.js b/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/script.js new file mode 100644 index 0000000000..3699d502ce --- /dev/null +++ b/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/script.js @@ -0,0 +1,11 @@ +var ga = new GlideAggregate('incident'); + ga.addQuery('active', true); + ga.addQuery('assigned_to.active', false); + ga.addAggregate('COUNT', 'assigned_to'); + ga.query(); + + while (ga.next()) { + var inactiveUser = ga.assigned_to.getDisplayValue(); + var taskCount = ga.getAggregate('COUNT', 'assigned_to'); + gs.info("Inactive user " + inactiveUser + " has " + IncidentCount + " active tasks."); + } From a6e23bd58ca5f781dffb723dd0d71840d90ec8e0 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 02:03:16 +0530 Subject: [PATCH 09/24] README.md --- .../README.md | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/README.md diff --git a/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/README.md b/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/README.md new file mode 100644 index 0000000000..a51d9e2ead --- /dev/null +++ b/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/README.md @@ -0,0 +1,46 @@ +Count Active Incidents Assigned to Inactive Users +This script uses GlideAggregate to efficiently count the number of active incidents assigned to inactive users. This is a crucial task for maintaining data hygiene and preventing incidents from being stalled due to inactive assignees. +Overview +The script performs the following actions: +Initializes GlideAggregate: Creates an aggregate query on the incident table. +Filters Records: Uses addQuery() to restrict the search to incidents that are both active (true) and assigned to a user whose active status is false. This filter uses a "dot-walk" on the assigned_to field to check the user's active status directly within the query. +Aggregates by Count: Uses addAggregate() to count the number of incidents, grouping the results by assigned_to user. +Executes and Logs: Runs the query, then loops through the results. For each inactive user found, it logs their name and the number of active incidents assigned to them. +Use case +This script is essential for regular cleanup and maintenance. It can be used in: +Scheduled Job: Automatically run the script daily or weekly to monitor for and report on incidents assigned to inactive users. +Fix Script: Perform a one-off run to identify and log all current incidents that need reassignment. +Reporting: The output from this script can be used to build a report for managers to track and reassign incidents promptly. +Script +javascript +var ga = new GlideAggregate('incident'); +ga.addQuery('active', true); +ga.addQuery('assigned_to.active', false); +ga.addAggregate('COUNT', 'assigned_to'); +ga.query(); + +while (ga.next()) { + var inactiveUser = ga.assigned_to.getDisplayValue(); + var taskCount = ga.getAggregate('COUNT', 'assigned_to'); + gs.info("Inactive user " + inactiveUser + " has " + taskCount + " active incidents."); +} +Use code with caution. + +Installation +As a Scheduled Job +Navigate to System Definition > Scheduled Jobs. +Click New and select Automatically run a script of your choosing. +Name the job (e.g., Find Incidents Assigned to Inactive Users). +Set your desired frequency and time. +Paste the script into the Run this script field. +Save and activate the job. +As a Fix Script +Navigate to System Definition > Fix Scripts. +Click New. +Name it (e.g., Find Active Incidents with Inactive Assignee). +Paste the script into the Script field. +Run the script to see the results in the System Log. +Customization +Targeted tables: Change the table name from incident to task or any other table with an assigned_to field to check for active records assigned to inactive users. +Automated reassignment: Extend the script to automatically reassign the incidents to a group or another user. This is a common practice to ensure that tickets do not get stuck in the queue. +Email notification: Instead of logging the information, modify the script to send an email notification to the group manager or another stakeholder with the list of incidents needing attention. From 484bcdda3d6c1ebf13870430d9aabd456a2ea3bf Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 02:08:11 +0530 Subject: [PATCH 10/24] Update script.js --- .../GlideJsonPath/GlideJsonPath Reader Example/script.js | 1 + 1 file changed, 1 insertion(+) diff --git a/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js b/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js index ddfd540a46..063812aad7 100644 --- a/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js +++ b/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js @@ -1,2 +1,3 @@ var v = new GlideJsonPath('{"lib":{"jsonpath":{"cricket":{"name":"India","players":["Rohit","Dhoni","Kholi"]}}}}'); var l = v.read("$['lib']['jsonpath']['cricket']['players'][*]"); + From 12f9ba99ae96f9b0877442212b7e43af784f2e5c Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 09:40:15 +0530 Subject: [PATCH 11/24] Delete Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/README.md --- .../README.md | 46 ------------------- 1 file changed, 46 deletions(-) delete mode 100644 Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/README.md diff --git a/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/README.md b/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/README.md deleted file mode 100644 index a51d9e2ead..0000000000 --- a/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/README.md +++ /dev/null @@ -1,46 +0,0 @@ -Count Active Incidents Assigned to Inactive Users -This script uses GlideAggregate to efficiently count the number of active incidents assigned to inactive users. This is a crucial task for maintaining data hygiene and preventing incidents from being stalled due to inactive assignees. -Overview -The script performs the following actions: -Initializes GlideAggregate: Creates an aggregate query on the incident table. -Filters Records: Uses addQuery() to restrict the search to incidents that are both active (true) and assigned to a user whose active status is false. This filter uses a "dot-walk" on the assigned_to field to check the user's active status directly within the query. -Aggregates by Count: Uses addAggregate() to count the number of incidents, grouping the results by assigned_to user. -Executes and Logs: Runs the query, then loops through the results. For each inactive user found, it logs their name and the number of active incidents assigned to them. -Use case -This script is essential for regular cleanup and maintenance. It can be used in: -Scheduled Job: Automatically run the script daily or weekly to monitor for and report on incidents assigned to inactive users. -Fix Script: Perform a one-off run to identify and log all current incidents that need reassignment. -Reporting: The output from this script can be used to build a report for managers to track and reassign incidents promptly. -Script -javascript -var ga = new GlideAggregate('incident'); -ga.addQuery('active', true); -ga.addQuery('assigned_to.active', false); -ga.addAggregate('COUNT', 'assigned_to'); -ga.query(); - -while (ga.next()) { - var inactiveUser = ga.assigned_to.getDisplayValue(); - var taskCount = ga.getAggregate('COUNT', 'assigned_to'); - gs.info("Inactive user " + inactiveUser + " has " + taskCount + " active incidents."); -} -Use code with caution. - -Installation -As a Scheduled Job -Navigate to System Definition > Scheduled Jobs. -Click New and select Automatically run a script of your choosing. -Name the job (e.g., Find Incidents Assigned to Inactive Users). -Set your desired frequency and time. -Paste the script into the Run this script field. -Save and activate the job. -As a Fix Script -Navigate to System Definition > Fix Scripts. -Click New. -Name it (e.g., Find Active Incidents with Inactive Assignee). -Paste the script into the Script field. -Run the script to see the results in the System Log. -Customization -Targeted tables: Change the table name from incident to task or any other table with an assigned_to field to check for active records assigned to inactive users. -Automated reassignment: Extend the script to automatically reassign the incidents to a group or another user. This is a common practice to ensure that tickets do not get stuck in the queue. -Email notification: Instead of logging the information, modify the script to send an email notification to the group manager or another stakeholder with the list of incidents needing attention. From 23f8bb31260f98bbf604ccc5109e9fb3f9fe96a5 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 09:40:42 +0530 Subject: [PATCH 12/24] Delete Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/script.js --- .../script.js | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/script.js diff --git a/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/script.js b/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/script.js deleted file mode 100644 index 3699d502ce..0000000000 --- a/Core ServiceNow APIs/GlideAggregate/Count Inactive Users with Active incidents/script.js +++ /dev/null @@ -1,11 +0,0 @@ -var ga = new GlideAggregate('incident'); - ga.addQuery('active', true); - ga.addQuery('assigned_to.active', false); - ga.addAggregate('COUNT', 'assigned_to'); - ga.query(); - - while (ga.next()) { - var inactiveUser = ga.assigned_to.getDisplayValue(); - var taskCount = ga.getAggregate('COUNT', 'assigned_to'); - gs.info("Inactive user " + inactiveUser + " has " + IncidentCount + " active tasks."); - } From 75d8c0b78e00dfe7d871c15dd159e6fbf6798b79 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 09:41:46 +0530 Subject: [PATCH 13/24] Delete Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/README.md --- .../README.md | 92 ------------------- 1 file changed, 92 deletions(-) delete mode 100644 Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/README.md diff --git a/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/README.md b/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/README.md deleted file mode 100644 index 722a45ac02..0000000000 --- a/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/README.md +++ /dev/null @@ -1,92 +0,0 @@ -ServiceNow Script: Find Oldest Open Incidents per Group -This script leverages GlideAggregate to efficiently find the oldest active incident for each assignment group. This is a powerful tool for monitoring and reporting on potential service level agreement (SLA) risks and improving incident management processes. -Overview -The script performs the following actions: -Initializes GlideAggregate: Creates an aggregate query on the incident table. -Filters Active Incidents: Uses addActiveQuery() to restrict the search to only open (active) incidents. -Aggregates by Minimum Date: Finds the minimum (MIN) opened_at date, which represents the oldest record. -Groups by Assignment Group: Groups the results by the assignment_group to get a separate result for each team. -Iterates and Logs: Loops through the query results and logs the assignment group and the opening date of its oldest open incident. -How to use -This script is intended to be used in a server-side context within a ServiceNow instance. Common use cases include: -Scheduled Job: Run this script on a regular schedule (e.g., daily) to generate a report on aging incidents. -Script Include: Incorporate the logic into a reusable function within a Script Include, allowing other scripts to call it. -Fix Script: Execute the script as a one-off task to perform an analysis. -Script -javascript -(function findOldestIncidents() { - var ga = new GlideAggregate('incident'); - ga.addActiveQuery(); - ga.addAggregate('MIN', 'opened_at'); - ga.groupBy('assignment_group'); - ga.query(); - - while (ga.next()) { - var group = ga.assignment_group.getDisplayValue(); - var oldestIncidentDate = ga.getAggregate('MIN', 'opened_at'); - gs.info("Oldest open incident for " + group + " was created on: " + oldestIncidentDate); - } -})(); -Use code with caution. - -Installation -As a Scheduled Job -Navigate to System Definition > Scheduled Jobs. -Click New and select Automatically run a script of your choosing. -Name the job (e.g., Find Oldest Open Incidents). -Set your desired frequency and time. -Paste the script into the Run this script field. -Save and activate the job. -As a Script Include -Navigate to System Definition > Script Includes. -Click New. -Name it (e.g., IncidentHelper). -API Name: global.IncidentHelper -Script: -javascript -var IncidentHelper = Class.create(); -IncidentHelper.prototype = { - initialize: function() { - }, - - findOldestIncidents: function() { - var ga = new GlideAggregate('incident'); - ga.addActiveQuery(); - ga.addAggregate('MIN', 'opened_at'); - ga.groupBy('assignment_group'); - ga.query(); - - var results = []; - while (ga.next()) { - var group = ga.assignment_group.getDisplayValue(); - var oldestIncidentDate = ga.getAggregate('MIN', 'opened_at'); - results.push({ - group: group, - oldestIncidentDate: oldestIncidentDate - }); - } - return results; - }, - - type: 'IncidentHelper' -}; -Use code with caution. - -You can then call this function from other scripts. For example: -javascript -var helper = new IncidentHelper(); -var incidents = helper.findOldestIncidents(); -for (var i = 0; i < incidents.length; i++) { - gs.info("Oldest open incident for " + incidents[i].group + " was created on: " + incidents[i].oldestIncidentDate); -} -Use code with caution. - -Customization -Change the output: Modify the gs.info() line to instead write to a custom log, send an email, or create a report. -Refine the query: Add more addQuery() statements to filter incidents by other criteria, such as priority or category. -Change the aggregate: Use MAX instead of MIN to find the newest incident in each group. -Get incident details: To get the actual incident record (e.g., its number), you would need to perform a secondary GlideRecord query based on the aggregated data. -Dependencies -This script uses standard ServiceNow APIs (GlideAggregate, gs). No external libraries are required. -Support -For any questions or issues, please open an issue in this repository. From 4f13513309152f52f807ad918b18ad9cd089bf94 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 09:42:00 +0530 Subject: [PATCH 14/24] Delete Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/script.js --- .../script.js | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/script.js diff --git a/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/script.js b/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/script.js deleted file mode 100644 index 4aabd461b1..0000000000 --- a/Core ServiceNow APIs/GlideAggregate/Find oldest Incident based Assignment Groups/script.js +++ /dev/null @@ -1,11 +0,0 @@ -var ga = new GlideAggregate('incident'); - ga.addActiveQuery(); - ga.addAggregate('MIN', 'opened_at'); - ga.groupBy('assignment_group'); - ga.query(); - - while (ga.next()) { - var group = ga.assignment_group.getDisplayValue(); - var oldestIncidentDate = ga.getAggregate('MIN', 'opened_at'); - gs.info("Oldest open incident for " + group + " was created on: " + oldestIncidentDate); - } From 5328ddaee5e89cd18b04b5b2f8c22b561303b1c4 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 09:42:25 +0530 Subject: [PATCH 15/24] Delete Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md --- .../GlideJsonPath Reader Example/README.md | 43 ------------------- 1 file changed, 43 deletions(-) delete mode 100644 Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md diff --git a/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md b/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md deleted file mode 100644 index 8106a2c022..0000000000 --- a/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/README.md +++ /dev/null @@ -1,43 +0,0 @@ -Parse JSON with GlideJsonPath -This script demonstrates how to use the GlideJsonPath API in ServiceNow to parse a complex JSON string and extract specific data. In this example, it efficiently retrieves an array of player names from a nested JSON structure representing cricket team information. - -Overview -The script performs the following actions: -Initializes GlideJsonPath: A new instance of GlideJsonPath is created, passing the target JSON string as a parameter. -Reads data with JSONPath: The read() method is called with a JSONPath expression to extract the desired data. The expression "$['lib']['jsonpath']['cricket']['players'][*]" navigates to the array of players: -$ represents the root of the JSON object. -['lib'], ['jsonpath'], and ['cricket'] use bracket notation to traverse the nested object structure. -['players'] accesses the array of player names. -[*] is a wildcard that returns all elements in the players array. -Stores the result: The extracted array of player names is stored in the l variable. -Use case -This script is useful in scenarios where you need to parse JSON data returned from a REST API call or an integration. By using GlideJsonPath, you can quickly and efficiently extract specific pieces of information without writing complex code to traverse the entire JSON object manually. -How to use -This script is intended for use in a server-side context within ServiceNow, such as a Script Include or Business Rule. -Example: Script Include -javascript -var CricketJsonParser = Class.create(); -CricketJsonParser.prototype = { - initialize: function() { - }, - - getPlayers: function() { - var jsonString = '{"lib":{"jsonpath":{"cricket":{"name":"India","players":["Rohit","Dhoni","Kholi"]}}}}'; - var v = new GlideJsonPath(jsonString); - var playerNames = v.read("$['lib']['jsonpath']['cricket']['players'][*]"); - - // At this point, `playerNames` is a JavaObject array. - // You can log it or process it further. - gs.info("Extracted players: " + JSON.stringify(playerNames)); - - return playerNames; - }, - - type: 'CricketJsonParser' -}; -Use code with caution. - -Customization -JSON Data: Replace the hardcoded jsonString with the variable that holds your JSON data (e.g., the body of a REST response). -JSONPath Expression: Modify the JSONPath expression in the read() method to extract different data from your JSON structure. -Result Handling: The read() function returns a JavaObject array, not a standard JavaScript array. If you need to use JavaScript array methods (like forEach), you may need to convert it. From 6750b61a4e6fdf4846b562fe97ace4a8607eb8e8 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 09:43:01 +0530 Subject: [PATCH 16/24] Delete Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js --- .../GlideJsonPath/GlideJsonPath Reader Example/script.js | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js diff --git a/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js b/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js deleted file mode 100644 index 063812aad7..0000000000 --- a/Core ServiceNow APIs/GlideJsonPath/GlideJsonPath Reader Example/script.js +++ /dev/null @@ -1,3 +0,0 @@ -var v = new GlideJsonPath('{"lib":{"jsonpath":{"cricket":{"name":"India","players":["Rohit","Dhoni","Kholi"]}}}}'); -var l = v.read("$['lib']['jsonpath']['cricket']['players'][*]"); - From 08a689f3dbf854bf7d7431c95c8b3fe33a4263c4 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 10:56:27 +0530 Subject: [PATCH 17/24] Create script.js --- .../script.js | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/script.js diff --git a/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/script.js b/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/script.js new file mode 100644 index 0000000000..2e55276b70 --- /dev/null +++ b/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/script.js @@ -0,0 +1,78 @@ +try { + // Get the JSON payload from the request body. + var requestBody = request.body.dataString; + + // Use GlideJsonPath to parse the JSON payload efficiently. + var gjp = new GlideJsonPath(requestBody); + + // Extract key information from the JSON payload. + var severity = gjp.read("$.alert.severity"); + var shortDescription = gjp.read("$.alert.description"); + var source = gjp.read("$.alert.source"); + var ciName = gjp.read("$.alert.configuration_item"); + var ciSysId = gjp.read("$.alert.ci_sys_id"); + + // Validate that mandatory fields are present. + if (!shortDescription || severity != 'CRITICAL') { + response.setStatus(400); // Bad Request + response.setBody({ + "status": "error", + "message": "Missing mandatory alert information or severity is not critical." + }); + return; + } + + // Use GlideRecordSecure for added security and ACL enforcement. + var grIncident = new GlideRecordSecure('incident'); + grIncident.initialize(); + + // Set incident field values from the JSON payload. + grIncident.setValue('short_description', 'INTEGRATION ALERT: [' + source + '] ' + shortDescription); + grIncident.setValue('description', 'A critical alert has been received from ' + source + '.\n\nAlert Details:\nSeverity: ' + severity + '\nDescription: ' + shortDescription + '\nCI Name: ' + ciName); + grIncident.setValue('source', source); + grIncident.setValue('impact', 1); // Set Impact to '1 - High' + grIncident.setValue('urgency', 1); // Set Urgency to '1 - High' + grIncident.setValue('priority', 1); // Set Priority to '1 - Critical' + + // If a CI sys_id is provided, set the Configuration Item. + if (ciSysId) { + grIncident.setValue('cmdb_ci', ciSysId); + } + + // Insert the new incident record and store its sys_id. + var newIncidentSysId = grIncident.insert(); + + if (newIncidentSysId) { + // Get the incident number for the successful response. + var incNumber = grIncident.getRecord().getValue('number'); + + // Log the successful incident creation. + gs.info('Critical P1 incident ' + incNumber + ' created from alert from ' + source); + + // Prepare the success response. + var responseBody = { + "status": "success", + "message": "Critical incident created successfully.", + "incident_number": incNumber, + "incident_sys_id": newIncidentSysId + }; + response.setStatus(201); // Created + response.setBody(responseBody); + } else { + // Handle database insertion failure. + response.setStatus(500); // Internal Server Error + response.setBody({ + "status": "error", + "message": "Failed to create the incident record." + }); + } + + } catch (ex) { + // Handle any exceptions during processing. + gs.error('An error occurred during critical alert incident creation: ' + ex); + response.setStatus(500); + response.setBody({ + "status": "error", + "message": "An internal server error occurred." + }); + } From ec153ef17af7d9d6ea458e68bfae774ca8d09622 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 10:58:08 +0530 Subject: [PATCH 18/24] README.md --- .../README.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/README.md diff --git a/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/README.md b/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/README.md new file mode 100644 index 0000000000..a7e9c769fa --- /dev/null +++ b/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/README.md @@ -0,0 +1,59 @@ +Create Critical P1 Incident from Alert +This script provides the server-side logic for a Scripted REST API endpoint in ServiceNow. 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. +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. + +Installation +As a Scripted REST API Resource +Create the Scripted REST API: +Navigate to System Web Services > Scripted REST APIs. +Click New and fill in the details: +Name: CriticalAlertIncident +API ID: critical_alert_incident +Save the record. + + +Create the Resource: +On the Resources related list of the API record, click New. +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. + +Dependencies +This script requires the GlideJsonPath API, which is available in Jakarta and later releases. +The API endpoint must be secured with appropriate authentication to prevent unauthorized access. + +Considerations + +Security: This API endpoint is a powerful integration point. 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. From 41a3933fc4ed96de41b1e2e21278f0a02f59ac8b Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 10:59:47 +0530 Subject: [PATCH 19/24] Delete Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/README.md --- .../README.md | 37 ------------------- 1 file changed, 37 deletions(-) delete mode 100644 Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/README.md diff --git a/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/README.md b/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/README.md deleted file mode 100644 index 6f7afc5eac..0000000000 --- a/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/README.md +++ /dev/null @@ -1,37 +0,0 @@ -Key features -Automatic problem creation: The script uses a GlideAggregate query to count the number of incidents opened for a specific CI. -Time-based threshold: Problems are only created if more than five incidents are opened within a 60-minute window. -Targeted incidents: The script focuses on incidents related to the same CI, making it effective for identifying recurring infrastructure issues. -Customizable conditions: The number of incidents and the time frame are easily configurable within the script. -Efficient performance: The use of GlideAggregate ensures the database is queried efficiently, minimizing performance impact. - -How it works -The script is designed to be executed as a server-side script, typically within a Business Rule. When an incident is inserted or updated, the script performs the following actions: -Queries incidents: It executes a GlideAggregate query on the incident table. -Sets conditions: The query is filtered to count all incidents that meet the following conditions: -Same CI: The incident's cmdb_ci matches the cmdb_ci of the current record. -Within the last hour: The opened_at time is within the last 60 minutes. -Evaluates count: After the query is run, the script checks if the count of matching incidents exceeds the threshold (in this case, 5). -Creates problem: If the threshold is exceeded, a new problem record is initialized. -The short_description is automatically populated with a descriptive message. -The cmdb_ci is linked to the new problem record. -The new record is then inserted into the database. -Implementation steps -Create a Business Rule: -Navigate to System Definition > Business Rules. -Click New. -Configure the Business Rule: -Name: Auto Create Problem from Multiple Incidents -Table: Incident [incident] -Advanced: true -When to run: Select after and check the Insert and Update checkboxes. This ensures the script runs after an incident has been saved. -Filter conditions: Optionally, you can add conditions to limit when the script runs (e.g., cmdb_ci is not empty). -Add the script: -Navigate to the Advanced tab. -Copy and paste the script into the Script field. -Customize (optional): -Number of incidents: Change the > 5 value to adjust the threshold. -Time frame: Adjust the gs.minutesAgoStart(60) value to change the time window. -Other conditions: If you need to check for specific incident statuses or categories, add more addQuery lines to the GlideAggregate call. -Save the Business Rule. -Customization examples From 10e9542d528705a01c060997320c2351eb124240 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 11:00:24 +0530 Subject: [PATCH 20/24] Delete Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/script.js --- .../script.js | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/script.js diff --git a/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/script.js b/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/script.js deleted file mode 100644 index dcec063918..0000000000 --- a/Core ServiceNow APIs/GlideAggregate/Create Problem based on incident volume/script.js +++ /dev/null @@ -1,13 +0,0 @@ -var incidentCheck = new GlideAggregate('incident'); - incidentCheck.addQuery('cmdb_ci', current.cmdb_ci); // Or any specific CI - incidentCheck.addQuery('opened_at', '>', 'javascript:gs.minutesAgoStart(60)'); - incidentCheck.addAggregate('COUNT'); - incidentCheck.query(); - - if (incidentCheck.next() && parseInt(incidentCheck.getAggregate('COUNT')) > 5) { - var problem = new GlideRecord('problem'); - problem.initialize(); - problem.short_description = 'Multiple incidents reported for CI: ' + current.cmdb_ci.getDisplayValue(); - problem.cmdb_ci = current.cmdb_ci; - problem.insert(); - } From 15403af4e283702717f16bb5da9c796d2e0d5578 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 19:25:12 +0530 Subject: [PATCH 21/24] script.js Create Critical P1 Incident from Alert --- .../script.js | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Core ServiceNow APIs/GlideJsonPath/Create Critical P1 Incident from Alert using GlideJsonPath/script.js diff --git a/Core ServiceNow APIs/GlideJsonPath/Create Critical P1 Incident from Alert using GlideJsonPath/script.js b/Core ServiceNow APIs/GlideJsonPath/Create Critical P1 Incident from Alert using GlideJsonPath/script.js new file mode 100644 index 0000000000..2e55276b70 --- /dev/null +++ b/Core ServiceNow APIs/GlideJsonPath/Create Critical P1 Incident from Alert using GlideJsonPath/script.js @@ -0,0 +1,78 @@ +try { + // Get the JSON payload from the request body. + var requestBody = request.body.dataString; + + // Use GlideJsonPath to parse the JSON payload efficiently. + var gjp = new GlideJsonPath(requestBody); + + // Extract key information from the JSON payload. + var severity = gjp.read("$.alert.severity"); + var shortDescription = gjp.read("$.alert.description"); + var source = gjp.read("$.alert.source"); + var ciName = gjp.read("$.alert.configuration_item"); + var ciSysId = gjp.read("$.alert.ci_sys_id"); + + // Validate that mandatory fields are present. + if (!shortDescription || severity != 'CRITICAL') { + response.setStatus(400); // Bad Request + response.setBody({ + "status": "error", + "message": "Missing mandatory alert information or severity is not critical." + }); + return; + } + + // Use GlideRecordSecure for added security and ACL enforcement. + var grIncident = new GlideRecordSecure('incident'); + grIncident.initialize(); + + // Set incident field values from the JSON payload. + grIncident.setValue('short_description', 'INTEGRATION ALERT: [' + source + '] ' + shortDescription); + grIncident.setValue('description', 'A critical alert has been received from ' + source + '.\n\nAlert Details:\nSeverity: ' + severity + '\nDescription: ' + shortDescription + '\nCI Name: ' + ciName); + grIncident.setValue('source', source); + grIncident.setValue('impact', 1); // Set Impact to '1 - High' + grIncident.setValue('urgency', 1); // Set Urgency to '1 - High' + grIncident.setValue('priority', 1); // Set Priority to '1 - Critical' + + // If a CI sys_id is provided, set the Configuration Item. + if (ciSysId) { + grIncident.setValue('cmdb_ci', ciSysId); + } + + // Insert the new incident record and store its sys_id. + var newIncidentSysId = grIncident.insert(); + + if (newIncidentSysId) { + // Get the incident number for the successful response. + var incNumber = grIncident.getRecord().getValue('number'); + + // Log the successful incident creation. + gs.info('Critical P1 incident ' + incNumber + ' created from alert from ' + source); + + // Prepare the success response. + var responseBody = { + "status": "success", + "message": "Critical incident created successfully.", + "incident_number": incNumber, + "incident_sys_id": newIncidentSysId + }; + response.setStatus(201); // Created + response.setBody(responseBody); + } else { + // Handle database insertion failure. + response.setStatus(500); // Internal Server Error + response.setBody({ + "status": "error", + "message": "Failed to create the incident record." + }); + } + + } catch (ex) { + // Handle any exceptions during processing. + gs.error('An error occurred during critical alert incident creation: ' + ex); + response.setStatus(500); + response.setBody({ + "status": "error", + "message": "An internal server error occurred." + }); + } From 5d15766d912b739c7a15f156843718b27801fab6 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 19:26:25 +0530 Subject: [PATCH 22/24] README.md --- .../README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Core ServiceNow APIs/GlideJsonPath/Create Critical P1 Incident from Alert using GlideJsonPath/README.md diff --git a/Core ServiceNow APIs/GlideJsonPath/Create Critical P1 Incident from Alert using GlideJsonPath/README.md b/Core ServiceNow APIs/GlideJsonPath/Create Critical P1 Incident from Alert using GlideJsonPath/README.md new file mode 100644 index 0000000000..84814e38fd --- /dev/null +++ b/Core ServiceNow APIs/GlideJsonPath/Create Critical P1 Incident from Alert using GlideJsonPath/README.md @@ -0,0 +1,17 @@ +Create Critical P1 Incident from Alert This script provides the server-side logic for a Scripted REST API endpoint in ServiceNow. +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. +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. + +Installation As a Scripted REST API Resource Create the Scripted REST API: Navigate to System Web Services > Scripted REST APIs. +Click New and fill in the details: Name: CriticalAlertIncident API ID: critical_alert_incident Save the record. + +Create the Resource: On the Resources related list of the API record, click New. +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. + +Dependencies This script requires the GlideJsonPath API, which is available in Jakarta and later releases. +The API endpoint must be secured with appropriate authentication to prevent unauthorized access. + +Considerations + +Security: This API endpoint is a powerful integration point. +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. From 75497d91f95b015451eff0eac16085ed3ce93812 Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 19:28:49 +0530 Subject: [PATCH 23/24] Delete Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/README.md --- .../README.md | 59 ------------------- 1 file changed, 59 deletions(-) delete mode 100644 Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/README.md diff --git a/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/README.md b/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/README.md deleted file mode 100644 index a7e9c769fa..0000000000 --- a/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/README.md +++ /dev/null @@ -1,59 +0,0 @@ -Create Critical P1 Incident from Alert -This script provides the server-side logic for a Scripted REST API endpoint in ServiceNow. 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. -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. - -Installation -As a Scripted REST API Resource -Create the Scripted REST API: -Navigate to System Web Services > Scripted REST APIs. -Click New and fill in the details: -Name: CriticalAlertIncident -API ID: critical_alert_incident -Save the record. - - -Create the Resource: -On the Resources related list of the API record, click New. -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. - -Dependencies -This script requires the GlideJsonPath API, which is available in Jakarta and later releases. -The API endpoint must be secured with appropriate authentication to prevent unauthorized access. - -Considerations - -Security: This API endpoint is a powerful integration point. 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. From eae75cfcaae4c5da4077e8d3ff6eaab34291d89f Mon Sep 17 00:00:00 2001 From: trimbakeshmadhan-109 Date: Tue, 28 Oct 2025 19:29:13 +0530 Subject: [PATCH 24/24] Delete Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/script.js --- .../script.js | 78 ------------------- 1 file changed, 78 deletions(-) delete mode 100644 Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/script.js diff --git a/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/script.js b/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/script.js deleted file mode 100644 index 2e55276b70..0000000000 --- a/Core ServiceNow APIs/GlideJsonPath/Basic-Example/Creating a P1 Major Incident from an external monitoring system/script.js +++ /dev/null @@ -1,78 +0,0 @@ -try { - // Get the JSON payload from the request body. - var requestBody = request.body.dataString; - - // Use GlideJsonPath to parse the JSON payload efficiently. - var gjp = new GlideJsonPath(requestBody); - - // Extract key information from the JSON payload. - var severity = gjp.read("$.alert.severity"); - var shortDescription = gjp.read("$.alert.description"); - var source = gjp.read("$.alert.source"); - var ciName = gjp.read("$.alert.configuration_item"); - var ciSysId = gjp.read("$.alert.ci_sys_id"); - - // Validate that mandatory fields are present. - if (!shortDescription || severity != 'CRITICAL') { - response.setStatus(400); // Bad Request - response.setBody({ - "status": "error", - "message": "Missing mandatory alert information or severity is not critical." - }); - return; - } - - // Use GlideRecordSecure for added security and ACL enforcement. - var grIncident = new GlideRecordSecure('incident'); - grIncident.initialize(); - - // Set incident field values from the JSON payload. - grIncident.setValue('short_description', 'INTEGRATION ALERT: [' + source + '] ' + shortDescription); - grIncident.setValue('description', 'A critical alert has been received from ' + source + '.\n\nAlert Details:\nSeverity: ' + severity + '\nDescription: ' + shortDescription + '\nCI Name: ' + ciName); - grIncident.setValue('source', source); - grIncident.setValue('impact', 1); // Set Impact to '1 - High' - grIncident.setValue('urgency', 1); // Set Urgency to '1 - High' - grIncident.setValue('priority', 1); // Set Priority to '1 - Critical' - - // If a CI sys_id is provided, set the Configuration Item. - if (ciSysId) { - grIncident.setValue('cmdb_ci', ciSysId); - } - - // Insert the new incident record and store its sys_id. - var newIncidentSysId = grIncident.insert(); - - if (newIncidentSysId) { - // Get the incident number for the successful response. - var incNumber = grIncident.getRecord().getValue('number'); - - // Log the successful incident creation. - gs.info('Critical P1 incident ' + incNumber + ' created from alert from ' + source); - - // Prepare the success response. - var responseBody = { - "status": "success", - "message": "Critical incident created successfully.", - "incident_number": incNumber, - "incident_sys_id": newIncidentSysId - }; - response.setStatus(201); // Created - response.setBody(responseBody); - } else { - // Handle database insertion failure. - response.setStatus(500); // Internal Server Error - response.setBody({ - "status": "error", - "message": "Failed to create the incident record." - }); - } - - } catch (ex) { - // Handle any exceptions during processing. - gs.error('An error occurred during critical alert incident creation: ' + ex); - response.setStatus(500); - response.setBody({ - "status": "error", - "message": "An internal server error occurred." - }); - }