0

Dispatch saved search

by
Published today

Run a saved search now and return the search ID (sid) of the job it starts. Take owner and app from the entry's acl in List saved searches.

Script splunk Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 3 hours ago
1
//native
2

3
/**
4
 * Dispatch saved search
5
 * Run a saved search now and return the search ID (sid) of the job it starts. Take owner and app from the entry's acl in List saved searches.
6
 */
7
export async function main(
8
  auth: RT.Splunk,
9
  name: string,
10
  owner: string,
11
  app: string,
12
  earliest_time: string | undefined,
13
  latest_time: string | undefined,
14
  trigger_actions: boolean | undefined,
15
  args: { [key: string]: any } | undefined
16
) {
17
  const base = auth.base_url.replace(/\/+$/, "")
18
  const url = `${base}/servicesNS/${encodeURIComponent(owner)}/${encodeURIComponent(app)}/saved/searches/${encodeURIComponent(name)}/dispatch`
19

20
  const body = new URLSearchParams({
21
    output_mode: "json",
22
    trigger_actions: String(trigger_actions === true),
23
  })
24
  if (earliest_time) body.append("dispatch.earliest_time", earliest_time)
25
  if (latest_time) body.append("dispatch.latest_time", latest_time)
26
  for (const [k, v] of Object.entries(args ?? {})) {
27
    if (v != null) {
28
      body.append(
29
        `args.${k}`,
30
        typeof v === "object" ? JSON.stringify(v) : String(v)
31
      )
32
    }
33
  }
34

35
  const response = await fetch(url, {
36
    method: "POST",
37
    headers: {
38
      Authorization: `Bearer ${auth.token}`,
39
      "Content-Type": "application/x-www-form-urlencoded",
40
      Accept: "application/json",
41
    },
42
    body,
43
  })
44

45
  if (!response.ok) {
46
    throw new Error(`${response.status} ${await response.text()}`)
47
  }
48

49
  return await response.json()
50
}
51