How-To: Automate Kubernetes with Python
While Kubernetes can be managed entirely with kubectl commands and YAML manifests, configuring the applications running inside the cluster often requires manual clicking in web UIs.
For example, when you deploy a new application, you often need to copy an API key from one application and paste it into another. As a DevOps engineer, you want to automate this to achieve "Zero-Touch Provisioning."
This guide explains how to bridge the gap between your local terminal, the Kubernetes cluster, and internal REST APIs using a single Python script.
The Goal
We want to write a script that: 1. Logs into a web application (e.g., Jellyseerr) to get an authentication cookie. 2. Reaches into a running Kubernetes pod (e.g., Radarr) to extract a hidden API key. 3. Sends that API key back to the first application to link them together.
Step 1: The Wrapper Script (uv)
We don't want to mess up our local laptop by installing random Python packages globally. We will use uv to create a standalone script that dynamically manages its own dependencies.
Create a file named configure-app.py:
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "requests",
# ]
# ///
import requests
import subprocess
import xml.etree.ElementTree as ET
def main():
print("Starting automation...")
if __name__ == "__main__":
main()
Make it executable: chmod +x configure-app.py
Step 2: Authenticate with the REST API
Use the requests.Session() object to automatically handle the cookies that the server sends back upon successful login.
session = requests.Session()
login_payload = {
"username": "admin",
"password": "password"
}
res = session.post("http://jellyseerr.homelab.local/api/v1/auth/jellyfin", json=login_payload)
if res.status_code != 200:
print("Login failed!")
return
Step 3: Extract Secrets from Kubernetes
Instead of trying to find an API endpoint that reveals the secret (which often doesn't exist for security reasons), we can use Python's subprocess module to execute kubectl exec.
This is the exact same command you would type in the terminal, but Python captures the output for us!
# Run the kubectl command to read the internal config file
cmd = "kubectl exec -n media deploy/radarr -- cat /config/config.xml"
result = subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
# The output is raw XML. We can parse it to find the specific <ApiKey> tag.
root = ET.fromstring(result.stdout)
api_key = root.find('ApiKey').text
print(f"Stolen API Key: {api_key}")
Step 4: Inject the Secret
Now we simply combine the API Key we stole from Kubernetes with the authenticated session we established in Step 2.
radarr_payload = {
"name": "Radarr",
"hostname": "radarr.media.svc.cluster.local",
"port": 7878,
"apiKey": api_key,
}
res = session.post("http://jellyseerr.homelab.local/api/v1/settings/radarr", json=radarr_payload)
if res.status_code in [200, 201]:
print("Successfully linked the applications!")
Running the Script
Because of the uv header block, you can simply run the script directly. uv will download the requests library into an isolated cache instantly and execute the code.
You have now successfully automated a complex UI setup process using Python and kubectl!
Real-World Examples
To see this in action, review the production automation scripts in the homelab repository:
homelab/scripts/configure-jellyseerr.py(Automates the Jellyfin, Radarr, and Sonarr setup wizards in Jellyseerr).homelab/scripts/configure-prowlarr.py(Automates the synchronization of proxy configurations and indexers to Radarr and Sonarr via the Prowlarr API).