Splunk® Enterprise

Developing Views and Apps for Splunk Web

Download manual as PDF

Download topic as PDF

Convert a script alert action to a custom alert action

The run a script alert action is officially deprecated. Learn how to migrate existing alert action scripts to the custom alert action framework.

Migration planning

  • Start the migration process by comparing the scripted and custom alert action frameworks.
  • Design a user interface to let users configure the alert action.


See the Custom alert actions overview for a compete guide to the custom alert action developer documentation.

Framework comparison

Feature Script alert action Custom alert action Notes
Numbered arguments for accessing alert values
For example, use $0 or SPLUNK_ARG_0 for the script name.
Yes No For custom alert actions, use configuration file parameters to access and pass values to the configuration payload that the alert action receives.
User interface API No Yes The custom alert action API lets you build a configuration user interface that users can access when creating or editing an alert.
Configuration files No Yes Custom alert actions use alert_actions.conf and savedsearches.conf for registration and configuration. They also use app.conf for app package and UI configuration.
Additional components No Yes Custom alert action app components can include a default.meta file to specify permissions and access for the alert action. You can also include an icon for the alert action.

Accessing script argument values in a custom alert action

One of the primary differences between the scripted alert action and custom alert actions is the API for accessing contextual values. These values are used in alert action configuration, dispatch, and communication.

The scripted alert action framework offers predefined positional arguments to access specific values.

In custom alert actions, a script can read in parameters and values from configuration files.Some of these values are available by default in the configuration payload. You can create configuration parameters in alert_actions.conf to pass additional values in to the payload. Developers typically set up configuration files before writing a custom alert action script.

For more information on working with configuration files and the configuration payload, see Set up custom alert configuration files.


SPLUNK_ARG environment variable Value How to access the value in a custom alert action
0 Script name The custom alert action script name must match the custom alert action stanza name in alert_actions.conf. It must also match the stanza name in alert_actions.conf.spec.
1 Number of events returned Not available by default in the configuration payload. You can create a param to capture this search property using the $job.resultCount$ token in alert_actions.conf.
2 Search terms Not available by default in the configuration payload. You can create a param to capture this search property using the $job.request.search$ token in alert_actions.conf.
3 Fully qualified search string Not available by default in the configuration payload. You can create a param to capture this search property using the $job.request.qualifedSearch$ token in alert_actions.conf.
4 Name of saved search Available as search_name key value pair in the custom alert action payload.
5 Trigger reason Not available by default in the configuration payload.

To replicate the scripted alert trigger reason, create a param for a trigger reason string in alert_actions.conf. Use the $relation$ and $quantity$ job properties to concatenate the trigger reason string.
6 Results link Available as results_link key value pair in the custom alert action configuration payload.
7 Not used in scripted alert actions N/A
8 File in which the results for the search are stored.

Contains raw results in gzip file format.

Available as results_file key value pair in the custom alert action configuration payload.

Building a user interface

Custom alert action apps include a user interface, while scripted actions do not. You can create a simple user interface as part of migrating an alert action script to a custom alert action. See Define a custom alert action interface for more information.


Example

This example shows you how to migrate a scripted alert action that posts a notification to a Slack chat room.

The files referenced are examples similar to files that you might have in your Splunk platform /scripts and etc/apps directories.

Scripted alert action

This sendSlackAlertPythonOnly script is in the /bin/scripts directory on the Splunk platform instance.

import os
import sys
import requests

def send_slack(args_tuple, label=""): 
    message = create_slack_msg(args_tuple, label)
    payload = str({"text": message})
    slackUrl = "https://hooks.slack.com/services/T41234fF2L/B4Z46756FW/Cowjj4NATJV7zqczOV23qWog"
    r = requests.post(slackUrl, data = payload)

def create_slack_msg(args_tuple, label=""):
    message = """
    *This is a Splunk %s :horse:. Below are the 8 command line*
    *arguments used when invoking this scripted alert action.*
        1) Number of Events Returned: %s
        2) Search Terms: %s
        3) Fully Qualified Search String: %s
        4) Name of Saved Search: %s
        5) Trigger Reason: %s
        6) Linked To Saved Search: %s
        7) Tags or File Name for Results: %s
        8) File Name for Results (or none if no tags): %s
    """ % ((label,) + args_tuple)
    return message
    
if __name__ == "__main__":
    print >> sys.stderr, "you_are_here"
    send_slack(tuple(sys.argv[1:]), "Scripted Alert Action (simple python scripted alert action)")

Comparable bash script example
The following bash script is an example of similar scripted alert action functionality in a shell script.

#!/bin/bash                                                                  

slackUrl = "https://hooks.slack.com/services/T41234fF2L/B4Z46756FW/Cowjj4NATJV7zqczOV23qWog"

read -d "" message <<- EOF
*This is a Splunk Scripted Alert (simple bash script) :horse:. Below are the 8 commandline arguments*
*that Splunk invokes this scripted alert with:*
    1) Number of Events Returned: $1
    2) Search Terms: $2
    3) Fully Qualified Search String: $3
    4) Name of Saved Search: $4
    5) Trigger Reason: $5
    6) Linked To Saved Search: $6
    7) Tags or File Name for Results: $7
    8) File Name for Results (or none if no tags): $8
