Splunk Search

Foreach command with eval if

mah
Builder

Hi, 

I have a table like that :

teststate_Astate_Bstate_C
1okko- WARNko - ERROR
2ko- WARNokok
3okokok

 

I would like to create a field "global_state" with "done" value if all fields state_* value are "OK" , if not write "issue":

teststate_Astate_Bstate_Cglobal_state
1okko- WARNko - ERRORissue
2ko- WARNokokissue
3okokokdone

I tried this foreach but not working :

| foreach state_*  [ eval global_state= if(<<FIELD>>=="ko- WARN" OR <<FIELD>>=="ko - ERROR", "issue", "done") ]

The second condition in the if is not applied. 

Can you help me please?

Labels (1)
Tags (1)
0 Karma

PickleRick
Ultra Champion

Your issue is that you evaluate the field with each foreach call (as per the name).

So effectively you're getting only the final value. In the first row you're gonna get "issue" properly as the result because you have a "not OK" value in the last field but in the second row the global_state gets evaluated to "issue" for state_A but is immediately overwritten with "done" from state_B and then from state_C.

In such case you'd rather want to define an initial value beforehand  and then overwrite it if there is a need to do so. Like

<your search>
| eval global_state="done"
| foreach state_*
[ eval global_state=if(<<FIELD>>!="ok","issue",global_state) ]

 This way you set your global_state initially to "done" and then if you encounter any value other than "ok" in any of the state_* fields, it's getting overwritten to "issue".

richgalloway
SplunkTrust
SplunkTrust

It looks like global_state will be set based only on the last field evaluated.  See if this variation helps.

| eval ok_count = 0
| foreach state_*  [ eval ok_count = ok_count + case(<<FIELD>>=="ko-WARN", 0, <<FIELD>>=="ko-ERROR", 0, 1==1, 1) ]
| eval global_state = if(ok_count==3, "done", "issue")

 

---
If this reply helps you, an upvote would be appreciated.
0 Karma

mah
Builder

Hi @richgalloway 

Your example did not work, it gave me same issue than my search.

0 Karma

johnhua
Builder

Here are 2 ways to skin this cat.

 

| eval combined_state=TRIM(state_A)."-".TRIM(state_B)."-".TRIM(state_C)
| eval global_state=IF(combined_state="ok-ok-ok", "done", "issue")

 

| foreach state_* [| eval combined_state=MVAPPEND(combined_state, TRIM(<<FIELD>>))]
| eval combined_state=MVDEDUP(combined_state)
| eval global_state=IF(MVCOUNT(combined_state)==1 AND combined_state="ok", "done", "issue")
0 Karma
Get Updates on the Splunk Community!

Improve Your Security Posture

Watch NowImprove Your Security PostureCustomers are at the center of everything we do at Splunk and security ...

Maximize the Value from Microsoft Defender with Splunk

 Watch NowJoin Splunk and Sens Consulting for this Security Edition Tech TalkWho should attend:  Security ...

This Week's Community Digest - Splunk Community Happenings [6.27.22]

Get the latest news and updates from the Splunk Community here! News From Splunk Answers ✍️ Splunk Answers is ...