Snippet Actions

Download this manual as a PDF file

This section describes how to create an action policy that executes a snippet, which is a custom-written Python program.

Use the following menu options to navigate the SL1 user interface:

  • To view a pop-out list of menu options, click the menu icon ().
  • To view a page containing all of the menu options, click the Advanced menu icon ().

Creating an Action Policy that Executes a Snippet

In the Action Policy Editor page, if you selected the Action Type of Run a Snippet, the new action policy will execute a custom-written Python program. If the action policy is aligned with an automation policy (i.e., if the action policy is included in the definition of an automation policy), and the criteria in the automation policy are met, SL1 will execute the Snippet. Snippet action policies can only include object types that can be serialized and deserialized by JSON data formats.

For increased flexibility and connectivity, you can specify whether the Snippet should be executed by the Database Server or by the Data Collector. In some cases, a device might not accept connections from the Database Server or may not be "visible" from the Database Server. In these situations, you can specify that the Snippet be executed by the Data Collector.

NOTE: For SL1 systems that are using an All-In-One Appliance, you cannot choose to execute a policy on a Database Server or a Data Collector. All policies will be executed on the All-In-One Appliance.

An action policy that executes a Snippet is useful when you want to run detailed network diagnostics on a device. For example, if SL1 generates an event saying that a device is not responding to ping, you could run a Snippet that performs a traceroute and specify that SL1 execute the Snippet from the Data Collector server. You would then execute a traceroute from the Data Collector to the device, store the results in the variable %_ EM7_ RESULT_%, and use that variable to pass the results to another action policy.

An action policy that executes a Snippet is useful when you want to perform some automated steps on the device to resolve a problem. For example, when a specific event is triggered, you could run a Snippet that turns on debugging on the remote device and copies the logs to another remote device.

NOTE: Snippets are developed using the Python programming language. To create a Snippet Action Policy, you must be familiar with the programming techniques and data structures of the Python language.

In the Action Policy Editor page, if you select the Action Type of Run a Snippet, you must supply values in the fields specified in Action Policies and also in the following fields:

  • Snippet Credential. Credential that allows SL1 to execute the Snippet code on the external device. Usually, these are credentials of type "Basic". The list of credentials is filtered to include only those credentials to which you have access.

If this field has already been set to a credential to which you do not have access, this field will display the value Restricted Credential. If you set this field to a different credential, the entry for Restricted Credential will be removed from the list in this field; you will not be able to re-align the device with the Restricted Credential.

NOTE: Your organization membership(s) might affect the list of credentials you can see in the Snippet Credential field.

  • Action Run Context. This option is not available on All-In-One Appliances. Specifies whether the action will be executed on the Database Server or on the Data Collector. The Choices are:
  • Database. Execute the action from the Database Server.
  • Collector. Execute the action from the Data Collector associated with the device. This is useful when a device doesn't accept connections from the Database Server or may not be "visible" from the Database Server.
  • Execution Environment. Select the execution environment to which you want to align the action. An execution environment is an on-demand Python environment that contains the supporting modules, code, scripts, directories, and files (packaged in ScienceLogic Libraries) for the snippet. An execution environment includes its own installation directories, doesn't share libraries with other environments, and allows granular control of dependencies, versions, and permissions. The default execution environment is System.This list also shows the Python version of each selectable execution environment. For more information, see the section on Managing Execution Environments.
  • Snippet Code. Python code for the Snippet.

NOTE: If you selected Code Highlighting in the Account Preferences page (Preferences > Account > Preferences), the code in the Snippet Code field appears with syntax highlighting.

Writing Snippet Code

The following sections describe the functions and variables that are available to python code for automation actions of type "snippet".

Snippet Functions

