Edits history of script submission #24039 for ' Create host record (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))}`
    }
    
    /**
     * Create host record
     * Create a host record (record:host) with one IPv4 address: a fixed ipv4addr, or the next free address of next_available_in_network (CIDR), allocated atomically. Setting mac also creates the DHCP reservation. extattrs uses the WAPI shape {"Site": {"value": "East"}}.
     */
    export async function main(
      auth: RT.InfobloxNios,
      name: string,
      ipv4addr: string | undefined,
      next_available_in_network: string | undefined,
      network_view: string | undefined,
      mac: string | undefined,
      view: string | undefined,
      aliases: string[] | undefined,
      ttl: number | undefined,
      comment: string | undefined,
      extattrs: { [key: string]: any } | undefined
    ) {
      if (!ipv4addr === !next_available_in_network) {
        throw new Error("Set exactly one of ipv4addr or next_available_in_network")
      }
    
      const address: { [key: string]: any } = {
        ipv4addr:
          ipv4addr ||
          `func:nextavailableip:${next_available_in_network}${network_view ? `,${network_view}` : ""}`,
      }
      if (mac) address.mac = mac
    
      const body: { [key: string]: any } = { name, ipv4addrs: [address] }
      if (view) body.view = view
      if (aliases?.length) body.aliases = aliases
      if (ttl != null) {
        body.ttl = ttl
        body.use_ttl = true
      }
      if (comment) body.comment = comment
      if (extattrs && Object.keys(extattrs).length > 0) body.extattrs = extattrs
    
      const url = wapiUrl(auth, "record:host")
      url.searchParams.append(
        "_return_fields+",
        "name,ipv4addrs,view,aliases,ttl,comment"
      )
      url.searchParams.append("_return_as_object", "1")
    
      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()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 7 hours ago