Packaging & Config

cdk8s

Framework AWS pour définir des manifests Kubernetes en TypeScript, Python, Java ou Go - abstractions réutilisables, autocomplétion IDE, génère du YAML standard. Apache 2.0.

cdk8s (Cloud Development Kit for Kubernetes) est un framework open source développé par AWS qui permet de définir des manifests Kubernetes à l'aide de langages de programmation (TypeScript, Python, Java, Go) au lieu de YAML brut. Le code est compilé en YAML Kubernetes standard via cdk8s synth. L'avantage principal : utiliser la puissance du code (boucles, conditions, fonctions, héritage, tests unitaires) pour générer des configurations complexes, avec l'autocomplétion et la validation de type dans les IDE.


Informations essentielles

Origine : AWS (open source)  ·  Licence : Apache 2.0  ·  Architectures : x86_64, ARM64

Liens : Site officiel  ·  Documentation  ·  GitHub  ·  Constructs Hub

Support : Projet AWS open source, communauté active.

Stack par défaut

ComposantValeur
LangagesTypeScript (recommandé), JavaScript, Python, Java, Go
CLIcdk8s
SortieFichiers YAML dans dist/
Bibliothèquescdk8s-plus (abstractions K8s haut niveau), constructs tiers
Package managernpm (TS/JS), pip (Python), Maven/Gradle (Java), Go modules

Prérequis

RessourceValeur
Node.js18+ (pour TypeScript/JavaScript)
kubectlPour appliquer le YAML généré

Installation et initialisation

# Installer la CLI cdk8s
npm install -g cdk8s-cli

# Créer un nouveau projet TypeScript
mkdir my-k8s-config && cd my-k8s-config
cdk8s init typescript-app

# Structure créée :
# ├── main.ts          # Point d'entrée
# ├── cdk8s.yaml       # Config cdk8s
# ├── package.json
# └── imports/         # Types K8s générés (kubectl apply -k ...)

Exemple TypeScript - définir une application

// main.ts

export class MyAppChart extends Chart {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    const label = { app: 'my-app' };

    // Deployment
    const deployment = new Deployment(this, 'my-app', {
      replicas: 3,
      containers: [{
        image: 'ghcr.io/org/my-app:1.0.0',
        portNumber: 8080,
        resources: {
          cpu: {
            request: Cpu.millis(250),
            limit: Cpu.millis(500),
          },
          memory: {
            request: Size.mebibytes(256),
            limit: Size.mebibytes(512),
          },
        },
        envVariables: {
          LOG_LEVEL: { value: 'info' },
        },
      }],
    });

    // Service
    new Service(this, 'service', {
      type: ServiceType.CLUSTER_IP,
      selector: deployment,
      ports: [{ port: 80, targetPort: 8080 }],
    });
  }
}

const app = new App();
new MyAppChart(app, 'my-app');
app.synth();
# Générer le YAML
npm run synth
# ou
cdk8s synth

# Le YAML est dans dist/
cat dist/my-app.k8s.yaml

# Appliquer sur le cluster
kubectl apply -f dist/

Exemple Python

# Créer un projet Python
cdk8s init python-app
pip install cdk8s cdk8s-plus-28
# main.py
from constructs import Construct
from cdk8s import App, Chart
from cdk8s_plus_28 import Deployment, Service, ServiceType

class MyAppChart(Chart):
    def __init__(self, scope: Construct, id: str):
        super().__init__(scope, id)

        deployment = Deployment(self, "deployment",
            replicas=3,
            containers=[{
                "image": "ghcr.io/org/my-app:1.0.0",
                "port_number": 8080,
            }]
        )

        Service(self, "service",
            type=ServiceType.CLUSTER_IP,
            selector=deployment,
            ports=[{"port": 80, "target_port": 8080}]
        )

app = App()
MyAppChart(app, "my-app")
app.synth()

Abstractions réutilisables (constructs)

// Un construct réutilisable "WebApp"

export interface WebAppProps {
  image: string;
  replicas?: number;
  hostname: string;
}

export class WebApp extends Construct {
  constructor(scope: Construct, id: string, props: WebAppProps) {
    super(scope, id);

    const deployment = new Deployment(this, 'deployment', {
      replicas: props.replicas ?? 2,
      containers: [{
        image: props.image,
        portNumber: 8080,
      }],
    });

    const service = new Service(this, 'service', {
      selector: deployment,
      ports: [{ port: 80, targetPort: 8080 }],
    });

    new Ingress(this, 'ingress', {
      rules: [{
        host: props.hostname,
        backend: IngressBackend.fromService(service),
      }],
    });
  }
}

// Utilisation dans main.ts
new WebApp(chart, 'frontend', { image: 'ghcr.io/org/frontend:1.0', hostname: 'app.example.com' });
new WebApp(chart, 'backend',  { image: 'ghcr.io/org/backend:2.0',  hostname: 'api.example.com', replicas: 5 });

Intégration CI/CD

# .github/workflows/deploy.yml
steps:
  - uses: actions/setup-node@v4
    with:
      node-version: 20

  - name: Install deps
    run: npm ci

  - name: Synth
    run: npm run synth

  - name: Apply
    run: kubectl apply -f dist/
    env:
      KUBECONFIG: ${{ secrets.KUBECONFIG_BASE64 }}

Mise à jour

npm update cdk8s cdk8s-plus-28 cdk8s-cli

Ressources

Newsletter · 2 000+ abonnés

Reste au courant de ce qui bouge en prod

RudeOps veille devops hebdo, droit au but.

Gratuit · Sans spam · Désinscription en un clic