Splunk® SOAR (On-premises)

Build Playbooks with the Playbook Editor

Acrobat logo Download manual as PDF


This documentation does not apply to the most recent version of Splunk® SOAR (On-premises). For documentation on the most recent version, go to the latest release.
Acrobat logo Download topic as PDF

Add custom code to your playbook with the code block

Add custom Python code to a Code block. Code blocks enable you to expand the kinds of processing performed in a playbook, such as adding custom input parameters and output variables.

Add a code block to your playbook

Perform the following steps to add a Code block to a playbook.

  1. Drag and drop the half-circle icon attached to any existing block in the editor. Select a Code block from the menu that appears.
  2. Configure input parameters and output variables. See Add input parameters to a code block and Add output variables to a code block.
  3. Click the Python Playbook Editor to open it and add your custom code. See Use the Python Playbook Editor to add custom code.
  4. Click Done.

Add input parameters to a code block

Input parameters represent a data path. You can set a data path from any valid blocks upstream, artifact data, and container data.

To create or remove an input parameter, perform the following steps:

  1. Click the + Input Parameter icon to add an input parameter. The index of parameters starts at zero.
  2. Click in the Select Parameter box to set the properties for the input parameter. You can select between artifact and event properties and can search in the search box for a specific property. Click Enter to go to the next result or use the Up and down result icons icons to navigate results. You can also expand or collapse the lists by using the Expand or collapse list icons icons.

Add output variables to a code block

Output variables are usable as inputs in other downstream blocks, such as Action, Utility, Filter, Decision, Format and Prompt blocks. The name of an output variable becomes <block_name>__<variable_name> in the auto-generated section of the playbook code. Give your output variables clear and meaningful names in your custom code so that you can distinguish them from one another.

Follow these steps to add an output variable:

  1. Click + Output Variable to add an output variable.
  2. Type a name to set the name for, or rename the output variable.

The following example shows both custom code and how outputs are saved:

def format_login(action=None, success=None, notable=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, **kwargs):
    oar.debug("format_login() called")

    format_login__login_table = None

    ################################################################################
    ## Custom Code Start
    ################################################################################

    # format the output into JIRA's markup language for rendering a table
    format_login__login_table = "|| output of '/usr/bin/last -a' ||\n"
    last_lines = get_user_1_result_item_0[0].split('\n')
	    for line in last_lines:
    	          format_login__login_table += "| {} |\n".format(line)
        
	oar.debug("table of logins for jira:")
	oar.debug(format_login__login_table)

    ################################################################################
    ## Custom Code End
    ################################################################################

    oar.save_run_data(key="format_login:login_table", value=json.dumps(format_login__login_table))

    return

Use custom names to easily identify and arrange your code blocks

You might want to set a custom name for a block to help you distinguish between blocks.

To set a custom name for the Code block, follow these steps:

  1. Click the Info tab from the configuration panel of the Code block.
  2. Enter a name in the Custom Name box. Custom names can use uppercase and lowercase letters A-Z, numbers 0-9, and underscores. Setting or changing a custom name changes that custom name in all data paths that use it, including generated and custom code.
  3. Enter a Description in the Description (code comment) box to act as a description of your code.
  4. Enter a note in the Notes (block tooltip) box to act as a tooltip for the Code block.

You can also configure Advanced settings for a Code block. You can use Join Settings and Scope, in a Code block. For more information on these settings, see Advanced settings.

Use the Python Playbook Editor to add custom code

You can use the Python Playbook Editor to add custom code to any existing block types. To add custom code to a block, follow these steps:

  1. Click on or create a block to open the configuration panel.
  2. Click Python Playbook Editor.
  3. Enter your custom code.

If you add or edit code outside of the Custom Code Start and Custom Code End sections, the configuration panel for that block is disabled.

Example: Use a custom function to process multiple artifacts and build a parameter list

The following example shows a custom function used to process multiple artifacts in order to build a parameter list.

def dbsearch(action=None, success=None, notable=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, **kwargs):
    oar.debug("dbsearch() called")

    ################################################################################
    ## Custom Code Start
    ################################################################################

    # Write your custom code here...
    customernamestr = name_value
    parameters = []

    # Loop over the notable event data structure (a list of lists, with each inner list of length three)
    for messagestr, start_time, artifact_id in notable_event_data:
        startdatestr = start_time.split(' ')[0]
        starttimestr = start_time.split(' ')[1]

        # Build the SQL
        if 'groupName:' in messagestr:
            hostgroupstr = messagestr.split('/')[0].replace('groupName:', '')
            hoststr = messagestr.split('/')[1].split(':')[1]
            sqlstr = "select COUNT(*) as cnt from schedule where customer = '"+ customernamestr +"' and startdate <= '"+ startdatetimestr +"' and enddate >= '"+ startdatetimestr +"' and ("
            for group in hostgroupstr.split('/'):
                sqlstr = sqlstr + "kyoten like '%"+ group +"%' or reason like '%"+ group +"%' or "
            sqlstr = sqlstr + "kyoten like '%"+ hoststr +"%' or reason like '%"+ hoststr +"%')"
            
        else:
            hoststr = messagestr.split(':')[0]
            sqlstr = "select COUNT(*) as cnt from schedule where customer = '"+ customernamestr +"' and  (kyoten like '%"+ hoststr +"%' or reason like '%"+ hoststr +"%') and startdate <= '"+ startdatetimestr +"' and enddate >= '"+ startdatetimestr +"'"

        # Update the parameter list
        # There should be one parameter per item in the container_data variable
        # There should be one item in the container_data variable per artifact
        # Thus, there should be one parameter per artifact
        parameters.append({
            'query': sqlstr,
            'format_vars': "",
            'no_commit': False,
        })

    oar.act("run query", parameters=parameters, connector_configs=['mysql'], callback=filter_2, name="SearchDB")

    ################################################################################
    ## Custom Code End
    ################################################################################

    return
Last modified on 22 September, 2021
PREVIOUS
Run other playbooks inside your playbook in
  NEXT
Add additional functionality to your playbook in using the Utility block

This documentation applies to the following versions of Splunk® SOAR (On-premises): 5.0.1


Was this documentation topic helpful?


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