Here's a Python automation script for XSOAR that adds a subplaybook to the current incident's workplan and executes it as an adhoc task:
Step 1: Create the Automation Script
Navigate to Settings > Integrations > Automations and click + New Automation.
- Name:
RunSubplaybook (or your preferred name)
- Description: Adds and executes a subplaybook as an adhoc task in the current incident
- Type: Python
- Tags: utility, playbook, adhoc
- Code: Paste the following Python code:
from CommonServerPython import *
def validate_playbook_exists(playbook_name):
"""
Validates if the playbook exists in the system
"""
try:
# Get all playbooks
res = demisto.executeCommand('getPlaybooks', {})
if isError(res):
return False, f"Failed to fetch playbooks: {get_error(res)}"
playbooks = res[0].get('Contents', [])
# Check if the playbook exists (case-insensitive)
playbook_names = [pb.get('name', '') for pb in playbooks]
# Try exact match first
if playbook_name in playbook_names:
return True, playbook_name
# Try case-insensitive match
for pb_name in playbook_names:
if pb_name.lower() == playbook_name.lower():
return True, pb_name
return False, f"Playbook '{playbook_name}' not found. Available playbooks: {', '.join(sorted(playbook_names))}"
except Exception as e:
return False, f"Error validating playbook: {str(e)}"
def add_and_run_subplaybook(playbook_name, task_name=None, task_description=None):
"""
Adds a subplaybook to the current incident and executes it
"""
try:
# Get current incident ID
incident = demisto.incident()
if not incident:
return_error("No incident context found. This script must be run within an incident.")
incident_id = incident.get('id')
if not incident_id:
return_error("Could not retrieve incident ID.")
# Validate playbook exists
is_valid, result = validate_playbook_exists(playbook_name)
if not is_valid:
return_error(result)
# Use the correctly cased playbook name
playbook_name = result
# Set task name if not provided
if not task_name:
task_name = f"Adhoc: {playbook_name}"
# Set task description if not provided
if not task_description:
task_description = f"Adhoc execution of playbook: {playbook_name}"
demisto.results(f"Adding playbook '{playbook_name}' to incident {incident_id}...")
# Add the playbook as a task to the incident
add_task_args = {
'incidentId': incident_id,
'name': task_name,
'type': 'playbook',
'playbookId': playbook_name,
'description': task_description,
'sla': 0, # No SLA for adhoc tasks
'slaReminder': 0
}
# Execute the addTask command
res = demisto.executeCommand('addTask', add_task_args)
if isError(res):
return_error(f"Failed to add playbook task: {get_error(res)}")
# Get the task ID from the response
task_data = res[0].get('Contents', {})
task_id = task_data.get('id')
if not task_id:
return_error("Task was created but could not retrieve task ID.")
# Build success message with details
success_msg = f"""
## ✅ Subplaybook Successfully Added and Started
**Playbook:** {playbook_name}
**Task Name:** {task_name}
**Task ID:** {task_id}
**Incident ID:** {incident_id}
**Status:** The playbook has been added to the Work Plan and will execute automatically.
You can monitor its progress in the Work Plan tab.
"""
# Return markdown formatted success message
return_results({
'ContentsFormat': formats['markdown'],
'Type': entryTypes['note'],
'Contents': success_msg
})
# Also set context data for potential use by other scripts
demisto.setContext('AdhocPlaybook', {
'playbookName': playbook_name,
'taskId': task_id,
'taskName': task_name,
'incidentId': incident_id,
'timestamp': datetime.now().isoformat()
})
except Exception as e:
return_error(f"An error occurred while adding the subplaybook: {str(e)}")
def main():
try:
args = demisto.args()
# Get arguments
playbook_name = args.get('playbookName', '').strip()
task_name = args.get('taskName', '').strip()
task_description = args.get('taskDescription', '').strip()
# Validate required arguments
if not playbook_name:
return_error("Missing required argument: 'playbookName'. Please specify the name of the playbook to run.")
# Add and run the subplaybook
add_and_run_subplaybook(playbook_name, task_name, task_description)
except Exception as e:
return_error(f"An error occurred in main: {str(e)}")
if __name__ in ('__main__', '__builtin__', 'builtins'):
main()
Step 2: Save and Test the Automation
- Click Save to save the automation script
- Make sure you're in an active incident before testing
Step 3: Using the Script from the War Room
Once the automation is saved, you can use it from the War Room in several ways:
Basic Usage:
!RunSubplaybook playbookName="Your Playbook Name"
With Custom Task Name:
!RunSubplaybook playbookName="Enrich Indicators" taskName="Manual Enrichment"
With Full Options:
!RunSubplaybook playbookName="Threat Hunting Playbook" taskName="Hunt for IOCs" taskDescription="Running threat hunting based on new intelligence"
Features of the Script:
-
Playbook Validation: The script validates that the specified playbook exists before attempting to add it. It supports case-insensitive matching.
-
Automatic Task Naming: If you don't specify a task name, it automatically creates one using the format "Adhoc: [Playbook Name]"
-
Error Handling: Comprehensive error handling for common issues like:
- Running outside of an incident context
- Non-existent playbooks
- API failures
-
Context Storage: The script stores information about the added task in the context under AdhocPlaybook for reference by other automations if needed.
-
Markdown Output: Returns a nicely formatted success message showing:
- Playbook name
- Task name and ID
- Incident ID
- Confirmation that the playbook is executing
Important Notes:
-
Permissions: The user running this command needs appropriate permissions to modify incidents and add tasks.
-
Playbook Execution: When a playbook is added as a task to an active incident, XSOAR automatically starts executing it. You don't need to manually trigger the execution.
-
Playbook Inputs: If the subplaybook requires inputs, you'll need to configure them in the playbook itself to use incident fields or set default values, as this script doesn't handle passing custom inputs to the subplaybook.
-
Work Plan View: After running the script, you can switch to the "Work Plan" tab in the incident to see the newly added playbook task and monitor its progress.
Advanced Usage - Creating an Alias:
For frequently used playbooks, you can create command aliases in the War Room. For example, if you frequently run an "Enrich Indicators" playbook, you could create an alias:
/alias enrichnow !RunSubplaybook playbookName="Enrich Indicators"
Then you can simply type enrichnow in the War Room to run that playbook.
This script provides a flexible way to dynamically add and execute playbooks during incident response, making it easier to adapt your response based on the specific needs of each incident.