0

Create CNAME record

Published 20 days ago

Create a DNS CNAME record (record:cname) pointing the alias name to a canonical name. extattrs takes {"Site": "East"} or the WAPI shape {"Site": {"value": "East"}}. Returns the created record with its _ref.

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

17
async function wapiError(response: Response) {
18
  const text = await response.text()
19
  if (response.status === 401) {
20
    return new Error(
21
      "401 Unauthorized: wrong username or password, or the user's admin group has no API access"
22
    )
23
  }
24
  try {
25
    // WAPI errors are JSON: {"Error": "AdmConDataNotFoundError: ...", "code": "Client.Ibap.Data.NotFound", "text": "..."}
26
    const { Error: error, code, text: detail } = JSON.parse(text)
27
    if (error) {
28
      const message =
29
        detail && !error.includes(detail) ? `${error}: ${detail}` : error
30
      return new Error(
31
        `${response.status} ${message}${code ? ` (${code})` : ""}`
32
      )
33
    }
34
  } catch {}
35
  return new Error(`${response.status} ${text}`)
36
}
37

38
// Accept {"Site": "East"} as well as the WAPI shape {"Site": {"value": "East"}}.
39
function toExtattrs(extattrs: { [key: string]: any }) {
40
  return Object.fromEntries(
41
    Object.entries(extattrs).map(([name, v]) => [
42
      name,
43
      v !== null && typeof v === "object" && !Array.isArray(v)
44
        ? v
45
        : { value: v },
46
    ])
47
  )
48
}
49

50
/**
51
 * Create CNAME record
52
 * Create a DNS CNAME record (record:cname) pointing the alias name to a canonical name. extattrs takes {"Site": "East"} or the WAPI shape {"Site": {"value": "East"}}. Returns the created record with its _ref.
53
 */
54
export async function main(
55
  auth: RT.InfobloxNios,
56
  name: string,
57
  canonical: string,
58
  view: string | undefined,
59
  ttl: number | undefined,
60
  comment: string | undefined,
61
  extattrs: { [key: string]: any } | undefined
62
) {
63
  const url = wapiUrl(auth, "record:cname")
64
  url.searchParams.append("_return_fields+", "name,canonical,view,ttl,comment")
65
  url.searchParams.append("_return_as_object", "1")
66

67
  const body: { [key: string]: any } = { name, canonical }
68
  if (view) body.view = view
69
  if (ttl != null) {
70
    body.ttl = ttl
71
    body.use_ttl = true
72
  }
73
  if (comment) body.comment = comment
74
  if (extattrs && Object.keys(extattrs).length > 0)
75
    body.extattrs = toExtattrs(extattrs)
76

77
  const response = await fetch(url, {
78
    method: "POST",
79
    headers: {
80
      Authorization: basicAuth(auth),
81
      "Content-Type": "application/json",
82
      Accept: "application/json",
83
    },
84
    body: JSON.stringify(body),
85
  })
86

87
  if (!response.ok) {
88
    throw await wapiError(response)
89
  }
90

91
  return await response.json()
92
}
93