惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
IT之家
IT之家
The Cloudflare Blog
Apple Machine Learning Research
Apple Machine Learning Research
WordPress大学
WordPress大学
N
Netflix TechBlog - Medium
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
L
LangChain Blog
博客园 - Franky
美团技术团队
J
Java Code Geeks
Microsoft Security Blog
Microsoft Security Blog
博客园 - 叶小钗
小众软件
小众软件
Y
Y Combinator Blog
B
Blog RSS Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
D
Docker
Hugging Face - Blog
Hugging Face - Blog
Jina AI
Jina AI
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Integrating ServiceNow Incidents with Elastic AI Agents f...
Nobu Sekiya · 2026-05-02 · via DEV Community

Nobu Sekiya

Introduction

This is an example of calling an Elastic AI Agent from a ServiceNow incident.
Based on the details recorded in the incident, you can have the AI Agent perform observability analysis as needed.
I am not very familiar with ServiceNow, so I implemented this while consulting with Gemini. Please note that this may not be the most optimal implementation.

The ServiceNow version used is Zurich.

Component Flow

The workflow involves having the Elastic AI Agent investigate the incident details and recording the returned results back into the incident.

[ServiceNow Incident]
        │
        ▼
[UI Action (Manual Trigger)]
        │
        ▼
[ServiceNow Flow Designer (Subflow)]
        │
        ▼
[ServiceNow Action (Integration Step)]
        │
        ▼
[Elastic Workflow (Orchestration)]
        │
        ▼
[Elastic AI Agent (Agent Builder)]
        │
        ▼
[Elasticsearch Observability Data]

Enter fullscreen mode Exit fullscreen mode

Elastic Side Configuration

Elastic Workflow

Save a Workflow with the following definition. Make sure to copy the Workflow ID included in its URL, as you will need it later to call it from ServiceNow.

name: test_servicenow
enabled: true
triggers:
  - type: manual
inputs:
  - name: incident_number
    type: string
    required: true
  - name: incident_sys_id
    type: string
    required: true
  - name: short_description
    type: string
    required: true
  - name: priority
    type: string
    required: true

steps:
  - name: console
    type: console
    with:
      message: "{{inputs.incident_number}} {{inputs.incident_sys_id}} {{inputs.priority}} {{inputs.short_description}}"
  - name: check_with_ai_agent
    type: ai.agent
    with:
      message: "Output in plain text format and **NO** markdown. Check index: kibana_sample_data_flights and get information of: {{ inputs.short_description }}"

  - name: post_to_snow
    type: http
    with:
      url: "https://<Your ServiceNow ID domain>/api/now/table/incident/{{ inputs.incident_sys_id }}"
      method: PATCH
      headers:
        Authorization: "Basic <Your user:password base64>"
        Content-Type: "application/json"
      body: '{"work_notes": "{{ steps.check_with_ai_agent.output.message | replace: "\n", "\\n"}}"}'

Enter fullscreen mode Exit fullscreen mode

For the Basic key above, set the base64-encoded string of username:password.
In this example, I used the ServiceNow admin user and password for testing. (On Mac, you can use the output of echo -n "admin:xxx" | base64).

ServiceNow Side Configuration

System Definition > Script Includes

CleanShot 2026-04-16 at 09.55.20.png

// Script Include: ElasticKibanaHelper
// Scope: Global
// Client callable: false

var ElasticKibanaHelper = Class.create();

ElasticKibanaHelper.prototype = {

    initialize: function() {
        this.baseUrl    = 'https://<xxx>.elastic.cloud';
        this.apiKey     = gs.getProperty('elastic.kibana.api_key', '');
        this.timeout    = 30000; // 30 seconds
    },

    /**
     * Trigger a Kibana Workflow by ID.
     *
     * @param  {String} workflowId  - The Kibana workflow ID to run
     * @param  {Object} bodyParams  - Optional JSON payload to send with the request
     * @returns {Object}            - { success: Boolean, status: Number, body: Object, error: String }
     */
    runWorkflow: function(workflowId, bodyParams) {

        if (!workflowId) {
            return this._error('workflowId is required');
        }

        if (!this.apiKey) {
            gs.error('ElasticKibanaHelper: elastic.kibana.api_key system property is not set');
            return this._error('API key not configured. Set the elastic.kibana.api_key system property.');
        }

        var endpoint = this.baseUrl + '/api/workflows/workflow/' + workflowId + '/run';
        var payload = JSON.stringify({
            inputs: bodyParams || {}
        });

        try {
            var request = new sn_ws.RESTMessageV2();
            request.setEndpoint(endpoint);
            request.setHttpMethod('POST');

            // ── Authentication ──────────────────────────────────────────────
            request.setRequestHeader('Authorization', 'ApiKey ' + this.apiKey);

            // ── Standard headers ────────────────────────────────────────────
            request.setRequestHeader('Content-Type',  'application/json');
            request.setRequestHeader('kbn-xsrf',      'true');   // Required by Kibana REST API

            // ── Body ────────────────────────────────────────────────────────
            request.setRequestBody(payload);

            // Timeout
            request.setEccParameter('connect_timeout', this.timeout);
            request.setEccParameter('read_timeout',    this.timeout);

            var response   = request.execute();
            var statusCode = response.getStatusCode();
            var bodyText   = response.getBody();

            gs.info(
                'ElasticKibanaHelper.runWorkflow | workflowId=' + workflowId +
                ' | status=' + statusCode
            );

            var parsedBody = {};
            try { parsedBody = JSON.parse(bodyText); } catch(e) { parsedBody = { raw: bodyText }; }

            if (statusCode >= 200 && statusCode < 300) {
                return {
                    success:    true,
                    status:      statusCode,
                    body:        parsedBody,
                    error:       null
                };
            }

            gs.error(
                'ElasticKibanaHelper.runWorkflow: HTTP ' + statusCode +
                ' for workflowId=' + workflowId + ' | body=' + bodyText
            );

            return {
                success: false,
                status:  statusCode,
                body:    parsedBody,
                error:   'HTTP ' + statusCode + ': ' + (parsedBody.message || bodyText)
            };

        } catch(ex) {
            gs.error('ElasticKibanaHelper.runWorkflow exception: ' + ex.message);
            return this._error(ex.message);
        }
    },

    // ── Private helpers ───────────────────────────────────────────────────────

    _error: function(msg) {
        return { success: false, status: null, body: null, error: msg };
    },

    type: 'ElasticKibanaHelper'
};

