Splunk Search

Sendemail (Splunk CLI) always sends email whether results are available or not...

the_wolverine
Champion

I'm running the following search from Splunk CLI:

./splunk search 'index=test | search _raw!="scoobydoo" | sendemail to="elvis@splunk.com,john@splunk.com" subject=myresults server=mail.splunk.com' -auth etc:pass

The behavior I see is that an email is always sent whether or not results are returned by the search.

Is there some way to tell Splunk to only send email when there are results?

Tags (2)

woodcock
Esteemed Legend

Do it like this:

... | rename COMMENT1of3 AS "Splunk sendemail ALWAYS sends email, even when no results found; we address this with 2 settings:"
| rename COMMENT2of3 AS "First, we put 'null()' in 'to' header when no results; this causes 'sendemail' to error."
| rename COMMENT3of3 AS "Last, we use 'graceful=true' so that the search does not log any error for that."
| eval valueForToHeader=if(isnotnull(someFieldNameInYourResults), "YourGoodEmailGoesHere@YourCompany.com", null())
| sendemail
   to=$result.valueForToHeader$
   graceful=true
   ...
0 Karma

gkanapathy
Splunk Employee
Splunk Employee

You could consider running using the Splunk scheduler, and using Splunk's conditional script triggering rather than running the search at the CLI.

0 Karma

Stephen_Sorkin
Splunk Employee
Splunk Employee

No, Splunk doesn't provide per-result set branching logic in the search language.

I would script this using the Python SDK:

import time
import splunk
import splunk.auth   as au
import splunk.search as se

splunk.mergeHostPath('localhost:4001', True)
key = au.getSessionKey('admin', 'changeme')

d = se.dispatch('search index=_internal | head 10')

while not d.isDone:
    time.sleep(1)

if d.resultCount > 0:
    d.setFetchOption(search='sendemail to=...@splunk.com from=...@splunk.com server=ip1.splunk.com subject=myresults sendresults=true')
    r = d.results[0]

You can then run this via: splunk cmd python <scriptname>.py

A shell script may be even easier.

Get Updates on the Splunk Community!

More Ways To Control Your Costs With Archived Metrics | Register for Tech Talk

Tuesday, May 14, 2024  |  11AM PT / 2PM ET Register to Attend Join us for this Tech Talk and learn how to ...

.conf24 | Personalize your .conf experience with Learning Paths!

Personalize your .conf24 Experience Learning paths allow you to level up your skill sets and dive deeper ...

Threat Hunting Unlocked: How to Uplevel Your Threat Hunting With the PEAK Framework ...

WATCH NOWAs AI starts tackling low level alerts, it's more critical than ever to uplevel your threat hunting ...