1 | |
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 host record |
19 | * 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"}}. |
20 | */ |
21 | export async function main( |
22 | auth: RT.InfobloxNios, |
23 | name: string, |
24 | ipv4addr: string | undefined, |
25 | next_available_in_network: string | undefined, |
26 | network_view: string | undefined, |
27 | mac: string | undefined, |
28 | view: string | undefined, |
29 | aliases: string[] | undefined, |
30 | ttl: number | undefined, |
31 | comment: string | undefined, |
32 | extattrs: { [key: string]: any } | undefined |
33 | ) { |
34 | if (!ipv4addr === !next_available_in_network) { |
35 | throw new Error("Set exactly one of ipv4addr or next_available_in_network") |
36 | } |
37 |
|
38 | const address: { [key: string]: any } = { |
39 | ipv4addr: |
40 | ipv4addr || |
41 | `func:nextavailableip:${next_available_in_network}${network_view ? `,${network_view}` : ""}`, |
42 | } |
43 | if (mac) address.mac = mac |
44 |
|
45 | const body: { [key: string]: any } = { name, ipv4addrs: [address] } |
46 | if (view) body.view = view |
47 | if (aliases?.length) body.aliases = aliases |
48 | if (ttl != null) { |
49 | body.ttl = ttl |
50 | body.use_ttl = true |
51 | } |
52 | if (comment) body.comment = comment |
53 | if (extattrs && Object.keys(extattrs).length > 0) body.extattrs = extattrs |
54 |
|
55 | const url = wapiUrl(auth, "record:host") |
56 | url.searchParams.append( |
57 | "_return_fields+", |
58 | "name,ipv4addrs,view,aliases,ttl,comment" |
59 | ) |
60 | url.searchParams.append("_return_as_object", "1") |
61 |
|
62 | const response = await fetch(url, { |
63 | method: "POST", |
64 | headers: { |
65 | Authorization: basicAuth(auth), |
66 | "Content-Type": "application/json", |
67 | Accept: "application/json", |
68 | }, |
69 | body: JSON.stringify(body), |
70 | }) |
71 |
|
72 | if (!response.ok) { |
73 | throw new Error(`${response.status} ${await response.text()}`) |
74 | } |
75 |
|
76 | return await response.json() |
77 | } |
78 |
|