ContextSetup
This script simplifies how you add data to Cortex XSOAR's context. Use it to set static values or to map different values to existing context paths. Instead of a value you can enter TIMESTAMP to get the current timestamp in ISO format. For example: `!ContextSetup keys=ip,src,timestamp val1=${AWS.EC2.Instances.NetworkInterfaces.PrivateIpAddress} val2="AWS" val3="TIMESTAMP" context_key="key"`.
- Type
- python
- Pack
- CortexExposureManagement
Source
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
def context_setup(keys: list[str], vals: dict) -> list[dict[str, str]]:
"""Prepares key/value mapping to prepare input into XSOAR context
:type keys: list[str]
:type vals: ``dict``
:param keys: comma separated values used for keys (columns)
:param vals: dictionary of the value assigned to keys
:return: list of dictionaries
"""
res_list = []
temp = {}
for i, key in enumerate(keys, start=1):
if vals[f"val{i}"] == "TIMESTAMP":
timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
temp[key] = timestamp
demisto.debug(f"Generated timestamp for key '{key}': {timestamp}")
else:
temp[key] = vals[f"val{i}"]
demisto.debug(f"Set key '{key}' to value: {vals[f'val{i}']}")
res_list.append(temp)
demisto.debug(f"Context setup completed. Result: {res_list}")
return res_list
""" COMMAND FUNCTION """
def context_setup_command(args: dict[str, str]) -> CommandResults:
"""
Main command that takes key/value pairs and formats them in a way that allows input into XSOAR context.
Args:
args (Dict[str, Any]): Demisto.args() object
Returns:
CommandResults: human readable message of results of !Set command.
"""
keys = argToList(args.get("keys", []))
overwrite = argToBoolean(args.get("overwrite", False))
context_key = args.get("context_key", None)
demisto.debug(f"Parsed keys: {keys}, Overwrite mode: {overwrite} Context key: {context_key}")
# dictionary or all vals
vals = {k: v for k, v in args.items() if k.startswith("val")}
demisto.debug(f"Extracted values: {vals}")
# error is keys and value numbers don't align
if len(keys) != len(vals):
error_msg = f"Number of keys ({len(keys)}) and values ({len(vals)}) needs to be the same"
demisto.debug(f"Validation error: {error_msg}")
raise ValueError(error_msg)
# Call the standalone function and get the raw response
result = context_setup(keys, vals)
if overwrite:
demisto.debug(f"Setting context key '{context_key}' with overwrite=True")
results = demisto.executeCommand("Set", {"key": context_key, "value": result})
else:
demisto.debug(f"Setting context key '{context_key}' with append=true")
results = demisto.executeCommand("Set", {"key": context_key, "value": result, "append": "true"})
return results
""" MAIN FUNCTION """
def main():
try:
return_results(context_setup_command(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
demisto.error(str(ex))
return_error(f"Failed to execute ContextSetup. Error: {str(ex)}")
""" ENTRY POINT """
if __name__ in ("__main__", "__builtin__", "builtins"):
main()
README
This script simplifies how you add data to Cortex XSOAR’s context. Use it to set static values or to map different values to existing context paths. Instead of a value you can enter TIMESTAMP to get the current timestamp in ISO format. For example:
!ContextSetup keys=ip,src,timestamp val1=${AWS.EC2.Instances.NetworkInterfaces.PrivateIpAddress} val2="AWS" val3="TIMESTAMP" context_key="key".
Script Data
| Name | Description |
|---|---|
| Script Type | python3 |
| Tags | Utility |
| Cortex XSOAR Version | 6.10.0 |
Dependencies
This script uses the following commands and scripts.
- Set
Used In
This script is used in the following playbooks and scripts.
- Cortex EM - Exposure Issue
- Cortex EM - ServiceNow CMDB
Inputs
| Argument Name | Description |
|---|---|
| keys | A comma-separated list of columns for the context key. |
| val1 | A value for the 1st key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val2 | A value for the 2nd key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val3 | A value for the 3rd key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val4 | A value for the 4th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val5 | A value for the 5th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val6 | A value for the 6th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val7 | A value for the 7th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val8 | A value for the 8th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val9 | A value for the 9th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val10 | A value for the 10th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val11 | A value for the 11th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val12 | A value for the 12th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val13 | A value for the 13th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val14 | A value for the 14th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val15 | A value for the 15th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val16 | A value for the 16th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val17 | A value for the 17th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val18 | A value for the 18th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val19 | A value for the 19th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| val20 | A value for the 20th key. (Can be a string or context path or `TIMESTAMP` to get the current timestamp in ISO format.) |
| context_key | Context key to populate. |
| overwrite | Whether to overwrite (true) or append (false) what is in the context key (default is false). |
Outputs
There are no outputs for this script.