forked from kubernetes-client/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatch-example.ts
More file actions
70 lines (64 loc) · 1.99 KB
/
patch-example.ts
File metadata and controls
70 lines (64 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import {
CoreV1Api,
RequestContext,
ResponseContext,
KubeConfig,
createConfiguration,
type Configuration,
ServerConfiguration,
} from '@kubernetes/client-node';
import { PromiseMiddlewareWrapper } from '@kubernetes/client-node/dist/gen/middleware.js';
const kc = new KubeConfig();
kc.loadFromDefault();
const k8sApi = kc.makeApiClient(CoreV1Api);
try {
const res = await k8sApi.listNamespacedPod({ namespace: 'default' });
const patch = [
{
op: 'replace',
path: '/metadata/labels',
value: {
foo: 'bar',
},
},
];
const headerPatchMiddleware = new PromiseMiddlewareWrapper({
pre: async (requestContext: RequestContext) => {
requestContext.setHeaderParam('Content-type', 'application/json-patch+json');
return requestContext;
},
post: async (responseContext: ResponseContext) => responseContext,
});
const currentContext = kc.getCurrentContext();
const currentCluster = kc.getCluster(currentContext);
if (currentCluster === undefined || currentCluster === null) {
throw new Error('Cluster is undefined');
}
const server = currentCluster.server;
if (server === undefined) {
throw new Error('Server is undefined');
}
const baseServerConfig: ServerConfiguration<{}> = new ServerConfiguration<{}>(server, {});
const configuration: Configuration = createConfiguration({
middleware: [headerPatchMiddleware],
baseServer: baseServerConfig,
authMethods: {
default: kc,
},
});
const podName = res.items[0]?.metadata?.name;
if (podName === undefined) {
throw new Error('Pod name is undefined');
}
await k8sApi.patchNamespacedPod(
{
name: podName,
namespace: 'default',
body: patch,
},
configuration,
);
console.log('Patched.');
} catch (err) {
console.error('Error: ', err);
}