0

Import DNS Records

by
Published today

Import DNS records into a zone from the text of a BIND zone file.

Script cloudflare Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 3 hours ago
1
//native
2

3
export type DynSelect_zone_id = string
4

5
// Dropdown of the account's zones so users pick a domain instead of pasting its 32-char id.
6
// ponytail: first 50 zones only (API max per_page); paste the id directly beyond that.
7
export async function zone_id(auth: RT.Cloudflare) {
8
  const response = await fetch(
9
    "https://api.cloudflare.com/client/v4/zones?per_page=50",
10
    {
11
      headers: {
12
        Authorization: `Bearer ${auth.token}`,
13
        Accept: "application/json",
14
      },
15
    }
16
  )
17
  if (!response.ok) {
18
    throw new Error(`${response.status} ${await response.text()}`)
19
  }
20
  const { result } = (await response.json()) as {
21
    result: { id: string; name: string }[]
22
  }
23
  return result.map((z) => ({ value: z.id, label: z.name }))
24
}
25

26
/**
27
 * Import DNS Records
28
 * Import DNS records into a zone from the text of a BIND zone file.
29
 */
30
export async function main(
31
  auth: RT.Cloudflare,
32
  zone_id: DynSelect_zone_id,
33
  bind_file: string,
34
  proxied: boolean | undefined
35
) {
36
  const form = new FormData()
37
  form.append("file", new Blob([bind_file], { type: "text/plain" }), "zone.txt")
38
  if (proxied != null) form.append("proxied", String(proxied))
39

40
  const response = await fetch(
41
    `https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records/import`,
42
    {
43
      method: "POST",
44
      headers: {
45
        Authorization: `Bearer ${auth.token}`,
46
        Accept: "application/json",
47
      },
48
      body: form,
49
    }
50
  )
51

52
  if (!response.ok) {
53
    throw new Error(`${response.status} ${await response.text()}`)
54
  }
55

56
  return await response.json()
57
}
58