- Posted on
- • Artificial Intelligence
Using Artificial Intelligence to Build Kubernetes Helper Scripts
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Using Artificial Intelligence to Build Kubernetes Helper Scripts (with Bash)
If you manage Kubernetes from the command line, you’ve probably memorized too many kubectl incantations, paged through endless YAML, and lost time hopping between docs and terminals. Good news: AI can offload a lot of that mental overhead. With a few small Bash wrappers, you can turn natural language into reliable kubectl commands, generate validated manifests, and even summarize failures — all without leaving your shell.
This article shows you why this approach works, how to set it up on Linux, and provides 3–5 practical scripts you can drop into your toolkit today.
Why pair AI with Bash and Kubernetes?
Kubernetes commands are structured.
kubectlhas predictable verbs, flags, and output formats. That makes it ideal for AI prompting and guardrails.You can keep humans in the loop. Scripts can require confirmation, use
--dry-run=client, and highlight diffs before applying changes.It works locally or in the cloud. You can run a local model via Ollama or use a hosted API via tools like Shell-GPT (
sgpt).It’s incremental. Start with one wrapper script. If it helps you avoid even a few context switches a day, it’s already paying off.
Prerequisites and installation
You’ll need kubectl, jq, yq, and at least one AI client (local via Ollama, or cloud via sgpt). Below are distro-specific installation steps.
kubectl
Apt (Debian/Ubuntu):
sudo apt-get update
sudo apt-get install -y apt-transport-https ca-certificates curl gpg
sudo mkdir -p -m 755 /etc/apt/keyrings
curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.30/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.30/deb/ /" | sudo tee /etc/apt/sources.list.d/kubernetes.list
sudo apt-get update
sudo apt-get install -y kubectl
DNF (Fedora/RHEL/CentOS Stream):
sudo dnf install -y dnf-plugins-core
sudo dnf config-manager --add-repo https://pkgs.k8s.io/core:/stable:/v1.30/rpm/
sudo rpm --import https://pkgs.k8s.io/core:/stable:/v1.30/rpm/repodata/repomd.xml.key
sudo dnf install -y kubectl
Zypper (openSUSE/SLE):
sudo rpm --import https://pkgs.k8s.io/core:/stable:/v1.30/rpm/repodata/repomd.xml.key
sudo zypper addrepo https://pkgs.k8s.io/core:/stable:/v1.30/rpm/ kubernetes
sudo zypper refresh
sudo zypper install -y kubectl
jq and yq
Apt:
sudo apt-get update
sudo apt-get install -y jq yq || echo "If yq not found, try: sudo snap install yq"
DNF:
sudo dnf install -y jq yq
Zypper:
sudo zypper install -y jq yq
Cloud AI option: Shell-GPT (sgpt)
Install pipx first:
Apt:
sudo apt-get update
sudo apt-get install -y pipx
pipx ensurepath
DNF:
sudo dnf install -y pipx
pipx ensurepath
Zypper:
sudo zypper install -y pipx
pipx ensurepath
Then install Shell-GPT:
pipx install shell-gpt
Set your API key (replace with your key):
export OPENAI_API_KEY="sk-..."
Tip: put that export in your shell profile (but never commit it to git).
Local AI option: Ollama
curl -fsSL https://ollama.com/install.sh | sh
# Pull a model (example: Llama 3.1)
ollama pull llama3.1
You can later change models by setting OLLAMA_MODEL=... in your environment.
Optional (quality and tests)
Apt:
sudo apt-get install -y shellcheck bats
DNF:
sudo dnf install -y ShellCheck bats
Zypper:
sudo zypper install -y ShellCheck bats
1) k-ask: Turn natural language into a safe kubectl command
This helper asks an AI to produce exactly one kubectl command, previews it in dry-run mode when appropriate, and requires confirmation before execution. It uses sgpt if available, otherwise ollama.
Save as k-ask and chmod +x k-ask:
#!/usr/bin/env bash
set -euo pipefail
# Usage:
# k-ask "scale frontend to 3 replicas in staging"
# Env:
# OLLAMA_MODEL (default: llama3.1)
has_cmd() { command -v "$1" >/dev/null 2>&1; }
AI_TOOL=""
if has_cmd sgpt; then
AI_TOOL="sgpt"
elif has_cmd ollama; then
AI_TOOL="ollama"
else
echo "Error: need sgpt or ollama installed." >&2
exit 1
fi
CTX="${KUBE_CONTEXT:-$(kubectl config current-context 2>/dev/null || true)}"
NS="${KUBE_NAMESPACE:-default}"
REQ="${*:-}"
if [[ -z "$REQ" ]]; then
echo "Usage: k-ask \"<request>\"" >&2
exit 1
fi
read_only_verbs="get|describe|logs|top|config|api-resources|api-versions|cluster-info"
SAFETY="If the command is not read-only, add --dry-run=client -o yaml."
PROMPT=$(
cat <<EOF
Write exactly one kubectl command for this request:
Request: $REQ
Constraints:
- Namespace: $NS by default unless user specified otherwise.
- If KUBE_CONTEXT is set, include: --context "$CTX".
- Do not include explanations, comments, code fences, or multiple commands.
- Prefer explicit resource types and labels.
- $SAFETY
EOF
)
if [[ "$AI_TOOL" == "sgpt" ]]; then
CMD_OUT="$(sgpt --shell "$PROMPT")"
else
MODEL="${OLLAMA_MODEL:-llama3.1}"
# Ask model to return a single line command with no commentary
CMD_OUT="$(ollama run "$MODEL" "$PROMPT
Return only the final kubectl command on a single line, no commentary.")"
CMD_OUT="$(echo "$CMD_OUT" | head -n1)"
fi
CMD_OUT="$(echo "$CMD_OUT" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
# Guardrails
if [[ ! "$CMD_OUT" =~ ^kubectl[[:space:]] ]]; then
echo "AI did not return a kubectl command. Output was:" >&2
echo "$CMD_OUT" >&2
exit 1
fi
if echo "$CMD_OUT" | grep -E -- '(\|\||&&|;|`|\$\(|\|[[:space:]]*sh)' >/dev/null; then
echo "Refusing to run potentially dangerous shell constructs." >&2
echo "$CMD_OUT" >&2
exit 1
fi
echo "Proposed:"
echo " $CMD_OUT"
read -r -p "Run it? [y/N] " ans
if [[ "$ans" =~ ^[Yy]$ ]]; then
eval "$CMD_OUT"
else
echo "Aborted."
fi
Examples:
k-ask "list pods in kube-system with restarts > 0"k-ask "scale deployment/web to 5 replicas in namespace payments"k-ask "restart all pods with label app=api in staging"
Tip: For non-read-only actions, the script asks the AI to include --dry-run=client -o yaml. You can copy the proposed command, drop the dry-run, and re-run if you approve.
2) k-gen-apply: Generate a manifest, validate, diff, then apply
This script asks AI to produce valid Kubernetes YAML, shows you a diff against the cluster, and applies only after confirmation.
Save as k-gen-apply and chmod +x k-gen-apply:
#!/usr/bin/env bash
set -euo pipefail
has_cmd() { command -v "$1" >/dev/null 2>&1; }
ai_run() {
local prompt="$1"
if has_cmd sgpt; then
sgpt --code "$prompt"
elif has_cmd ollama; then
local model="${OLLAMA_MODEL:-llama3.1}"
ollama run "$model" "$prompt
Output ONLY valid Kubernetes YAML (no backticks, no comments).
If multiple objects, separate with '---'."
else
echo "Error: need sgpt or ollama." >&2
exit 1
fi
}
NS="${KUBE_NAMESPACE:-default}"
CTX="${KUBE_CONTEXT:-$(kubectl config current-context 2>/dev/null || true)}"
REQ="${*:-}"
if [[ -z "$REQ" ]]; then
echo "Usage: k-gen-apply \"<describe the resource you want>\"" >&2
exit 1
fi
PROMPT=$(
cat <<EOF
Generate a minimal, production-safe Kubernetes manifest.
Request: $REQ
Constraints:
- Namespace: $NS (unless otherwise specified).
- Include apiVersion and kind for each object.
- Add reasonable labels (app/name/component).
- For Deployments, include resource requests/limits and readiness/liveness if applicable.
- Do not include Service of type LoadBalancer unless requested.
- Output ONLY YAML (no code fences, no explanations).
EOF
)
YAML="$(ai_run "$PROMPT")"
echo "$YAML" | yq -P >/tmp/k-gen-apply.yaml
echo "Validating with dry-run..."
if ! kubectl ${CTX:+--context "$CTX"} apply --dry-run=client -f /tmp/k-gen-apply.yaml >/dev/null; then
echo "Dry-run failed. Review /tmp/k-gen-apply.yaml" >&2
exit 1
fi
echo "Showing diff vs. cluster (this may show creates/updates):"
kubectl ${CTX:+--context "$CTX"} diff -f /tmp/k-gen-apply.yaml || true
read -r -p "Apply these changes? [y/N] " ans
if [[ "$ans" =~ ^[Yy]$ ]]; then
kubectl ${CTX:+--context "$CTX"} apply -f /tmp/k-gen-apply.yaml
else
echo "Manifest saved at /tmp/k-gen-apply.yaml"
fi
Examples:
k-gen-apply "a Deployment named api v1.2 image ghcr.io/acme/api:1.2, 3 replicas, expose on ClusterIP 8080->80"k-gen-apply "a CronJob that runs every hour to clean temp files, with resource limits"
3) k-explain-pod: Summarize failures and likely fixes
When a pod is CrashLooping or failing readiness, this helper aggregates describe and recent logs, then asks AI for a short diagnosis and next steps.
Save as k-explain-pod and chmod +x k-explain-pod:
#!/usr/bin/env bash
set -euo pipefail
has_cmd() { command -v "$1" >/dev/null 2>&1; }
ai_say() {
local prompt="$1"
if has_cmd sgpt; then
sgpt "$prompt"
elif has_cmd ollama; then
local model="${OLLAMA_MODEL:-llama3.1}"
ollama run "$model" "$prompt"
else
echo "Error: need sgpt or ollama." >&2
exit 1
fi
}
NS="${KUBE_NAMESPACE:-default}"
CTX="${KUBE_CONTEXT:-$(kubectl config current-context 2>/dev/null || true)}"
if [[ $# -lt 1 ]]; then
echo "Usage: k-explain-pod <pod-name> [container]" >&2
exit 1
fi
POD="$1"
CTR="${2:-}"
DESC="$(kubectl ${CTX:+--context "$CTX"} -n "$NS" describe pod "$POD" 2>&1 || true)"
if [[ -n "$CTR" ]]; then
LOGS="$(kubectl ${CTX:+--context "$CTX"} -n "$NS" logs "$POD" -c "$CTR" --tail=200 2>&1 || true)"
else
LOGS="$(kubectl ${CTX:+--context "$CTX"} -n "$NS" logs "$POD" --tail=200 2>&1 || true)"
fi
PROMPT=$(
cat <<EOF
You are a Kubernetes SRE assistant. Given a pod's describe output and recent logs,
write a concise diagnosis (3-6 bullets) and propose concrete next steps. Avoid speculation.
Describe:
$DESC
Logs:
$LOGS
EOF
)
ai_say "$PROMPT"
Examples:
k-explain-pod web-7d8d76c7b9-lk2sjKUBE_NAMESPACE=payments k-explain-pod api-6c4dbd6c88-6tg4f sidecar-proxy
4) Hardening and good habits
Keep humans in the loop:
- Add
--dry-run=client -o yamlto non-read-only actions. - Use
kubectl diffbeforeapply. - Ask for confirmation before executing AI-generated commands.
- Add
Guardrails in scripts:
- Reject outputs that don’t start with
kubectl. - Block
;,&&, pipelines to shells, backticks, or$(. - Restrict default namespace and context via env:
KUBE_NAMESPACE,KUBE_CONTEXT.
- Reject outputs that don’t start with
RBAC and scope:
- Use read-only contexts for exploratory tasks.
- Work in dev/staging first; promote via GitOps for prod.
Lint and test:
- Run
shellcheck ./k-*to catch script issues. - Add minimal tests with
batsif you put these in CI.
- Run
5) Real-world examples
Quickly find noisy pods:
k-ask "show pods in kube-system with restarts > 5 sorted by restarts desc"
Controlled rollout:
k-gen-apply "Deployment api image ghcr.io/acme/api:2.0 with maxSurge 1 maxUnavailable 0"
Triage a CrashLoop:
KUBE_NAMESPACE=staging k-explain-pod worker-6b7ddf5bdc-9p6cr
Notes on privacy and cost
Local models (Ollama) avoid sending cluster details to third parties, at the cost of higher local CPU/RAM usage.
Hosted APIs are often faster and stronger, but only send redacted, non-sensitive data. Never paste secrets or credentials into prompts.
Consider prompt redaction: pipe through a small function that masks common secret patterns before calling the AI.
Conclusion and next steps
AI won’t replace your Kubernetes skills — it amplifies them. Start with k-ask to translate intent into safe commands, add k-gen-apply to scaffold manifests with diffs and dry-runs, and drop in k-explain-pod for rapid diagnostics. From there, iterate: add caching, namespace allowlists, or integrate with your team’s GitOps flow.
Call to action:
Install the prerequisites above, pick either
sgptorollama, and try one script today.Adapt the prompts to your conventions (labels, resource policies).
Share your best prompts and wrappers with your team — let the terminal do more of the thinking for you.