Splunk Enterprise SDK for JavaScript

repository·develop·Indexed 41 days ago

https://github.com/splunk/splunk-sdk-javascript

SDK for interacting with the Splunk REST API using server-side (Node.js) and client-side JavaScript. Version 2.0.2 features Promise-based methods for async/await support, replacing callbacks from v1.x. Includes tools for authentication via username/password, session keys, or bearer tokens, as well as utilities for managing .conf files and a CLI for building and testing.

Tokens
7.6K
Snippets
34
Records
46
Agent score
52%

What's inside Splunk SDK for JavaScript

  1. Migrate from Callbacks (v1.x) to Promises/async-await (v2.x)

    develop

    In version 2.x, Splunk Enterprise SDK for JavaScript methods have been updated to return Promises. This allows you to use async/await instead of passing callback functions.

    Important Change: The abort() method has been replaced by the response_timeout parameter, which allows you to specify a timeout for a particular API call.

    // v2.x Promise/async-await approach
    let appName = "<app-name>";  
    try {
        let apps = await service.apps().fetch();
        let appList = apps.list();
        // other code
    } catch (err) {
        console.log("There was an error retrieving the list of applications:", err);
    }
  2. How the Data-Attribute API works

    develop

    Bootstrap plugins can be used purely through HTML markup using data attributes without writing JavaScript. This allows for declarative interaction patterns.

    To disable the data-attribute API globally, unbind all events on the body namespaced with 'data-api':

    $('body').off('.data-api')

    To target a specific plugin for disabling, include the plugin's name as a namespace:

    $('body').off('.alert.data-api')
    $('body').off('.data-api')
  3. How the Programmatic API works

    develop

    All Bootstrap plugins are available via a JavaScript API. Public APIs are designed to be single, chainable methods that return the collection they acted upon.

    Methods typically accept one of three types of arguments:

    1. An optional options object: To configure the plugin instance.
    2. A string: To target a specific method (e.g., 'show').
    3. null: To initiate the default behavior.

    Example of chaining and method invocation:

    // Chaining methods
    $(".btn.danger").button("toggle").addClass("fat")
    
    // Initializing with defaults
    $("#myModal").modal()
    
    // Initializing with custom options
    $("#myModal").modal({ keyboard: false })
    
    // Initializing and invoking a specific method immediately
    $("#myModal").modal('show')
    $("#myModal").modal('show')
  4. Use a .splunkrc file for development convenience

    develop

    To avoid passing host, port, and credentials via command line during development, you can create a .splunkrc file in your user's home directory. The SDK unit tests will automatically use these values if they are not explicitly provided.

    Warning: Do not use .splunkrc to store production credentials. It is intended for local development convenience only.

    File Format:

    # Splunk Enterprise host (default: localhost)
    host=localhost
    # Splunk Enterprise admin port (default: 8089)
    port=8089
    # Splunk Enterprise username
    username=admin
    # Splunk Enterprise password
    password=changed!
    # Access scheme (default: https)
    scheme=https
    # Your version of Splunk Enterprise
    version=9.0

    Locations:

    • OS X: ~/.splunkrc
    • Windows: C:\Users\<currentusername>\.splunkrc (Note: You may need to use the command line Notepad.exe .splunkrc to create files starting with a dot on Windows).
  5. Authenticate using a Bearer Token

    develop

    To authenticate with Splunk using a token instead of a session key, pass the token to the sessionKey property when initializing the splunkjs.Service object. Ensure the scheme (e.g., 'https') and host are correctly configured for your Splunk instance.

    let serviceWithBearerToken = new splunkjs.Service({
        // Replace the host if you are accessing remote host
        scheme: 'https',
        host: 'localhost',
        port: '8089',
        sessionKey: TOKEN, // Add your token here
        version: '8',
    });
    
    try {
        let res  = await serviceWithBearerToken.jobs({ count: 2 });
        console.log("Login successful with bearer token");
    } catch(err) {
        console.log(err);
    }
  6. Authenticate with a token

    develop

    To use token-based authentication, you must first enable token authentication on the Splunk instance, then create a token.

    Enable token authentication via Shell

    curl -k -u <username>:<password> -X POST <scheme>://<host>:<port>/services/admin/token-auth/tokens_auth -d disabled=false

    Enable token authentication via Web UI

    Navigate to Settings > Tokens and click on 'Enable Token Authentication'.

    Create a token via Shell

    curl -k -u <username>:<password> -X POST <scheme>://<host>:<port>/services/authorization/tokens?output_mode=json --data name=<username> --data audience=Users --data-urlencode expires_on=+30d
  7. Manage development tasks with sdkdo

    develop

    The SDK uses a helper script called sdkdo to manage building, testing, and documentation generation. All commands should be run from the splunk-sdk-javascript directory.

    Compile browser files: Rebuild and minify browser-ready files:

    node sdkdo compile

    (Note: If you encounter TypeErrors, run npm install first.)

    Run unit tests: Note: The SDK App Collection app is required for running tests.

    • Run all tests: node sdkdo tests
    • Run specific modules (e.g., http and utils): node sdkdo tests http,utils
    • Run tests matching a string: node sdkdo tests --grep "While success"
    • Run browser tests: node sdkdo tests-browser
    • Run tests quietly (no log messages): node sdkdo tests --quiet
    • Generate a Mochawesome HTML report: node sdkdo tests --reporter mochawesome

    To see all available commands and options, run:

    node sdkdo --help
  8. How to use Data Attributes for plugins

    develop

    Data attributes define interactions and options directly in markup. They follow these patterns:

    • data-{{verb}}={{plugin}}: Defines the main interaction.
    • data-target or href^=#: Used on a 'control' element to target a different element.
    • data-{{noun}}: Defines class instance options.

    Examples

    Control elements (targeting others):

    <div data-toggle="modal" data-target="#foo"></div>
    <div data-toggle="collapse" data-target="#foo" data-parent="#bar"></div>

    Elements being controlled:

    <div data-spy="scroll"></div>
    <div data-dismiss="modal"></div>
    <div data-dismiss="alert"></div>

    Other common toggles:

    <div data-toggle="dropdown"></div>
    <div data-toggle="button"></div>
    <div data-toggle="buttons-checkbox"></div>
    <div data-toggle="buttons-radio"></div>