Edits history of script submission #24044 for ' Get next available IP (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 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}`)
    }
    
    /**
     * Get next available IP
     * Return the next free IPv4 address(es) of a network, given its CIDR (e.g. 10.20.0.0/24), or of one of its DHCP ranges (range_start_addr), skipping the addresses in exclude. Nothing is reserved: to allocate atomically, create the host record or fixed address with next_available_in_network instead.
     */
    export async function main(
      auth: RT.InfobloxNios,
      network: string,
      network_view: string | undefined,
      num: number | undefined,
      exclude: string[] | undefined,
      range_start_addr: string | undefined
    ) {
      const objectType = range_start_addr ? "range" : "network"
      const label = range_start_addr
        ? `DHCP range starting at ${range_start_addr} in ${network}`
        : `Network ${network}`
    
      const lookup = wapiUrl(auth, objectType)
      lookup.searchParams.append("network", network)
      if (range_start_addr)
        lookup.searchParams.append("start_addr", range_start_addr)
      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 await wapiError(lookupResponse)
      }
      const { result: matches } = (await lookupResponse.json()) as {
        result: { _ref: string; network_view: string }[]
      }
      if (matches.length === 0) {
        throw new Error(`${label} not found`)
      }
      if (matches.length > 1) {
        throw new Error(
          `${label} exists in several network views (${matches.map((n) => n.network_view).join(", ")}); set network_view`
        )
      }
      const ref = matches[0]._ref
    
      const url = wapiUrl(auth, ref)
      url.searchParams.append("_function", "next_available_ip")
      url.searchParams.append("_return_as_object", "1")
    
      const body: { [key: string]: any } = { num: num || 1 }
      if (exclude?.length) body.exclude = exclude
    
      const response = await fetch(url, {
        method: "POST",
        headers: {
          Authorization: basicAuth(auth),
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(body),
      })
    
      if (!response.ok) {
        throw await wapiError(response)
      }
    
      const data = await response.json()
      return {
        ref,
        [range_start_addr ? "range_ref" : "network_ref"]: ref,
        ips: data.result.ips,
      }
    }
    

    Submitted by hugo989 15 days ago

  • bunnative
    //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 basicAuth(auth: RT.InfobloxNios) {
      const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`)
      return `Basic ${btoa(String.fromCharCode(...bytes))}`
    }
    
    /**
     * Get next available IP
     * Return the next free IPv4 address(es) of a network, given its CIDR (e.g. 10.20.0.0/24). Nothing is reserved: to allocate atomically, create the host record or fixed address with next_available_in_network instead.
     */
    export async function main(
      auth: RT.InfobloxNios,
      network: string,
      network_view: string | undefined,
      num: number | undefined,
      exclude: string[] | undefined
    ) {
      const lookup = wapiUrl(auth, "network")
      lookup.searchParams.append("network", network)
      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: networks } = (await lookupResponse.json()) as {
        result: { _ref: string; network: string; network_view: string }[]
      }
      if (networks.length === 0) {
        throw new Error(`Network ${network} not found`)
      }
      if (networks.length > 1) {
        throw new Error(
          `Network ${network} exists in several network views (${networks.map((n) => n.network_view).join(", ")}); set network_view`
        )
      }
    
      const url = wapiUrl(auth, networks[0]._ref)
      url.searchParams.append("_function", "next_available_ip")
      url.searchParams.append("_return_as_object", "1")
    
      const body: { [key: string]: any } = { num: num || 1 }
      if (exclude?.length) body.exclude = exclude
    
      const response = await fetch(url, {
        method: "POST",
        headers: {
          Authorization: basicAuth(auth),
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(body),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const data = await response.json()
      return { network_ref: networks[0]._ref, ips: data.result.ips }
    }
    

    Submitted by hugo989 21 days ago