Enter fullscreen mode Exit fullscreen mode

Configure Elastic Authentication API Key via sys_properties.list

Set the property: elastic.kibana.api_key
CleanShot 2026-04-21 at 19.20.27@2x.png

Flow Designer (Workflow Studio) > Actions

Inputs

CleanShot 2026-04-21 at 17.59.28@2x.png

Script - Input Variables

CleanShot 2026-04-21 at 18.01.44@2x.png

Script - Script

CleanShot 2026-04-21 at 18.02.22@2x.png

// Flow Designer Action Script Step
// Action name: Run Elastic Kibana Workflow
// Step name:   Invoke Kibana Workflow API
//
// Inputs (mapped from Action Inputs above):
//   inputs.workflow_id        → String
//   inputs.incident_number    → String
//   inputs.incident_sys_id    → String
//   inputs.short_description  → String
//   inputs.priority           → String
//
// Outputs to set:
//   outputs.success           → Boolean
//   outputs.response_status   → Integer
//   outputs.response_body     → String
//   outputs.error_message     → String

(function execute(inputs, outputs) {

    var helper = new ElasticKibanaHelper();

    // Build the payload sent to Kibana
    var payload = {
        source:            'ServiceNow',
        incident_number:   inputs.incident_number  || '',
        incident_sys_id:   inputs.incident_sys_id  || '',
        short_description: inputs.short_description || '',
        priority:          inputs.priority          || '',
        triggered_at:      new GlideDateTime().getDisplayValue()
    };

    var result = helper.runWorkflow(inputs.workflow_id, payload);

    // ── Map results to Action outputs ────────────────────────────────────────
    outputs.success         = result.success;
    outputs.response_status = result.status   ? String(result.status) : '';
    outputs.response_body   = result.body     ? JSON.stringify(result.body) : '';
    outputs.error_message   = result.error    ? result.error : '';

    if (!result.success) {
        // Surface the error in the flow execution log
        gs.error(
            'Run Elastic Kibana Workflow action failed | ' +
            'incident=' + inputs.incident_number +
            ' | workflowId=' + inputs.workflow_id +
            ' | error=' + result.error
        );
    }

})(inputs, outputs);

Enter fullscreen mode Exit fullscreen mode

Script - Output Variables

CleanShot 2026-04-21 at 18.02.36@2x.png

Flow Designer (Workflow Studio) > Subflows

CleanShot 2026-04-21 at 18.33.56@2x.png

The ID of the Elastic Workflow to be executed is hardcoded here.
CleanShot 2026-04-21 at 18.05.15@2x.png

All > System Definitions > UI Actions

Check Form button and set the Script.
CleanShot 2026-04-21 at 18.11.59@2x.png

(function() {
    try {
        var inputs = {};
        // Set "current" to the "Name" defined in the Subflow Input (e.g., incident_record)
        inputs['incident_record'] = current; 

        // Test with "synchronous execution" that is guaranteed to work
        // * Be sure to use the Internal Name copied from the Subflow Properties for 'global.xxx'
        var result = sn_fd.FlowAPI.executeSubflow('global.from_button_trigger_elastic_investigation', inputs);

        // For synchronous execution, you can directly retrieve information from the returned object
        gs.addInfoMessage('Executed Subflow');

    } catch (ex) {
        // Force display of the error type and details
        var errorDetail = (ex.message) ? ex.message : ex.toString();
        gs.addErrorMessage('[Debug] Error details: ' + errorDetail);

        // Also output detailed information to the system log (sys_log)
        gs.error('Subflow Debug: ' + errorDetail);
    }

    // Keep the current screen
    action.setRedirectURL(current);
})();

Enter fullscreen mode Exit fullscreen mode

Testing the Operation!

Create an Incident in ServiceNow.

  • Confirm that the Execute data investigation in Elastic AI button appears in the top right.
  • The Short description will be the investigation request sent to the Elastic AI Agent.

Save the Incident once, then open it again and execute the button.

CleanShot 2026-04-21 at 18.40.50@2x.png

Confirm that "Executed Subflow" is displayed.
CleanShot 2026-04-21 at 18.41.22@2x.png

Confirm that the Elastic Workflow is executed successfully.
CleanShot 2026-04-21 at 19.38.57@2x.png

Confirm that the results from the Elastic AI Agent are returned to the Incident.
CleanShot 2026-04-21 at 19.39.19@2x.png

Conclusion

Before the era of AI Agents, the data returned by such integrations was very limited. Now, AI Agents can perform various analyses and return them in a human-readable format, making them highly effective for incident management.