How to Generate a Kubernetes Deployment Manifest in Python
Generate a Kubernetes Deployment manifest as YAML from a Python dictionary using PyYAML.
Requires third-party packages — install first
pip install PyYAML
Python code
40 linesimport 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
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
- Load an existing YAML file with `yaml.safe_load` and modify fields programmatically
- 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
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.