SL1 automatically imports the module em7_snippets. This module includes the following functions that you can use within your Snippet code:

  • import logging

    Best practices for logging in Dynamic Applications and run book automation snippets and ScienceLogic Libraries is to use basic pythonic logging under the silo namespace and to let the system handle routing and storage. Logging directly to the filesystem and using print statements should be avoided.

    To log custom messages from a Dynamic Application or run book snippet:

    import logging

     

    logger = logging.getLogger("silo." + "my_custom_id")

    logger.info("This will go to /var/log/sl1/sl1.log.")

    To log custom messages from ScienceLogic Libraries:

    import logging

     

    logger = logging.getLogger("silo." + __name__)

    logger.info("This will go to /var/log/sl1/sl1.log.")

    If the ScienceLogic Library is already in the silo namespace, then prepending the token is unnecessary. For example, a package called silo-apps that is imported using import silo.apps is already in the namespace. In this example library, logging can be added without the silo prepended:

    import logging

     

    logger = logging.getLogger(__name__)

    logger.info("This will go to /var/log/sl1/sl1.log.")

    Snippet Dynamic Applications run in debug mode with pythonic logging will also output to the screen. Use this type of logging in place of “print” statements.

    Logs are written to /var/log/sl1/sl1.log. SL1 version 11.3.0 and earlier wrote logs to /var/log/sl1/snippet.log. Do not log directly to the filesystem or custom locations.

  • em7_snippets.generate_alert(message, xid, xtype, yid, ytype, yname, value, threshold).

This function allows you to generate an alert from a Snippet action policy. You can define an event based on the alert; the event must have a Source of API and use pattern matching to match the alert. The arguments for the function are:

  • message. Required argument. The message text for the alert.
  • xid. Required argument. The entity to associate with the alert. Supply the numeric ID of an entity. For example, if you supply '1' in the xtype argument, supply a device ID in this argument.
  • xtype. Specifies the type of ScienceLogic element associated with the alert. Supply one of the following integer values:
  • 0. Organization
  • 1. Device
  • 2. Asset
  • 4. Network
  • 5. Interface
  • 6. Vendor
  • 7. User Account
  • 8. Virtual Interface
  • 9. Device Group
  • 10. IT Service
  • 11. Ticket
  • 12. Quality of Service Object
  • 13. Discovery Session
  • 14. Business Service
  • 15. Business Service - IT Service
  • 16. Device Service
  • 20. Aggregate Service
  • yid = value. The sub-entity to associate with the alert. Supply the numeric ID of a sub-entity. For example, if you supply '3' in the ytype argument, supply a file system ID in this argument.
  • ytype = value. Optional argument. The type of sub-entity for which you specified an ID in the yid argument. Supply one of the following integer values:
  • 9. News Feed (if xtype is 0) or Process (if xtype is 1).
  • 1. CPU. Can be specified only if xtype is 1 (Device).
  • 2. Disk. Can be specified only if xtype is 1 (Device).
  • 3. File System. Can be specified only if xtype is 1 (Device).
  • 4. Memory. Can be specified only if xtype is 1 (Device).
  • 5. Swap. Can be specified only if xtype is 1 (Device).
  • 6. Hardware Component. Can be specified only if xtype is 1 (Device).
  • 7. Interface. Can be specified only if xtype is 1 (Device).
  • 10. Port. Can be specified only if xtype is 1 (Device).
  • 11. Windows Service. Can be specified only if xtype is 1 (Device).
  • 12. Web Content. Can be specified only if xtype is 1 (Device).
  • 13. Email Monitor. Can be specified only if xtype is 1 (Device).
  • 14. DNS. Can be specified only if xtype is 1 (Device).
  • 15. RSS. Can be specified only if xtype is 1 (Device).
  • 16. Quality of Service. Can be specified only if xtype is 1 (Device).
  • yname = value. Optional argument. The name of the sub-entity for which you specified an ID in the yid argument.
  • value= string. Optional argument. A value that will be passed with the alert message. This value is available in the %V substitution character for event policies.
  • threshold= string. Optional argument. A threshold value that will be passed with the alert message. This threshold value is available in the %T substitution character for event policies.

For example:

