# ServiceNow

A `servicenow` notification endpoint posts Insights alerts to a [Scripted REST API](https://developer.servicenow.com/) you build in your ServiceNow instance. Your script decides what each alert becomes: an incident, an event, or nothing. Insights keeps no ServiceNow state of its own, and this setup does not need Event Management or the ITOM add-on.

This guide covers what Insights sends, what the receiving script must do with it, and an example that opens, refreshes and closes incidents.

## Configuration

```
notifications:

  servicenow:

    - name: "servicenow"

      url: "https://<instance>.service-now.com/api/<namespace>/insights/alerts"

      auth-type: "apikey"

      auth-token: "${SERVICENOW_API_KEY}"

      subscriptions: ["*"]
```

The fields are the same as every other endpoint type; see [Notifications → Configuration](/insights/1.3/guides/notifications.md#configuration). `auth-type` is required and must be `apikey` or `basic`:

* **`apikey`**: sends `auth-token` in the `x-sn-apikey` header. Needs the Washington DC release or later, with the *API Key and HMAC Authentication* plugin active. In ServiceNow, create an inbound authentication profile of type API Key that reads the `x-sn-apikey` header, a REST API key for a dedicated integration user, and a REST API access policy that applies the profile to your Scripted REST API. See ServiceNow's [inbound REST API keys](https://www.servicenow.com/community/developer-advocate-blog/inbound-rest-api-keys/ba-p/2854924) walkthrough. The key can be revoked without touching the user's password, so prefer it where your release supports it.

  * ServiceNow generates the key when you create the REST API key record; reveal its token on that record and put it in the `SERVICENOW_API_KEY` environment variable (or straight into `auth-token`; see [Secrets from the environment](/insights/1.3/guides/notifications.md#secrets-from-the-environment)).
  * The integration user needs no roles: the script below writes incidents server-side.
  * Once the access policy exists, the API accepts only the authentication profiles the policy lists. Basic auth to it stops working unless you add a basic profile to the policy too.

* **`basic`**: a ServiceNow user with permission to call the Scripted REST API and write the incident table. Works on any release.

The URL is the resource path ServiceNow shows for the Scripted REST resource: the API's base path plus the resource's relative path.

## What Insights sends

Each request is the [`webhook` envelope](/insights/1.3/guides/notifications.md#payload-labels-and-annotations): a JSON object whose `alerts` array holds one entry per alert, each with `status` (`firing` or `resolved`), `labels`, `annotations`, `startsAt`, `endsAt`, `generatorURL` and `fingerprint`.

Insights sends two kinds of request to the same URL:

* **Transitions**, as soon as an epoch commits: a check firing, resolving, or changing severity.
* **The active set**, every minute and once at startup: every alert currently firing for the endpoint's subscriptions, each with an `endsAt` four minutes ahead.

The `fingerprint` is a hash of the alert's labels. `severity` is a label, so a finding that changes severity is a new alert with a new fingerprint. The same request resolves the former severity's alert first, with a `resolve_reason` annotation of `severity_changed`, and the new alert carries `previous_severity`.

## Receiver contract

The script must do all of the following. Each one covers a failure Insights cannot fix on its own side.

1. **Key every record on `fingerprint`.** The same fingerprint arrives every minute while an alert fires, and a failed delivery is retried, so the same alert can arrive many times.
2. **On a firing alert, create the record if none is open, otherwise refresh it.** The active set also re-creates a record whose original firing alert was lost, such as one still waiting for a retry when Insights restarted.
3. **On a resolved alert, close the open record with that fingerprint.** Ignore a resolve for a fingerprint with no open record.
4. **Close any record whose `endsAt` has passed without a refresh.** This is a requirement, not an optimisation. A resolve can be lost: Insights keeps pending retries in memory, and a script can return 200 without acting. A firing alert that stops arriving has cleared, or Insights has stopped, and either way the record must not stay open forever. A Scripted REST resource only runs when called, so this needs a scheduled job.

## Example

The example below opens one incident per alert, refreshes it while the alert keeps arriving, and resolves it on a resolve or on expiry. Adapt it to your instance: the field mapping, the close code, and whether you raise incidents at all are your choice.

It runs in the global scope: create the Scripted REST API, the scheduled job and the custom field with the Global application selected. In a scoped application, ServiceNow prefixes the field name with the scope, and the script no longer finds it.

It uses these incident fields:

* `correlation_id`: the alert's `fingerprint`.
* `correlation_display`: `insights`, to tell these incidents apart from other integrations.
* `u_insights_ends_at`: a custom Date/Time field you add to the incident table, holding the latest `endsAt`. Give it the `no_audit=true` dictionary attribute, or every refresh adds an entry to the incident's history.

### Scripted REST resource

Create a Scripted REST API, then a resource with HTTP method `POST`, **Requires authentication** checked, and this script:

```
(function process(request, response) {

    // Severity to impact and urgency (1 high, 3 low).

    var LEVEL = { critical: 1, warning: 2, info: 3 };

    var RESOLVED = 6;



    var alerts = request.body.data.alerts || [];

    for (var i = 0; i < alerts.length; i++) {

        handle(alerts[i]);

    }

    response.setStatus(200);



    function handle(alert) {

        var inc = new GlideRecord('incident');

        inc.addQuery('correlation_id', alert.fingerprint);

        inc.addQuery('state', '<', RESOLVED);

        inc.setLimit(1);

        inc.query();

        var open = inc.next();



        if (alert.status == 'resolved') {

            if (open) {

                var why = alert.annotations.resolve_reason == 'severity_changed'

                    ? 'Insights: severity changed; a new incident tracks the new severity.'

                    : 'Insights: the finding cleared.';

                resolve(inc, why);

            }

            return;

        }



        if (open) {

            // A refresh: move the deadline only, without business rules or

            // notifications firing every minute.

            inc.setValue('u_insights_ends_at', toGlide(alert.endsAt).getValue());

            inc.setWorkflow(false);

            inc.update();

            return;

        }



        var level = LEVEL[alert.labels.severity] || 3;

        var a = alert.annotations;

        var subject = a.entity_name || alert.labels.entity_key || alert.labels.entity_type;

        inc.initialize();

        inc.setValue('correlation_id', alert.fingerprint);

        inc.setValue('correlation_display', 'insights');

        inc.setValue('impact', level);

        inc.setValue('urgency', level);

        inc.setValue('short_description',

            (a.summary || alert.labels.alertname) + ': ' + subject + ' (' + alert.labels.system + ')');

        inc.setValue('description', [

            a.description, a.remediation, alert.generatorURL

        ].filter(Boolean).join('\n\n'));

        inc.setValue('u_insights_ends_at', toGlide(alert.endsAt).getValue());

        inc.insert();

    }



    function resolve(inc, notes) {

        inc.setValue('state', RESOLVED);

        inc.setValue('close_code', 'Solution provided');

        inc.setValue('close_notes', notes);

        inc.update();

    }



    // endsAt is RFC 3339 with up to nanosecond precision; Date takes milliseconds.

    function toGlide(iso) {

        var g = new GlideDateTime();

        g.setNumericValue(new Date(iso.replace(/\.\d+/, '')).getTime());

        return g;

    }

})(request, response);
```

### Scheduled job for expiry

Create a **Scheduled Script Execution** that runs every few minutes:

```
(function () {

    var RESOLVED = 6;

    var inc = new GlideRecord('incident');

    inc.addQuery('correlation_display', 'insights');

    inc.addQuery('state', '<', RESOLVED);

    inc.addQuery('u_insights_ends_at', '<', new GlideDateTime().getValue());

    inc.query();

    while (inc.next()) {

        inc.setValue('state', RESOLVED);

        inc.setValue('close_code', 'Solution provided');

        inc.setValue('close_notes',

            'Insights: no refresh before the deadline. The finding cleared without a resolve reaching ServiceNow, or Insights stopped sending.');

        inc.update();

    }

})();
```

If Insights stops for longer than four minutes, this resolves its open incidents, and the first active-set delivery after it restarts opens new ones for whatever is still firing. The same applies to an incident someone resolves by hand while its alert still fires: the next active-set delivery, within a minute, opens a new one.

## Testing

Use the **Test** button on the endpoint's page in the Insights UI to send a synthetic firing alert, and confirm an incident appears. Its `endsAt` is one minute ahead and it is never refreshed, so the scheduled job resolves it on its first run after that. A [personal developer instance](https://developer.servicenow.com/) is a safe place to build the script before installing it on a production instance.
