0

Update host record

Published 20 days ago

Rename a host record, change its TTL or comment, or replace its IPv4 address list with a single address (and optional MAC), identified by its _ref (from Search records). extattrs ({"Site": "East"}) adds or overwrites those attributes and keeps the others. Empty inputs are left unchanged.

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
// Accept {"Site": "East"} as well as the WAPI shape {"Site": {"value": "East"}}.
55
function toExtattrs(extattrs: { [key: string]: any }) {
56
  return Object.fromEntries(
57
    Object.entries(extattrs).map(([name, v]) => [
58
      name,
59
      v !== null && typeof v === "object" && !Array.isArray(v)
60
        ? v
61
        : { value: v },
62
    ])
63
  )
64
}
65

66
/**
67
 * Update host record
68
 * Rename a host record, change its TTL or comment, or replace its IPv4 address list with a single address (and optional MAC), identified by its _ref (from Search records). extattrs ({"Site": "East"}) adds or overwrites those attributes and keeps the others. Empty inputs are left unchanged.
69
 */
70
export async function main(
71
  auth: RT.InfobloxNios,
72
  ref: string,
73
  name: string | undefined,
74
  ipv4addr: string | undefined,
75
  mac: string | undefined,
76
  ttl: number | undefined,
77
  comment: string | undefined,
78
  extattrs: { [key: string]: any } | undefined
79
) {
80
  if (mac && !ipv4addr) {
81
    throw new Error(
82
      "mac is set together with ipv4addr, which replaces the address list"
83
    )
84
  }
85

86
  const body: { [key: string]: any } = {}
87
  if (name) body.name = name
88
  if (ipv4addr) body.ipv4addrs = [mac ? { ipv4addr, mac } : { ipv4addr }]
89
  if (ttl != null) {
90
    body.ttl = ttl
91
    body.use_ttl = true
92
  }
93
  if (comment) body.comment = comment
94
  // extattrs+ adds or overwrites the given attributes and keeps the others.
95
  if (extattrs && Object.keys(extattrs).length > 0)
96
    body["extattrs+"] = toExtattrs(extattrs)
97
  if (Object.keys(body).length === 0) {
98
    throw new Error("Nothing to update: set at least one field")
99
  }
100

101
  const url = refUrl(auth, ref, "record:host")
102
  url.searchParams.append(
103
    "_return_fields+",
104
    "name,ipv4addrs,view,aliases,ttl,comment,extattrs"
105
  )
106
  url.searchParams.append("_return_as_object", "1")
107

108
  const response = await fetch(url, {
109
    method: "PUT",
110
    headers: {
111
      Authorization: basicAuth(auth),
112
      "Content-Type": "application/json",
113
      Accept: "application/json",
114
    },
115
    body: JSON.stringify(body),
116
  })
117

118
  if (!response.ok) {
119
    throw await wapiError(response)
120
  }
121

122
  return await response.json()
123
}
124