How to Generate a Kubernetes Deployment Manifest in Python

Generate a Kubernetes Deployment manifest as YAML from a Python dictionary using PyYAML.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 13 views 0 copies

Requires third-party packages — install first
pip install PyYAML

Python code

40 lines
Python 3.9+
import yaml

deployment = {
    "apiVersion": "apps/v1",
    "kind": "Deployment",
    "metadata": {
        "name": "mock-app",
        "labels": {"app": "mock-app"}
    },
    "spec": {
        "replicas": 3,
        "selector": {
            "matchLabels": {"app": "mock-app"}
        },
        "template": {
            "metadata": {
                "labels": {"app": "mock-app"}
            },
            "spec": {
                "containers": [
                    {
                        "name": "mock-container",
                        "image": "nginx:latest",
                        "ports": [
                            {"containerPort": 80}
                        ],
                        "env": [
                            {"name": "MOCK_ENV", "value": "production"}
                        ]
                    }
                ]
            }
        }
    }
}

manifest = yaml.safe_dump(deployment, sort_keys=False)
print(manifest)
print(f"Replicas: {deployment['spec']['replicas']}")
print(f"Image: {deployment['spec']['template']['spec']['containers'][0]['image']}")

Output

stdout
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mock-app
  labels:
    app: mock-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: mock-app
  template:
    metadata:
      labels:
        app: mock-app
    spec:
      containers:
      - name: mock-container
        image: nginx:latest
        ports:
        - containerPort: 80
        env:
        - name: MOCK_ENV
          value: production
Replicas: 3
Image: nginx:latest

How it works

The yaml.safe_dump function converts a Python dictionary into a YAML string, preserving key order with sort_keys=False. The nested dictionary structure mirrors the Kubernetes Deployment spec, allowing direct access to fields like replicas and image. This approach makes it easy to programmatically customize manifests before applying them with kubectl.

Common mistakes

  • Forgetting to install PyYAML (pip install PyYAML) and getting a ModuleNotFoundError
  • Using `sort_keys=True` which reorders keys alphabetically, breaking expected YAML order
  • Not using `safe_dump` and accidentally dumping arbitrary Python objects

Variations

  1. Load an existing YAML file with `yaml.safe_load` and modify fields programmatically
  2. Use templating tools like Jinja2 for more complex manifest generation

Real-world use cases

  • Generating deployment manifests dynamically in CI/CD pipelines based on environment variables.
  • Creating configuration management tools that update image tags or replica counts before applying.
  • Building internal platform services that generate Kubernetes resources for tenant onboarding.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Production deployment patterns

Related tutorials and quizzes for this topic.