🌳
pt0/deployF/hostnameF/ensureWcDnsRecordsAI.mts
1import * as _ from 'lodash-es'
9export const ensurewcdnsrecords = async () => {
10 const {cluster_name, klustCertsH, serverIp, cfApiKeySecretName, domainNames, klusterVipHostname, clusterVip} = getKlusterCtx()
11 if (!serverIp) throPtErr('!serverIp')
12 if (!klustCertsH) throPtErr('!klustCertsH')
14 const headers = getCfHeaders({cfApiKeySecretName})
15 const claimStore = domainNames && domainNames.length ? mkCfTxtClaimStore({headers, domainNames}) : undefined
17 const wcHostnames = _.flatMap(_.values(klustCertsH), (dnsNamesRaw) => {
18 const dnsNames = Array.isArray(dnsNamesRaw) ? dnsNamesRaw : [dnsNamesRaw]
19 return dnsNames.filter((hn: string) => hn.startsWith('*.'))
20 })
22 if (wcHostnames.length === 0) {
23 console.log('no wildcard hostnames in klustCertsH')
24 return
25 }
27 const zones = await cfFetch('/zones', headers)
29 for (const wcHostname of wcHostnames) {
30 const zoneName = domainNames!.find((d: string) => wcHostname.endsWith(d.replace(/^[^.]+\./, '')) || wcHostname.slice(2).endsWith(`.${d}`) || wcHostname.slice(2) === d)
31 if (!zoneName) {
32 console.log(`⚠️ no matching zone for ${wcHostname}`)
33 continue
34 }
35 const zone = zones.find((z: any) => z.name === zoneName)
36 if (!zone) {
37 console.log(`⚠️ zone not found: ${zoneName}`)
38 continue
39 }
41 const targetIp = wcHostname === klusterVipHostname ? clusterVip : serverIp
43 if (claimStore) {
44 const claimed = await checkClaim({store: claimStore, claimKey: wcClaimKey(wcHostname), owner: cluster_name})
45 if (!claimed) { betLog({skippedWcClaim: wcHostname, cluster_name}); continue }
46 }
47 const existing = await cfFetch(`/zones/${zone.id}/dns_records?type=A&name=${encodeURIComponent(wcHostname)}`, headers)
48 const existingRecord = _.first(existing) as {content?: string, id?: string} | undefined
50 if (existingRecord && existingRecord.content === targetIp) {
51 console.log(`✓ ${wcHostname} → ${targetIp}`)
52 continue
53 }
55 const body = JSON.stringify({type: 'A', name: wcHostname, content: targetIp, ttl: 1, proxied: false})
56 if (existingRecord) {
57 await cfFetch(`/zones/${zone.id}/dns_records/${existingRecord.id}`, headers, {method: 'PATCH', body})
58 betLog({wcHostname, updated: `${existingRecord.content} → ${targetIp}`})
59 } else {
60 await cfFetch(`/zones/${zone.id}/dns_records`, headers, {method: 'POST', body})
61 betLog({wcHostname, created: targetIp})
62 }
63 }
66ensurewcdnsrecords.cliDescript = 'ensure Cloudflare wildcard A records exist for all wildcard certs in klustCertsH'