cdk8s

cdk8s Kubernetes 清单生成

补充说明

cdk8s 用 TypeScript、Python、Java 等语言定义 Kubernetes 清单,编译成 YAML。适合需要复用逻辑、类型检查和编程抽象的团队。

核心概念:App、Chart、ApiObject、Construct。

常用示例

初始化项目:

npm install -g cdk8s-cli
cdk8s init typescript-app

定义 Chart:

import { App, Chart, ChartProps } from 'cdk8s';
import { Deployment, Service } from './imports/k8s';

export class MyChart extends Chart {
  constructor(scope: App, id: string, props?: ChartProps) {
    super(scope, id, props);
    const app = new Deployment(this, 'app', {
      spec: {
        replicas: 2,
        selector: { matchLabels: { app: 'demo' } },
        template: {
          metadata: { labels: { app: 'demo' } },
          spec: { containers: [{ name: 'app', image: 'nginx:1.27' }] },
        },
      },
    });
    new Service(this, 'svc', {
      spec: { selector: { app: 'demo' }, ports: [{ port: 80 }] },
    });
  }
}

const app = new App();
new MyChart(app, 'demo');
app.synth();

生成并应用:

cdk8s synth
kubectl apply -f dist/

易错点与排错