11import * as k8s from '@kubernetes/client-node' ;
2- import * as yaml from 'js-yaml' ;
3- import { promises as fs } from 'fs' ;
42
5- /**
6- * Replicate the functionality of `kubectl apply`. That is, create the resources defined in the `specFile` if they do
7- * not exist, patch them if they do exist.
8- *
9- * @param specPath File system path to a YAML Kubernetes spec.
10- * @return Array of resources created
11- */
12- export async function apply ( specPath : string ) : Promise < k8s . KubernetesObject [ ] > {
13- const kc = new k8s . KubeConfig ( ) ;
14- kc . loadFromDefault ( ) ;
3+ const kc = new k8s . KubeConfig ( ) ;
4+ kc . loadFromDefault ( ) ;
155
16- const client = k8s . KubernetesObjectApi . makeApiClient ( kc ) ;
6+ const client = k8s . KubernetesObjectApi . makeApiClient ( kc ) ;
177
18- const specString = await fs . readFile ( specPath , 'utf8' ) ;
19- const specs : k8s . KubernetesObject [ ] = yaml . loadAll ( specString ) ;
20- const validSpecs = specs . filter ( ( s ) => s && s . kind && s . metadata ) ;
21- const created : k8s . KubernetesObject [ ] = [ ] ;
22- for ( const spec of validSpecs ) {
23- // this is to convince the old version of TypeScript that metadata exists even though we already filtered specs
24- // without metadata out
25- spec . metadata = spec . metadata || { } ;
26- spec . metadata . annotations = spec . metadata . annotations || { } ;
27- delete spec . metadata . annotations [ 'kubectl.kubernetes.io/last-applied-configuration' ] ;
28- spec . metadata . annotations [ 'kubectl.kubernetes.io/last-applied-configuration' ] = JSON . stringify ( spec ) ;
29- try {
30- // try to get the resource, if it does not exist an error will be thrown and we will end up in the catch
31- // block.
32- await client . read ( spec ) ;
33- // we got the resource, so it exists, so patch it
34- //
35- // Note that this could fail if the spec refers to a custom resource. For custom resources you may need
36- // to specify a different patch merge strategy in the content-type header.
37- //
38- // See: https://github.com/kubernetes/kubernetes/issues/97423
39- const response = await client . patch ( spec ) ;
40- created . push ( response . body ) ;
41- } catch ( e ) {
42- // we did not get the resource, so it does not exist, so create it
43- const response = await client . create ( spec ) ;
44- created . push ( response . body ) ;
45- }
46- }
47-
48- return created ;
8+ // update deployment "my-deployment" in namespace "my-namespace" to 3 replicas
9+ const deployment = {
10+ apiVersion : 'apps/v1' ,
11+ kind : 'Deployment' ,
12+ metadata : {
13+ name : 'my-deployment' ,
14+ namespace : 'my-namespace'
15+ } ,
16+ spec : {
17+ replicas : 3
18+ }
4919}
20+
21+ client . patch ( deployment )
0 commit comments