Edits history of script submission #24042 for ' Delete 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))}`
    }
    
    /**
     * Delete fixed address
     * Delete a static DHCP reservation, identified by its _ref or by its MAC address (optionally narrowed by network_view). Fails without deleting anything when the MAC matches zero or several reservations. Returns the _ref of the deleted reservation.
     */
    export async function main(
      auth: RT.InfobloxNios,
      ref: string | undefined,
      mac: string | undefined,
      network_view: string | undefined
    ) {
      if (!ref === !mac) {
        throw new Error("Set exactly one of ref or mac")
      }
    
      let target = ref
      if (!target) {
        const lookup = wapiUrl(auth, "fixedaddress")
        lookup.searchParams.append("mac", mac!)
        if (network_view) lookup.searchParams.append("network_view", network_view)
        lookup.searchParams.append("_return_as_object", "1")
    
        const lookupResponse = await fetch(lookup, {
          headers: {
            Authorization: basicAuth(auth),
            Accept: "application/json",
          },
        })
        if (!lookupResponse.ok) {
          throw new Error(`${lookupResponse.status} ${await lookupResponse.text()}`)
        }
        const { result } = (await lookupResponse.json()) as {
          result: { _ref: string; ipv4addr: string; network_view: string }[]
        }
        if (result.length === 0) {
          throw new Error(`No fixed address found for MAC ${mac}`)
        }
        if (result.length > 1) {
          throw new Error(
            `MAC ${mac} matches ${result.length} fixed addresses; pass the ref of one: ${result.map((r) => r._ref).join(", ")}`
          )
        }
        target = result[0]._ref
      }
    
      const url = refUrl(auth, target!, "fixedaddress")
      url.searchParams.append("_return_as_object", "1")
    
      const response = await fetch(url, {
        method: "DELETE",
        headers: {
          Authorization: basicAuth(auth),
          Accept: "application/json",
        },
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 7 hours ago