0

Delete fixed address

Published 20 days ago

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.

Script infoblox_nios Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 15 days ago
1
//native
2

3
function wapiUrl(auth: RT.InfobloxNios, path: string) {
4
  const host = auth.host
5
    .trim()
6
    .replace(/^https?:\/\//, "")
7
    .replace(/\/+$/, "")
8
  const version = auth.wapi_version.trim().replace(/^v/, "")
9
  return new URL(`https://${host}/wapi/v${version}/${path}`)
10
}
11

12
function refUrl(auth: RT.InfobloxNios, ref: string, type: string) {
13
  // Encode each segment so ?, # or .. in a ref can't reach another path or query.
14
  const segments = ref.split("/")
15
  if (
16
    segments[0] !== type ||
17
    segments.length < 2 ||
18
    segments.some((s) => s === "." || s === "..")
19
  ) {
20
    throw new Error(`Expected a ${type} reference, got: ${ref}`)
21
  }
22
  return wapiUrl(
23
    auth,
24
    segments.map((s) => encodeURIComponent(s).replace(/%3A/gi, ":")).join("/")
25
  )
26
}
27

28
function basicAuth(auth: RT.InfobloxNios) {
29
  const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`)
30
  return `Basic ${btoa(String.fromCharCode(...bytes))}`
31
}
32

33
async function wapiError(response: Response) {
34
  const text = await response.text()
35
  if (response.status === 401) {
36
    return new Error(
37
      "401 Unauthorized: wrong username or password, or the user's admin group has no API access"
38
    )
39
  }
40
  try {
41
    // WAPI errors are JSON: {"Error": "AdmConDataNotFoundError: ...", "code": "Client.Ibap.Data.NotFound", "text": "..."}
42
    const { Error: error, code, text: detail } = JSON.parse(text)
43
    if (error) {
44
      const message =
45
        detail && !error.includes(detail) ? `${error}: ${detail}` : error
46
      return new Error(
47
        `${response.status} ${message}${code ? ` (${code})` : ""}`
48
      )
49
    }
50
  } catch {}
51
  return new Error(`${response.status} ${text}`)
52
}
53

54
/**
55
 * Delete fixed address
56
 * 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.
57
 */
58
export async function main(
59
  auth: RT.InfobloxNios,
60
  ref: string | undefined,
61
  mac: string | undefined,
62
  network_view: string | undefined
63
) {
64
  if (!ref === !mac) {
65
    throw new Error("Set exactly one of ref or mac")
66
  }
67

68
  let target = ref
69
  if (!target) {
70
    const lookup = wapiUrl(auth, "fixedaddress")
71
    lookup.searchParams.append("mac", mac!)
72
    if (network_view) lookup.searchParams.append("network_view", network_view)
73
    lookup.searchParams.append("_return_as_object", "1")
74

75
    const lookupResponse = await fetch(lookup, {
76
      headers: {
77
        Authorization: basicAuth(auth),
78
        Accept: "application/json",
79
      },
80
    })
81
    if (!lookupResponse.ok) {
82
      throw await wapiError(lookupResponse)
83
    }
84
    const { result } = (await lookupResponse.json()) as {
85
      result: { _ref: string; ipv4addr: string; network_view: string }[]
86
    }
87
    if (result.length === 0) {
88
      throw new Error(`No fixed address found for MAC ${mac}`)
89
    }
90
    if (result.length > 1) {
91
      throw new Error(
92
        `MAC ${mac} matches ${result.length} fixed addresses; pass the ref of one: ${result.map((r) => r._ref).join(", ")}`
93
      )
94
    }
95
    target = result[0]._ref
96
  }
97

98
  const url = refUrl(auth, target!, "fixedaddress")
99
  url.searchParams.append("_return_as_object", "1")
100

101
  const response = await fetch(url, {
102
    method: "DELETE",
103
    headers: {
104
      Authorization: basicAuth(auth),
105
      Accept: "application/json",
106
    },
107
  })
108

109
  if (!response.ok) {
110
    throw await wapiError(response)
111
  }
112

113
  return await response.json()
114
}
115