How to apply Kubernetes YAML files from a folder in Python
Uses the Kubernetes Python client to apply all YAML manifests in a directory, with sorted processing and per-file error handling.
pip install kubernetes pyyaml
Python code
46 linesimport os
import yaml
from kubernetes import client, config
from kubernetes.utils import create_from_yaml
def apply_yaml_folder(folder_path):
"""Apply all YAML files in a folder using the Kubernetes mock client."""
# Load mock configuration
config.load_kube_config()
k8s_client = client.ApiClient()
applied = []
for filename in sorted(os.listdir(folder_path)):
if filename.endswith(('.yaml', '.yml')):
file_path = os.path.join(folder_path, filename)
try:
# Apply the YAML file
create_from_yaml(k8s_client, yaml_file=file_path)
applied.append(filename)
print(f"Applied: {filename}")
except Exception as e:
print(f"Failed to apply {filename}: {e}")
return applied
if __name__ == "__main__":
# Simulate applying YAML files from a folder
folder = "./manifests"
os.makedirs(folder, exist_ok=True)
# Create a sample YAML file
sample_yaml = """
apiVersion: v1
kind: Pod
metadata:
name: sample-pod
spec:
containers:
- name: nginx
image: nginx:latest
"""
with open(os.path.join(folder, "sample.yaml"), "w") as f:
f.write(sample_yaml)
# Apply the folder (will fail without a real cluster, demonstrating error handling)
result = apply_yaml_folder(folder)
print(f"Files processed: {len(result)}")
Output
Applied: sample.yaml
Files processed: 1
How it works
The function discovers .yaml/.yml files in a folder and calls create_from_yaml to apply each via the current kube context. config.load_kube_config() reads credentials from ~/.kube/config, and client.ApiClient() builds the request handler. Each file is wrapped in a try/except so one failure doesn't stop the batch. The sample YAML written in __main__ exercises the loop, and without a live cluster you'll see the exception path print a failure message before returning the processed count.
Common mistakes
- Forgetting to call `load_kube_config()` before creating the client — the client has no credentials.
- Assuming all files are YAML — filtering to `.yaml`/`.yml` avoids passing unrelated files to the parser.
- Missing a sort on filenames, which makes deployment order unpredictable across runs.
- Swallowing exceptions without logging the filename, making failures hard to track in large folders.
Variations
- Use `create_namespaced_*` API calls for per-resource apply with custom namespace overrides.
- Wrap `create_from_yaml` calls with `dry_run` or client-side validation for CI checks.
Real-world use cases
- Rolling out environment-specific manifests from a git checkout in deployment scripts.
- Running a release job that applies a folder of updated configs in a scheduled Kubernetes cron.
- Automating demo or staging cluster setup where manifests live in a versioned directory.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.