0

Create fixed address

by
Published today

Create a static DHCP reservation (fixedaddress) binding a MAC address to an IPv4 address: a fixed ipv4addr, or the next free address of next_available_in_network (CIDR), allocated atomically. extattrs uses the WAPI shape {"Site": {"value": "East"}}.

Script infoblox_nios Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 7 hours 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 basicAuth(auth: RT.InfobloxNios) {
13
  const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`)
14
  return `Basic ${btoa(String.fromCharCode(...bytes))}`
15
}
16

17
/**
18
 * Create fixed address
19
 * Create a static DHCP reservation (fixedaddress) binding a MAC address to an IPv4 address: a fixed ipv4addr, or the next free address of next_available_in_network (CIDR), allocated atomically. extattrs uses the WAPI shape {"Site": {"value": "East"}}.
20
 */
21
export async function main(
22
  auth: RT.InfobloxNios,
23
  mac: string,
24
  ipv4addr: string | undefined,
25
  next_available_in_network: string | undefined,
26
  network_view: string | undefined,
27
  name: string | undefined,
28
  comment: string | undefined,
29
  extattrs: { [key: string]: any } | undefined
30
) {
31
  if (!ipv4addr === !next_available_in_network) {
32
    throw new Error("Set exactly one of ipv4addr or next_available_in_network")
33
  }
34

35
  const body: { [key: string]: any } = {
36
    ipv4addr:
37
      ipv4addr ||
38
      `func:nextavailableip:${next_available_in_network}${network_view ? `,${network_view}` : ""}`,
39
    mac,
40
  }
41
  if (network_view) body.network_view = network_view
42
  if (name) body.name = name
43
  if (comment) body.comment = comment
44
  if (extattrs && Object.keys(extattrs).length > 0) body.extattrs = extattrs
45

46
  const url = wapiUrl(auth, "fixedaddress")
47
  url.searchParams.append(
48
    "_return_fields+",
49
    "ipv4addr,mac,network,network_view,name,comment"
50
  )
51
  url.searchParams.append("_return_as_object", "1")
52

53
  const response = await fetch(url, {
54
    method: "POST",
55
    headers: {
56
      Authorization: basicAuth(auth),
57
      "Content-Type": "application/json",
58
      Accept: "application/json",
59
    },
60
    body: JSON.stringify(body),
61
  })
62

63
  if (!response.ok) {
64
    throw new Error(`${response.status} ${await response.text()}`)
65
  }
66

67
  return await response.json()
68
}
69