Node client interfacing with a k8s cluster using simple functions and yaml template strings. If you're just interested in creating k8s javascript client objects using template strings, see @thinkdeep/k8s-manifest.
- Tested on Kubernetes javascript client v0.15 (Based on conventions within this API I think it could work with multiple versions but that hasn't been verified)
- Node v16.14.2 LTS
npm i @thinkdeep/k8sAssuming the role binding linking the necessary role and service account has the needed permissions:
import{K8sClient,KubeConfig,stringify}from'@thinkdeep/k8s';constconfig=newKubeConfig();// KubeConfig exported directly from https://github.com/kubernetes-client/javascriptconfig.loadFromCluster();// Or whatever desired loading mechanismconstclient=awaitnewK8sClient(config).init();// Set default namespace fallback to whatever you desire or use the default provided 'default'.client.defaultNamespace='development';constoptions={name: 'dynamic-cron-job',namespace: 'production',schedule: '* * * * *',image: 'busybox',command: 'echo',args: ['Hello World']};// Assuming environment variables have been defined...constcronJob=awaitclient.create(` apiVersion: "batch/v1" kind: "CronJob" metadata: name: "${options.name}" namespace: "${options.namespace||"default"}" spec: schedule: "${options.schedule}" jobTemplate: spec: template: spec: containers: - name: "${process.env.HELM_RELEASE_NAME}-data-collector" image: "${options.image}" command: ["${options.command}"] args: ${JSON.stringify(options.args)} envFrom: - secretRef: name: "${process.env.HELM_RELEASE_NAME}-deep-microservice-collection-secret"${process.env.PREDECOS_KAFKA_SECRET ? ` - secretRef: name: "${process.env.PREDECOS_KAFKA_SECRET}" ` : ``} serviceAccountName: "${process.env.HELM_RELEASE_NAME}-secret-accessor-service-account" restartPolicy: "Never" imagePullSecrets: - name: "docker-secret" `);console.log(`Created cron job:\n${stringify(cronJob)}`);constmicroserviceDeployment=awaitclient.get('deployment','my-deployment','production');if(!microserviceDeployment.status.readyReplicas){awaitclient.delete(cronJob);console.log(`Deleted cron job:\n${stringify(cronJob)}`);}constcronJobs=awaitclient.getAll('cronjob','production');for(constcronJobofcronJobs){console.log(`Found:\n${stringify(cronJob)}`);if(cronJob.metadata.name==='some-name-thats-present'){cronJob.spec.schedule='0 */12 * * *';awaitclient.apply(cronJob);}}