CDK for Kubernetes (cdk8s)

2.70.55 · active · verified Wed Apr 15

This is the core library of Cloud Development Kit (CDK) for Kubernetes (cdk8s). cdk8s is an open-source software development framework for defining Kubernetes applications using rich object-oriented APIs in languages like Python, TypeScript, Java, and Go. cdk8s apps synthesize into standard Kubernetes manifests which can be applied to any Kubernetes cluster. The project is actively maintained, with frequent releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a basic Kubernetes Deployment and Service using `cdk8s`. It requires installing the `cdk8s-cli` (via npm), initializing a project with `cdk8s init python-app`, running `cdk8s import k8s` to generate Kubernetes API constructs, and then placing this code in `main.py`. The `app.synth()` call generates the Kubernetes YAML manifests, which can then be applied to any Kubernetes cluster.

import os
from constructs import Construct
from cdk8s import App, Chart, IntOrString
from imports import k8s # This directory is generated by 'cdk8s import k8s'

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

        # Define a Kubernetes Deployment
        k8s.KubeDeployment(self, "my-deployment",
            spec=k8s.DeploymentSpec(
                replicas=1,
                selector=k8s.LabelSelector(
                    match_labels={"app": "my-app"}
                ),
                template=k8s.PodTemplateSpec(
                    metadata=k8s.ObjectMeta(
                        labels={"app": "my-app"}
                    ),
                    spec=k8s.PodSpec(
                        containers=[k8s.Container(
                            name="my-container",
                            image="nginx:latest",
                            ports=[k8s.ContainerPort(container_port=80)]
                        )]
                    )
                )
            )
        )

        # Define a Kubernetes Service
        k8s.KubeService(self, "my-service",
            spec=k8s.ServiceSpec(
                type="LoadBalancer",
                ports=[k8s.ServicePort(port=80, target_port=IntOrString.from_number(80))],
                selector={"app": "my-app"}
            )
        )

app = App()
MyChart(app, "my-cdk8s-app")
app.synth()

view raw JSON →