Edits history of script submission #24194 for ' Update fixed address (infoblox_nios)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    function wapiUrl(auth: RT.InfobloxNios, path: string) {
      const host = auth.host
        .trim()
        .replace(/^https?:\/\//, "")
        .replace(/\/+$/, "")
      const version = auth.wapi_version.trim().replace(/^v/, "")
      return new URL(`https://${host}/wapi/v${version}/${path}`)
    }
    
    function refUrl(auth: RT.InfobloxNios, ref: string, type: string) {
      // Encode each segment so ?, # or .. in a ref can't reach another path or query.
      const segments = ref.split("/")
      if (
        segments[0] !== type ||
        segments.length < 2 ||
        segments.some((s) => s === "." || s === "..")
      ) {
        throw new Error(`Expected a ${type} reference, got: ${ref}`)
      }
      return wapiUrl(
        auth,
        segments.map((s) => encodeURIComponent(s).replace(/%3A/gi, ":")).join("/")
      )
    }
    
    function basicAuth(auth: RT.InfobloxNios) {
      const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`)
      return `Basic ${btoa(String.fromCharCode(...bytes))}`
    }
    
    async function wapiError(response: Response) {
      const text = await response.text()
      if (response.status === 401) {
        return new Error(
          "401 Unauthorized: wrong username or password, or the user's admin group has no API access"
        )
      }
      try {
        // WAPI errors are JSON: {"Error": "AdmConDataNotFoundError: ...", "code": "Client.Ibap.Data.NotFound", "text": "..."}
        const { Error: error, code, text: detail } = JSON.parse(text)
        if (error) {
          const message =
            detail && !error.includes(detail) ? `${error}: ${detail}` : error
          return new Error(
            `${response.status} ${message}${code ? ` (${code})` : ""}`
          )
        }
      } catch {}
      return new Error(`${response.status} ${text}`)
    }
    
    // Accept {"Site": "East"} as well as the WAPI shape {"Site": {"value": "East"}}.
    function toExtattrs(extattrs: { [key: string]: any }) {
      return Object.fromEntries(
        Object.entries(extattrs).map(([name, v]) => [
          name,
          v !== null && typeof v === "object" && !Array.isArray(v)
            ? v
            : { value: v },
        ])
      )
    }
    
    /**
     * Update fixed address
     * Change the MAC address, name or comment of a static DHCP reservation, identified by its _ref (from Search fixed addresses). extattrs ({"Site": "East"}) adds or overwrites those attributes and keeps the others. Empty inputs are left unchanged.
     */
    export async function main(
      auth: RT.InfobloxNios,
      ref: string,
      mac: string | undefined,
      name: string | undefined,
      comment: string | undefined,
      extattrs: { [key: string]: any } | undefined
    ) {
      const body: { [key: string]: any } = {}
      if (mac) body.mac = mac
      if (name) body.name = name
      if (comment) body.comment = comment
      // extattrs+ adds or overwrites the given attributes and keeps the others.
      if (extattrs && Object.keys(extattrs).length > 0)
        body["extattrs+"] = toExtattrs(extattrs)
      if (Object.keys(body).length === 0) {
        throw new Error("Nothing to update: set at least one field")
      }
    
      const url = refUrl(auth, ref, "fixedaddress")
      url.searchParams.append(
        "_return_fields+",
        "ipv4addr,mac,network,network_view,name,comment,extattrs"
      )
      url.searchParams.append("_return_as_object", "1")
    
      const response = await fetch(url, {
        method: "PUT",
        headers: {
          Authorization: basicAuth(auth),
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(body),
      })
    
      if (!response.ok) {
        throw await wapiError(response)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 3 hours ago