1 | |
2 |
|
3 | |
4 | * List hosts |
5 | * List hosts (host.get) filtered by exact technical host names, a case-insensitive substring of the visible name, or host group IDs; returns hostid, host, name, status (0 enabled, 1 disabled) and hostgroups. 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 | host_names: string[] | undefined, |
10 | name_search: string | undefined, |
11 | group_ids: string[] | undefined, |
12 | limit: number | undefined |
13 | ) { |
14 | const max = Math.max(1, limit || 100) |
15 | const params: { [key: string]: any } = { |
16 | output: ["hostid", "host", "name", "status"], |
17 | selectHostGroups: ["groupid", "name"], |
18 | sortfield: "hostid", |
19 | limit: max + 1, |
20 | } |
21 | if (host_names?.length) { |
22 | params.filter = { host: host_names } |
23 | } |
24 | if (name_search) { |
25 | params.search = { name: name_search } |
26 | } |
27 | if (group_ids?.length) { |
28 | params.groupids = group_ids |
29 | } |
30 |
|
31 | const hosts = await call(auth, "host.get", params) |
32 | return { hosts: hosts.slice(0, max), has_more: hosts.length > max } |
33 | } |
34 |
|
35 | async function call(auth: RT.Zabbix, method: string, params: any) { |
36 | const response = await fetch( |
37 | `${auth.base_url.replace(/\/+$/, "").replace(/\/api_jsonrpc\.php$/, "")}/api_jsonrpc.php`, |
38 | { |
39 | method: "POST", |
40 | headers: { |
41 | Authorization: `Bearer ${auth.token}`, |
42 | "Content-Type": "application/json-rpc", |
43 | Accept: "application/json", |
44 | }, |
45 | body: JSON.stringify({ jsonrpc: "2.0", method, params, id: 1 }), |
46 | } |
47 | ) |
48 |
|
49 | if (!response.ok) { |
50 | throw new Error(`${response.status} ${await response.text()}`) |
51 | } |
52 |
|
53 | const text = await response.text() |
54 | let data: any |
55 | try { |
56 | data = JSON.parse(text) |
57 | } catch { |
58 | throw new Error( |
59 | `Not a JSON-RPC response (check base_url): ${text.slice(0, 300)}` |
60 | ) |
61 | } |
62 | if (data.error) { |
63 | throw new Error( |
64 | `${data.error.code} ${data.error.message} ${data.error.data ?? ""}` |
65 | ) |
66 | } |
67 | return data.result |
68 | } |
69 |
|