em7_snippets.generate_alert('Attempted File System Cleanup', '60', '1', '150', '3')

will generate an alert with the message "Attempted File System Cleanup" associated with the file system with ID 150 on the device with ID 60.

Snippet Variables

A Snippet can use the following global Snippet variables:

  • EM7_LAST_RESULT. Variable that contains the results from the previous Action Policy. The output of this variable is the same as the output of EM7_LAST_RESULT_LIST except it outputs a single object from the list.
  • EM7_RESULT. Variable in which to store the results from the current Snippet Action Policy. This variable is used to populate the variable %_EM7_RESULT_%.
  • A Snippet can access the standard replacement variables (described in the appendix on Variables) by using the global dictionary EM7_VALUES. The syntax is:

EM7_VALUES['variable']

For example, to access the variable that contains a device's IP address:

EM7_VALUES['%a']

  • EM7_ACTION_CRED. Variable that contains a dictionary of values from the credential for this action policy, specified in the Snippet Credential field.
  • EM7_DEVICE_CRED. Variable that contains a dictionary of values from the credential used to discover the device where the event occurred (that is, the event specified in the automation policy that triggered the current action policy). If the triggering event is not aligned with a device, this variable does not contain a value.
  • EM7_DYNAMIC_APP_CREDS['Dynamic_Application'_ID']. Variable that returns a dictionary of values from the credential associated with the specified Dynamic Application on the device (where the triggering event occurred). The syntax is:

EM7_DYNAMIC_APP_CREDS['Dynamic_Application_ID'] 

For example, to access the dictionary of values for the credential assigned to the Dynamic Application with the ID of "17", you would enter:

EM7_DYNAMIC_APP_CREDS[17]

This would return the dictionary of values for the credential that allows the Dynamic Application with an ID of "17" to run for the device where the triggering event occurred.

A returned value can be used in a Run Book Automation snippet to set a value. For example, the following statement will set the value in the key "cred_user" to variable "user" within the snippet:

user = EM7_DYNAMIC_APP_CREDS['Dynamic_Application's_ID']

Credential Dictionary Structure

Several elements in the credential dictionary are common to all credential types, and each credential type (other than Basic/Snippet) has unique elements that appear only in the credential dictionary for that credential type. The following elements are common to every type of credential dictionary:

  • cred_id. Integer. Unique credential ID.
  • cred_type. Integer. Type of credential .
    • 1 SNMP. SNMP credentials allow SL1 to access SNMP data on a managed device.
    • 2 DB. Database credentials allow SL1 to access data on a database on a managed device.
    • 3 SOAP/XML. SOAP/XML credentials allow SL1 to access a web server on a managed device.
    • 4 LDAP. LDAP or Active Directory credentials allow SL1 to access data on an LDAP server or Active Directory server.
    • 5 Snippet. Basic/Snippet credentials define standard authentication parameters, but are not tied to a specific authentication protocol.
    • 6 SSH. SSH/Key credentials specifies the hostname or IP address of the system you want to monitor, the port number used to access that system, and the private key used for authentication.
    • 7 PowerShell. PowerShell credentials allow Dynamic Applications to retrieve data from Microsoft devices.

    NOTE: For more information, the section on Credential Management.

  • cred_host. String. Host name or IP address (%D substitution string).
  • cred_port. Integer. TCP/IP port for connections.
  • cred_pwd. String. Password (encrypted in the database, stored as clear text in the dictionary).
  • cred_user. String. Username.
  • cred_timeout. Integer. Timeout in milliseconds.

The following elements are unique for SNMP credentials:

  • snmp_version. Integer. SNMP version, values 1, 2, 3.
  • snmp_ro_community. String. Read-only community string.
  • snmp_rw_community. String. Read/Write community string.
  • snmp_retries. Integer. Number of retries.
  • snmpv3_auth_proto. String. V3 auth. protocol,. Can be either MD5 or SHA.
  • snmpv3_sec_level. String. V3 security. Can be noAuthNoPriv, AuthNoPriv, or AuthPriv.
  • snmpv3_priv_proto. String. V3 privacy protocol. Can be : DES or AES.
  • snmpv3_priv_pwd. String. V3 password encrypted in the database and stored as clear text in the dictionary.
  • snmpv3_context. String. V3 context.

The following elements are unique for Database credentials:

  • db_type. Integer.
    • 1 MySQL
    • 2 MSSQL
    • 3 Oracle
    • 4 Postgress
    • 5 DB2
    • 6 Sybase
    • 7 Informix
    • 8 Ingress).

  • db_name. String. Initial database name.
  • db_sid. String. Database SID (Oracle only).
  • db_connect. String. Database connect string (Oracle only).

The following elements are unique for SOAP/XML credentials:

  • curl_url. String. URL.
  • curl_proxy_ip. String. Proxy server IP address.
  • curl_proxy_port. Integer. Proxy server TCP/IP port.
  • curl_proxy_acct. String. Proxy server account.
  • curl_proxy_passwd. String. Proxy server password.
  • curl_encoding. String. Encoding method (eg text/xml).
  • curl_post_or_get. Integer. HTTP method 0 – GET, 1- POST.
  • curl_http_version. HTTP version: 10 = 1.0, 11 = 1.1.
  • curl_request_sub_1. String. Substitution value to substitute into Snippet code.
  • curl_request_sub_2. String. Substitution value to substitute into Snippet code.
  • curl_request_sub_3. String. Substitution value to substitute into Snippet code.
  • curl_request_sub_4. String. Substitution value to substitute into Snippet code.
  • curl_headers. List of Strings. Each string is a HTTP key/value pair.
  • curl_opts. Dictionary of Curl options comprising a series of pairs of string key and corresponding string value.

Using the Results of Previous Actions

EM7_LAST_RESULT_LIST Variable

The variable EM7_LAST_RESULT_LIST allows you to use the results from a previous Action Policy in the current Action Policy. The results of an action are available only to other actions within the same automation policy. For example, if an automation policy includes three action policies, you could pass the results from the first action policy to the third action policy. To specify the action policy for which you want to retrieve the results, you include the index number for that action policy. Index numbers start at zero ("0").

Each index in the EM7_LAST_RESULT_LIST variable is a list with the following structure:

('success', 'type', 'result', 'metrics', 'message')

Where:

  • success. Contains "True" if the specified Action Policy was successful and "False" if the specified Action Policy was not successful. To assign this value to a local variable, the syntax is:

success = EM7_LAST_RESULT_LIST[i].success

where success is the variable in which to store the returned value and i is the index number for the Action Policy, for example "1" for the second Action Policy.

  • type. Numeric ID for the action type. Possible values are:
  • 0. Send An Email Notification
  • 1. Send an SNMP Trap
  • 2. Create a New Ticket
  • 3. Send an SNMP Set
  • 5. Run a Snippet
  • 6. Execute an SQL Query
  • 7. Update an Existing Ticket

To assign this value to a local variable, the syntax is:

type = EM7_LAST_RESULT_LIST[i].type

where type is the variable in which to store the returned value and i is index number for the Action Policy, for example "1" for the second Action Policy.

  • result. Returns the result of the specified Action Policy and is usually a Python dict object. To assign this value to a local variable, the syntax is:

result = EM7_LAST_RESULT_LIST[i].result

where result is the variable in which to store the returned value and i is the index number for the Action Policy, for example "1" for the second Action Policy.

  • metrics. Returns metrics about the specified Action Policy.
  • If the specified Action Policy is not of type "Run a Snippet", this value will be NONE.
  • If the specified Action Policy is of type "Run a Snippet", this value contains the following list structure:

('start_time', 'end_time', 'duration', 'mem', cpu_sys', 'cpu_user')

To assign this value to a local variable, the syntax is:

metrics = EM7_LAST_RESULT_LIST[i].metrics.end_time

where metrics is the variable in which to store the returned value and i is the index number for the Action Policy, for example "1" for the second Action Policy.

This syntax returns the "end_time" metric. To view another metric, substitute its name for "end_time". The name of each metric is listed above, in the description of the data structure.

  • message. An informational message. If the success parameter returns False, this parameter returns the error message. To assign this value to a local variable, the syntax is:

message = EM7_LAST_RESULT_LIST[i].message

where message is the variable in which to store the returned value and i is the index number for the Action Policy, for example "1" for the second Action Policy.

For example, suppose we included the following Snippet code in an action of type "Run a Snippet". Suppose our current Action (the one that includes the code) is the fourth action in the Automation Policy. Suppose we want to gather information about the third action (which has an index of "2"). Suppose the third action created a new ticket. Suppose the snippet included the following local variable assignment statements:

success = EM7_LAST_RESULT_LIST[2].success

type = EM7_LAST_RESULT_LIST[2].type

result = EM7_LAST_RESULT_LIST[2].result

metrics = EM7_LAST_RESULT_LIST[2].metrics

message = EM7_LAST_RESULT_LIST[2].message

The contents of the local variables might be:

success: true

type: 2

result: {'tid': 814}

metrics: metrics is None

message: Created ticket 814

EM7_LAST_RESULT Variable

The EM7_LAST_RESULT variable allows you to use the last object returned from the previous Action Policy in the current Action Policy. With this variable, the results of the last action are available only to the next action. The objects available are the same as with EM7_LAST_RESULT_LIST but are presented as a single object and not as a list. EM7_LAST_RESULT returns the following:

('success', 'type', 'result', 'metrics', 'message')

Where:

  • success. Contains "True" if the specified Action Policy was successful and "False" if the specified Action Policy was not successful. To assign this value to a local variable, the syntax is as follows:

success = EM7_LAST_RESULT.success

where success is the variable in which to store the returned value

  • type. Numeric ID for the action type. Possible values are as follows:
  • 0. Send An Email Notification
  • 1. Send an SNMP Trap
  • 2. Create a New Ticket
  • 3. Send an SNMP Set
  • 5. Run a Snippet
  • 6. Execute an SQL Query
  • 7. Update an Existing Ticket

To assign this value to a local variable, the syntax is as follows:

type = EM7_LAST_RESULT.type

where type is the variable in which to store the returned value.

  • result. Returns the result of the specified Action Policy and is usually a Python dict object. To assign this value to a local variable, the syntax is as follows:

result = EM7_LAST_RESULT.result

where result is the variable in which to store the returned value.

  • metrics. Returns metrics about the specified Action Policy.
  • If the specified Action Policy is not of type "Run a Snippet", this value will be NONE.
  • If the specified Action Policy is of type "Run a Snippet", this value contains the following list structure:

('start_time', 'end_time', 'duration', 'mem', cpu_sys', 'cpu_user')

To assign this value to a local variable, the syntax is as follows:

metrics = EM7_LAST_RESULT.metrics.end_time

where metrics is the variable in which to store the returned value.

This syntax returns the "end_time" metric. To view another metric, substitute its name for "end_time". The name of each metric is listed above, in the description of the data structure.

  • message. An informational message. If the success parameter returns False, this parameter returns the error message. To assign this value to a local variable, the syntax is as follows:

message = EM7_LAST_RESULT.message

where message is the variable in which to store the returned value.

For example, suppose we included the following Snippet code in our last action, which is of type "Run a Snippet". Suppose the snippet included the following local variable assignment statements:

success = EM7_LAST_RESULT.success

type = EM7_LAST_RESULT.type

result = EM7_LAST_RESULT.result

metrics = EM7_LAST_RESULT.metrics

message = EM7_LAST_RESULT.message

The contents of the local variables might be:

success: true

type: 2

result: {'tid': 814}

metrics: metrics is None

message: Created ticket 814