EOF

curl -X POST -H 'Content-type: application/json' --data "{'text': '$message'}" "$slackUrl"


Migrated custom alert action files

The following files are part of a custom alert action app package in the /etc/apps/alert_slack directory. This custom alert action migrates the sendSlackAlertPythonOnly scripted alert action.

The example files here are only those required for migrating the scripted alert action. They do not represent all of the files in a custom alert action app. See the Custom alert action component reference for complete details.


Script
This script uses symlinking to import functionality from the sendSlackAlertPythonOnly scripted alert action. Symlinking is optional when migrating a scripted alert action.

import sys
import os
import json
from urllib import urlencode
import urllib2
import requests

# symlink this
from sendSlackAlertPythonOnly import create_slack_msg

def send_slack(settings):
    try:
        config = settings['configuration']
        args_tuple = (
            config['result_count'],
            config['search_query'],
            config['search_query'],
            settings['search_name'],
            config['trigger_reason'],
            settings['results_link'],
            'NA',
            settings['results_file']       
        )
        message = create_slack_msg(args_tuple, "Custom Alert Action (that invokes a legacy, python, scripted alert)")
        payload = "{'text': '%s'}" % message
        slack_url = config['slack_url']
        res = requests.post(slack_url, data = payload)
        if 200 <= res.status_code < 300:
            print >> sys.stderr, "DEBUG receiver endpoint responded with HTTP status=%d" % res.status_code
            return True
        else:
            print >> sys.stderr, "ERROR receiver endpoint responded with HTTP status=%d" % res.status_code
            return False
    except Exception, e:
        print >> sys.stderr, "ERROR Error %s" % e
    return False
    
if __name__ == "__main__":
    if len(sys.argv) < 2 or sys.argv[1] != "--execute":
        print >> sys.stderr, "FATAL Unsupported execution mode (expected --execute flag)"
        sys.exit(1)
    else:
        settings = json.loads(sys.stdin.read())
        if not send_slack(settings):
            print >> sys.stderr, "ERROR Unable to contact slack endpoint"
            sys.exit(2)
        else:
            print >> sys.stderr, "DEBUG slack endpoint responded with OK status"

app.conf

[ui]
is_visible = 0
label = Log Slack Event Alert Action

[launcher]
author = Splunk
description = Log Slack Event Alert Action
version=6.6.0

[install]
state = enabled
is_configured = 1


alert_actions.conf

[slackcustomalert]
is_custom = 1
label = Slack Custom Alert Action
description = Send splunk event data to a Slack team room
icon_path = slacklogo.png
payload_format = json

param.trigger_reason = Saved Search [slackcustomalert] number of events($job.resultCount$)
param.result_count = $job.resultCount$
param.search_query = $job.search$
param.slack_url = 


alert_actions.conf.spec

[slackcustomalert]

param.trigger_reason = <string>
* Provided for backwards compatibility with scripted alerts
 
param.result_count = <string>
* Number of results returned 

param.search_query = <string>
* Search string


savedsearches.conf.spec

# Slack event action settings

action.slackcustomalert.param.slack_url = <string>
* Slack chat room endpoint

action.slackcustomalert.param.trigger_reason = <string>
* Provided for backwards compatibility with scripted alerts
 
action.slackcustomalert.param.result_count = <string>
* Number of results returned 

action.slackcustomalert.param.search_query = <string>
* Search string


User interface HTML file

form class="form-horizontal form-complex">
    <div class="control-group">
        <label class="control-label" for="slackcustomalert_slack_url">WebHook URL</label>
        <div class="controls">
            <textarea name="action.slackcustomalert.param.slack_url" id="slackcustomalert_slack_url" style="width: 270px; max-width: 270px; height: 60px;"></textarea>
        </div>
    </div>
    <div class="control-group">
        <div class="controls">
            <span class="help-block" style="display: block; position: static; width: auto; margin-left: 0;">
                URL needed to POST data to your Slack team room
                <br />
                <a href="https://api.slack.com/incoming-webhooks" target="_blank"
                   title="Slack Webhook Documentation">Slack Webhook Documentation<i class="icon-external"></i></a>
            </span>
        </div>
    </div>
</form>
PREVIOUS
Optional custom alert action components
  NEXT
Logger example for custom alert actions

This documentation applies to the following versions of Splunk® Enterprise: 6.6.0, 6.6.1, 6.6.2, 6.6.3, 6.6.4, 7.0.0


Was this documentation topic helpful?

Enter your email address, and someone from the documentation team will respond to you:

Please provide your comments here. Ask a question or make a suggestion.

You must be logged into splunk.com in order to post comments. Log in now.

Please try to keep this discussion focused on the content covered in this documentation topic. If you have a more general question about Splunk functionality or are experiencing a difficulty with Splunk, consider posting a question to Splunkbase Answers.

0 out of 1000 Characters