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?
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
...
You could consider running using the Splunk scheduler, and using Splunk's conditional script triggering rather than running the search at the CLI.
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.