- Posted on
- • Artificial Intelligence
Artificial Intelligence Bash Automation for Home Labs
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Artificial Intelligence Bash Automation for Home Labs
What if your homelab could draft Nginx configs, summarize noisy logs at 3 a.m., and turn plain English into actionable tasks—all from Bash? With lightweight local LLMs and a few CLI tools, you can wire AI into your scripts to save time, reduce toil, and make your lab more resilient.
In this post you’ll learn why AI + Bash is a natural fit for home labs, how to install the essentials, and get 3 practical automations you can drop into your toolkit today.
Why AI + Bash makes sense in a homelab
Shell-native workflow: LLM CLIs (like Ollama) are stream-friendly, work with pipes, and play nicely with tools you already use (jq, grep, systemd, cron).
Local, private, and cheap: Run models on your own hardware—offline, zero per-token cost, and no data leaves your network.
“Explain, summarize, generate” glue: Use models to draft configs, condense incidents, and scaffold playbooks—then validate with your usual linters and tests.
Safety by design: Keep AI out of the execution path. Treat it like a smart assistant: it proposes; you review and run.
Step 1 — Install prerequisites
These tools will cover most AI-to-shell workflows: curl, jq, git, podman, shellcheck, and (optionally) nginx for the example.
Debian/Ubuntu (apt):
sudo apt update
sudo apt install -y curl jq git podman shellcheck nginx
Fedora/RHEL/CentOS Stream (dnf):
sudo dnf install -y curl jq git podman ShellCheck nginx
openSUSE (zypper):
sudo zypper refresh
sudo zypper install -y curl jq git podman ShellCheck nginx
Notes:
If you don’t run Nginx on your reverse proxy host, skip
nginxabove.If
ShellCheck/nginxaren’t in your base repos on RHEL-like systems, enable EPEL or your preferred repo first.
Step 2 — Install a local LLM runtime (Ollama)
Ollama gives you a simple CLI for running local models.
Install Ollama:
curl -fsSL https://ollama.com/install.sh | sh
Start/restart the Ollama service (if needed):
sudo systemctl enable --now ollama
Pull a model (pick one that fits your hardware; llama3 is a good general model):
ollama pull llama3
Test a quick prompt:
echo "List 5 ways to harden an Nginx reverse proxy." | ollama run llama3
Tip: Running on CPU works; a GPU speeds things up but isn’t required for these examples.
Step 3 — A tiny Bash “AI standard library”
Drop this into ~/bin/ai.sh (and chmod +x ~/bin/ai.sh) to make LLM calls easy and composable.
#!/usr/bin/env bash
set -euo pipefail
# Default model for local runs
: "${AI_MODEL:=llama3}"
# Local (Ollama) one-shot completion.
# Usage:
# ai_chat_ollama "write me a nginx server block"
# printf "Summarize:\n%s" "$(journalctl -u sshd -n 200)" | ai_chat_ollama
ai_chat_ollama() {
local model="${1:-$AI_MODEL}"
# If more than one arg is given, treat all as the prompt.
if [ $# -gt 1 ]; then
shift
prompt="$*"
elif [ -t 0 ]; then
# tty and one arg: prompt is that arg
prompt="${prompt:-}"
else
# read from stdin
prompt="$(cat)"
fi
ollama run "$model" 2>/dev/null <<<"$prompt"
}
# Optional: OpenAI-compatible HTTP endpoint (cloud or self-hosted).
# Expects: OPENAI_API_KEY (required), OPENAI_MODEL (default: gpt-4o-mini),
# OPENAI_BASE_URL (default: https://api.openai.com/v1)
ai_chat_openai() {
: "${OPENAI_MODEL:=gpt-4o-mini}"
: "${OPENAI_BASE_URL:=https://api.openai.com/v1}"
: "${OPENAI_API_KEY:?Set OPENAI_API_KEY}"
local prompt
prompt="$(cat)"
curl -fsS "$OPENAI_BASE_URL/chat/completions" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d "$(jq -n --arg m "$OPENAI_MODEL" --arg p "$prompt" \
'{model:$m, messages:[{role:"user", content:$p}], temperature:0.2}')" \
| jq -r '.choices[0].message.content'
}
Optional: Store remote API keys safely
# ~/.config/ai.env
export OPENAI_API_KEY="paste-key-here"
export OPENAI_MODEL="gpt-4o-mini"
# export OPENAI_BASE_URL="https://api.openai.com/v1" # or self-hosted/vLLM
Load it in your shell profile:
# ~/.bashrc or ~/.profile
[ -f "$HOME/.config/ai.env" ] && . "$HOME/.config/ai.env"
export PATH="$HOME/bin:$PATH"
Security: chmod 600 ~/.config/ai.env
Step 4 — Real-world automations you can use today
Below are three small, composable automations. Each uses AI to propose structured, reviewable output. You remain in control.
1) Generate and validate an Nginx reverse proxy
This script drafts a server block for a given domain and upstream, validates it with nginx -t, and stages it. You review before enabling.
Create ai-nginx.sh:
#!/usr/bin/env bash
set -euo pipefail
domain="${1:?Usage: $0 example.com 127.0.0.1:8080}"
upstream="${2:?Usage: $0 example.com 127.0.0.1:8080}"
prompt=$(cat <<'EOF'
You are an Nginx expert. Output a single valid Nginx server block only, no commentary.
Requirements:
- Reverse proxy HTTPS traffic for the given $DOMAIN to $UPSTREAM (HTTP).
- Include sensible security headers.
- Enable gzip for text/* and application/json.
- Add basic rate limiting (per IP).
- Listen on 443 ssl http2; assume cert paths /etc/letsencrypt/live/$DOMAIN/fullchain.pem and privkey.pem.
EOF
)
server_block=$(DOMAIN="$domain" UPSTREAM="$upstream" envsubst <<EOF | ai_chat_ollama
$prompt
EOF
)
tmpfile="$(mktemp)"
echo "$server_block" > "$tmpfile"
echo "Draft written to $tmpfile"
echo "Validating syntax..."
sudo nginx -t -q -c <(printf "events {}\nhttp { include mime.types; %s }" "$(cat "$tmpfile")") && \
echo "Syntax looks OK."
echo "If acceptable, install with:"
echo " sudo install -m 644 $tmpfile /etc/nginx/sites-available/$domain.conf"
echo " sudo ln -s /etc/nginx/sites-available/$domain.conf /etc/nginx/sites-enabled/$domain.conf"
echo " sudo nginx -t && sudo systemctl reload nginx"
Notes:
Run
sudo certbot(or your ACME client) to provision certs, then reload Nginx.Always validate generated configs before enabling.
If you need Nginx installed:
apt:
sudo apt install -y nginxdnf:
sudo dnf install -y nginxzypper:
sudo zypper install -y nginx
2) Log triage: Turn noisy journals into an actionable summary
Summarize the last 400 lines of a unit log and print structured next steps.
Create ai-logsum.sh:
#!/usr/bin/env bash
set -euo pipefail
unit="${1:?Usage: $0 <systemd-unit.service>}"
lines="${2:-400}"
journalctl -u "$unit" --no-pager -n "$lines" \
| sed -E 's/[0-9a-f]{32,}/<REDACTED-HASH>/g' \
| sed -E 's/[A-F0-9]{12}(:[A-F0-9]{2}){5}/<REDACTED-MAC>/g' \
| ai_chat_ollama <<'EOF'
Summarize these logs into strict JSON with keys:
{"top_issues":[{"issue":"","evidence":"","likely_cause":"","suggested_fix":""}],
"priority":"low|medium|high",
"one_line_advice":""}
Only output JSON.
EOF
Because we ask for strict JSON, you can post-process with jq:
./ai-logsum.sh sshd.service | jq -r '.top_issues[] | "- " + .issue + " -> " + .suggested_fix'
3) Daily health report: Human-readable digest you can email or send to chat
Create ai-health.sh:
#!/usr/bin/env bash
set -euo pipefail
collect() {
echo "DATE: $(date -Is)"
echo
echo "DISK USAGE:"
df -h --output=source,pcent,avail,target | sed '1!b;s/^/ /'
echo
echo "FAILED UNITS:"
systemctl --failed --no-legend | sed 's/^/ /' || true
echo
echo "TOP TALKERS (TCP/UDP listeners):"
ss -tulpn | sed '1!b;s/^/ /'
echo
echo "RECENT AUTH FAILS:"
journalctl -u sshd -p warning -n 100 --no-pager | sed 's/^/ /' || true
}
collect \
| ai_chat_ollama <<'EOF'
You are a pragmatic SRE. Turn this raw system status into a short, actionable daily report:
- Bullet the top 3 risks with evidence.
- Note quick wins (one-liners).
- Flag any anomalies worth deeper dive.
Keep it under 200 words.
EOF
Automate with systemd timers or cron to send the output via mail or a webhook.
Safety, reproducibility, and performance tips
Never auto-execute: Don’t pipe model output straight into
sh. Save, validate (e.g.,nginx -t,shellcheck), review, then apply.Prefer local by default: Use Ollama first; flip to a remote API only when you need a specific model.
Ask for JSON, then parse: Constrain outputs and consume with
jq.Redact secrets: Strip tokens, hashes, and URLs before sending prompts anywhere.
Cache expensive prompts: Hash the prompt and store results in
~/.cache/ai/to avoid rework.Be explicit: Low temperature, clear constraints, “no commentary” instructions reduce fluff.
Add
set -euo pipefailto every script; lint withshellcheck:- apt:
sudo apt install -y shellcheck - dnf:
sudo dnf install -y ShellCheck - zypper:
sudo zypper install -y ShellCheck
- apt:
Conclusion and next steps
AI won’t replace your shell skills—it amplifies them. Start small:
Install the prerequisites and Ollama.
Add
ai.shto your PATH.Try one automation (log triage or daily health) on a non-critical host.
Iterate: tighten prompts, add validation, and standardize patterns you trust.
Call to action:
Pick one service in your lab that causes the most toil and script a “draft + validate” AI helper for it this week.
Share what you build with your team or the homelab community—your prompt patterns will help others, and theirs will help you.
Happy automating!