0

List maintenances

by
Published today

List maintenance windows filtered by name, host or host group.

Script zabbix Verified

The script

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

3
/**
4
 * List maintenances
5
 * List maintenance windows (maintenance.get) by exact name, a case-insensitive name substring, host IDs or host group IDs, with their hosts, host groups and time periods. The Zabbix API has no offset: has_more tells you the limit cut the result, so narrow the filters or raise the limit.
6
 */
7
export async function main(
8
  auth: RT.Zabbix,
9
  name: string | undefined,
10
  name_search: string | undefined,
11
  host_ids: string[] | undefined,
12
  group_ids: string[] | undefined,
13
  limit: number | undefined
14
) {
15
  const max = Math.max(1, limit || 100)
16
  const params: { [key: string]: any } = {
17
    output: "extend",
18
    selectHosts: ["hostid", "host", "name"],
19
    selectHostGroups: ["groupid", "name"],
20
    selectTimeperiods: "extend",
21
    sortfield: "maintenanceid",
22
    limit: max + 1,
23
  }
24
  if (name) {
25
    params.filter = { name }
26
  }
27
  if (name_search) {
28
    params.search = { name: name_search }
29
  }
30
  if (host_ids?.length) {
31
    params.hostids = host_ids
32
  }
33
  if (group_ids?.length) {
34
    params.groupids = group_ids
35
  }
36

37
  const maintenances = await call(auth, "maintenance.get", params)
38
  return {
39
    maintenances: maintenances.slice(0, max),
40
    has_more: maintenances.length > max,
41
  }
42
}
43

44
async function call(auth: RT.Zabbix, method: string, params: any) {
45
  const response = await fetch(
46
    `${auth.base_url.replace(/\/+$/, "").replace(/\/api_jsonrpc\.php$/, "")}/api_jsonrpc.php`,
47
    {
48
      method: "POST",
49
      headers: {
50
        Authorization: `Bearer ${auth.token}`,
51
        "Content-Type": "application/json-rpc",
52
        Accept: "application/json",
53
      },
54
      body: JSON.stringify({ jsonrpc: "2.0", method, params, id: 1 }),
55
    }
56
  )
57

58
  if (!response.ok) {
59
    throw new Error(`${response.status} ${await response.text()}`)
60
  }
61

62
  const text = await response.text()
63
  let data: any
64
  try {
65
    data = JSON.parse(text)
66
  } catch {
67
    throw new Error(
68
      `Not a JSON-RPC response (check base_url): ${text.slice(0, 300)}`
69
    )
70
  }
71
  if (data.error) {
72
    throw new Error(
73
      `${data.error.code} ${data.error.message} ${data.error.data ?? ""}`
74
    )
75
  }
76
  return data.result
77
}
78