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!

Announcing Scheduled Export GA for Dashboard Studio

We're excited to announce the general availability of Scheduled Export for Dashboard Studio. Starting in ...

Extending Observability Content to Splunk Cloud

Watch Now!   In this Extending Observability Content to Splunk Cloud Tech Talk, you'll see how to leverage ...

More Control Over Your Monitoring Costs with Archived Metrics GA in US-AWS!

What if there was a way you could keep all the metrics data you need while saving on storage costs?This is now ...