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.

Medium Python 3.9+ Aug 9, 2026 Automation & scripting 12 views 0 copies

Requires third-party packages — install first
pip install kubernetes pyyaml

Python code

46 lines
Python 3.9+
import 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

stdout
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

  1. Use `create_namespaced_*` API calls for per-resource apply with custom namespace overrides.
  2. 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

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 Automation & scripting

Related tutorials and quizzes for this topic.