🌳
pt0/deployF/k8sF/kustomizeF.mts
1import yaml from 'js-yaml'
2import * as _ from 'lodash-es'
5import { getKlusterCtx, type KubeResource } from './ctxF/klusterCtxF.mts'
6import { execSync } from 'child_process'
8export const guardKustomizeInstalled = () => {
9 try {
10 execSync('which kustomize', {stdio: 'ignore'})
11 } catch { // catch:userapproved — absence is the guard condition
12 console.error([
13 'kustomize not found. Install with:',
14 '',
15 ' brew install kustomize',
16 '',
17 'or: https://kubectl.docs.kubernetes.io/installation/kustomize/binaries/',
18 ].join('\n'))
19 process.exit(1)
20 }
23type ReplacementH = Record<string, string>
25export const yamlReplaceAndLoad = ({contentS, replacementH}: {contentS: string, replacementH?: ReplacementH}): unknown[] => {
26 _.each(replacementH, (val, key) => {
27 contentS = _.replace(contentS, new RegExp(key, "g"), val)
28 })
30 return yaml.loadAll(contentS)
33export const kustomize = async ({path, replacementH}: {path: string, replacementH?: ReplacementH}): Promise<unknown[]> => {
34 guardKustomizeInstalled()
35 const {stdout} = await execAsyncR(`kustomize build ${path}`)
37 return yamlReplaceAndLoad({contentS: stdout, replacementH})
40export const getResources = async ({path, replacementH}: {path: string, cluster_name?: string, replacementH?: ReplacementH}) => {
41 return await kustomize({path, replacementH})
44type Kube2ApplyKProps = { action: string, resources: KubeResource[], cluster_name?: string }
45export const kube2ApplyK = async ({action, resources, cluster_name}: Kube2ApplyKProps) => {
46 cluster_name ||= getKlusterCtx().cluster_name
47 const promises = _.map(resources, (resource) => {
48 return new Promise((resolv, reject) => {
49 res1Action({resource, action, cluster_name: cluster_name!}).then((applied) => {
50 resolv(applied)
51 }).catch((ee: any) => {
52 try {
53 const {body: {reason}} = ee
55 if (reason == 'AlreadyExists') {
56 resolv(resource)
57 } else {
58 reject("unexpected body")
59 console.error(['unexpected body', ee.body])
60 }
61 } catch (ee2) {
62 reject(["unexpected exception", ee])
63 }
64 })
65 })
66 })
67 return Promise.all(promises)
70type KubeApplyKProps = { action: string, path: string, cluster_name?: string, replacementH?: ReplacementH }
71export const kubeApplyK = async ({action, cluster_name, ...props}: KubeApplyKProps) => {
72 const resources = await getResources(props)
73 return await kube2ApplyK({action, resources: resources as KubeResource[], cluster_name})