Splunk Dev

Custom alert action created via splunk add on builder is not working

vijayameda5
New Member

Hi Team,

 

i am trying to create a custom alert action using splunk add on builder.
this alert action will have 2 inputs for rest url and token. And also take payload from output of an alert.

Here is the code i am using.

but alert action is not working and no errors too in the code.

 


import os
# encoding = utf-8

def process_event(helper, *args, **kwargs):
"""
# IMPORTANT
# Do not remove the anchor macro:start and macro:end lines.
# These lines are used to generate sample code. If they are
# removed, the sample code will not be updated when configurations
# are updated.

[sample_code_macro:start]

# The following example gets the alert action parameters and prints them to the log
rest_url = helper.get_param("rest_url")
helper.log_info("rest_url={}".format(rest_url))

token = helper.get_param("token")
helper.log_info("token={}".format(token))


# The following example adds two sample events ("hello", "world")
# and writes them to Splunk
# NOTE: Call helper.writeevents() only once after all events
# have been added
helper.addevent("hello", sourcetype="sample_sourcetype")
helper.addevent("world", sourcetype="sample_sourcetype")
helper.writeevents(index="summary", host="localhost", source="localhost")

# The following example gets the events that trigger the alert
events = helper.get_events()
for event in events:
helper.log_info("event={}".format(event))

# helper.settings is a dict that includes environment configuration
# Example usage: helper.settings["server_uri"]
helper.log_info("server_uri={}".format(helper.settings["server_uri"]))
[sample_code_macro:end]
"""

helper.log_info("Alert action test started.")
helper.log_debug("debug message")
os.system("echo end of action")

# TODO: Implement your alert action logic here

import requests
import sys, os
import json
import logging
import logging.handlers

 

def setup_logger(level):
logger = logging.getLogger("maintenance_window_logger")
logger.propagate = False # Prevent the log messages from being duplicated in the python.log file
logger.setLevel(level)
file_handler = logging.handlers.RotatingFileHandler(os.environ['SPLUNK_HOME'] + '/var/log/splunk/maintenance_window_alert.log', maxBytes=25000000, backupCount=5)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger

logger = setup_logger(logging.DEBUG)

def create_maintenance_window(title,entity_key,start,end):
logger.debug("calling create_maintenance_window()")
url="https://xxxxx:8089/servicesNS/nobody/SA-ITOA/maintenance_services_interface/maintenance_calendar"
headers = {'Authorization':'Bearer xxxxxxxxxxxx'}
data = {"title":title,"start_time":start,"end_time":end,"objects":[{"object_type":"entity","_key":entity_key}]}
logger.debug(data)
response = requests.post(url,headers=headers,json=data,verify=True)
logger.debug(response)
data=response.json()
logger.debug(data)
logger.debug("completing create_maintenance_window()")
return data
def validate_payload(payload):
if not 'configuration' in payload:
log("FATAL Invalid payload, missing 'configuration'")
return False
config = payload.get('configuration')

title = config.get('title')
if not title:
log("FATAL Validation error: Parameter `title` is missing or empty")
return False

entity_key = config.get('entity_key')
if not entity_key:
log("FATAL Validation error: Parameter `entity_key` is missing or empty")
return False

start = config.get('start')
if not start:
log("FATAL Validation error: Parameter `start` is missing or empty")
return False

end = config.get('end')
if not end:
log("FATAL Validation error: Parameter `end` is missing or empty")
return False

return True

def main():
logger.debug("calling main()")
if len(sys.argv) > 1 and sys.argv[1] == "--execute":
logger.debug(sys.argv)
payload = json.loads(sys.stdin.read())
if not validate_payload(payload):
sys.exit(ERROR_CODE_VALIDATION_FAILED)
logger.info(payload)
config = payload.get('configuration')
title = config.get('title')
entity_key=config.get('entity_key')
start=config.get('start')
end=config.get('end')
logger.debug(title)
logger.debug(start)
logger.debug(end)
logger.debug(entity_key)
data = create_maintenance_window(title,entity_key,start,end)
logger.debug("completing main()")


if __name__ == "__main__":
main()


#return 0

0 Karma
Get Updates on the Splunk Community!

Introducing the Splunk Community Dashboard Challenge!

Welcome to Splunk Community Dashboard Challenge! This is your chance to showcase your skills in creating ...

Wondering How to Build Resiliency in the Cloud?

IT leaders are choosing Splunk Cloud as an ideal cloud transformation platform to drive business resilience,  ...

Updated Data Management and AWS GDI Inventory in Splunk Observability

We’re making some changes to Data Management and Infrastructure Inventory for AWS. The Data Management page, ...