Splunk® SOAR (On-premises)

Build Playbooks with the Playbook Editor

The classic playbook editor will be deprecated in early 2025. Convert your classic playbooks to modern mode.
After the future removal of the classic playbook editor, your existing classic playbooks will continue to run, However, you will no longer be able to visualize or modify existing classic playbooks.
For details, see:

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 datapath. You can set a datapath 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 datapath for the input parameter. For details on specifying datapaths, see Specify data in your playbook.
  3. (Optional) Create a custom datapath if the datapath you need isn't available. For details on creating a custom datapath, see Custom datapaths in the Specify data in your playbook article.

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.
    1. As a best practice, do not use personally identifiable information in the names of code blocks.
    2. Custom names can use uppercase and lowercase letters A-Z, numbers 0-9, and underscores.
    3. Custom names can be up to 50 characters long.
    4. Setting or changing a custom name changes that custom name in all data paths that use it, including any 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.

Waiting within a playbook

You might need your playbook to wait for a specified amount of time, for example, to do this. In cases like this, use the no op action from the Splunk-maintained Phantom app, available on Splunkbase.

Do not use the Python sleep function in your playbook code. Doing so can lock up all of your playbook runners and reduce your automation throughput to zero.


APIs in custom code

You can include calls to the APIs within the custom code. For example, you can include one or more Vault APIs to add or access files in the Vault. For information on APIs, see Python Playbook API Reference for .

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 31 July, 2023
Run other playbooks inside your playbook in   Add custom code to your playbook with a custom function

This documentation applies to the following versions of Splunk® SOAR (On-premises): 5.1.0, 5.2.1, 5.3.1, 5.3.2, 5.3.3, 5.3.4, 5.3.5, 5.3.6, 5.4.0, 5.5.0, 6.0.0, 6.0.1, 6.0.2, 6.1.0, 6.1.1, 6.2.0, 6.2.1, 6.2.2, 6.3.0


Was this topic useful?







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