Edits history of script submission #23994 for ' Push value (zabbix)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Push value
     * Push a value to a Zabbix trapper item (history.push, Zabbix 7.0+), identified by itemid or by technical host name + item key, e.g. to raise an alarm when a workflow fails. The trapper item and its trigger must already exist; if the item restricts Allowed hosts, include the Zabbix web frontend's IP. Minimal setup: a trapper item with key "trap" (numeric) and a trigger like last(/<host>/trap)>0; push 1 on failure and 0 to recover. Throws if Zabbix rejects the push (unknown item, no permission, source not in Allowed hosts). A value that doesn't fit the item's type is accepted, then makes the item unsupported.
     */
    export async function main(
      auth: RT.Zabbix,
      value: string,
      itemid: string | undefined,
      host: string | undefined,
      key: string | undefined,
      clock: string | undefined
    ) {
      const params: { [key: string]: any } = { value }
      if (itemid && (host || key)) {
        throw new Error("Provide itemid, or host and key, not both")
      }
      if (itemid) {
        params.itemid = itemid
      } else if (host && key) {
        params.host = host
        params.key = key
      } else {
        throw new Error("Provide itemid, or both host and key")
      }
      if (clock) {
        const seconds = Math.floor(new Date(clock).getTime() / 1000)
        if (Number.isNaN(seconds)) {
          throw new Error(`Invalid clock: ${clock}`)
        }
        params.clock = seconds
      }
    
      const result = await call(auth, "history.push", params)
      const failed = (result.data ?? []).filter((d: any) => d.error)
      if (failed.length) {
        throw new Error(
          `history.push rejected the value: ${failed.map((d: any) => d.error).join("; ")}`
        )
      }
      return result
    }
    
    async function call(auth: RT.Zabbix, method: string, params: any) {
      const response = await fetch(
        `${auth.base_url.replace(/\/+$/, "").replace(/\/api_jsonrpc\.php$/, "")}/api_jsonrpc.php`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/json-rpc",
            Accept: "application/json",
          },
          body: JSON.stringify({ jsonrpc: "2.0", method, params, id: 1 }),
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const text = await response.text()
      let data: any
      try {
        data = JSON.parse(text)
      } catch {
        throw new Error(
          `Not a JSON-RPC response (check base_url): ${text.slice(0, 300)}`
        )
      }
      if (data.error) {
        throw new Error(
          `${data.error.code} ${data.error.message} ${data.error.data ?? ""}`
        )
      }
      return data.result
    }
    

    Submitted by hugo989 3 hours ago