//native
function wapiUrl(auth: RT.InfobloxNios, path: string) {
const host = auth.host
.trim()
.replace(/^https?:\/\//, "")
.replace(/\/+$/, "")
const version = auth.wapi_version.trim().replace(/^v/, "")
return new URL(`https://${host}/wapi/v${version}/${path}`)
}
function basicAuth(auth: RT.InfobloxNios) {
const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`)
return `Basic ${btoa(String.fromCharCode(...bytes))}`
}
/**
* Get next available IP
* Return the next free IPv4 address(es) of a network, given its CIDR (e.g. 10.20.0.0/24). Nothing is reserved: to allocate atomically, create the host record or fixed address with next_available_in_network instead.
*/
export async function main(
auth: RT.InfobloxNios,
network: string,
network_view: string | undefined,
num: number | undefined,
exclude: string[] | undefined
) {
const lookup = wapiUrl(auth, "network")
lookup.searchParams.append("network", network)
if (network_view) lookup.searchParams.append("network_view", network_view)
lookup.searchParams.append("_return_as_object", "1")
const lookupResponse = await fetch(lookup, {
headers: {
Authorization: basicAuth(auth),
Accept: "application/json",
},
})
if (!lookupResponse.ok) {
throw new Error(`${lookupResponse.status} ${await lookupResponse.text()}`)
}
const { result: networks } = (await lookupResponse.json()) as {
result: { _ref: string; network: string; network_view: string }[]
}
if (networks.length === 0) {
throw new Error(`Network ${network} not found`)
}
if (networks.length > 1) {
throw new Error(
`Network ${network} exists in several network views (${networks.map((n) => n.network_view).join(", ")}); set network_view`
)
}
const url = wapiUrl(auth, networks[0]._ref)
url.searchParams.append("_function", "next_available_ip")
url.searchParams.append("_return_as_object", "1")
const body: { [key: string]: any } = { num: num || 1 }
if (exclude?.length) body.exclude = exclude
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: basicAuth(auth),
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(body),
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const data = await response.json()
return { network_ref: networks[0]._ref, ips: data.result.ips }
}
Submitted by hugo989 7 hours ago