- Posted on
- • Artificial Intelligence
Artificial Intelligence Bash Automation for Cloud Servers
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Artificial Intelligence Bash Automation for Cloud Servers
If your cloud servers keep waking you up at 3 a.m., you’re not alone. Logs explode, alerts cascade, and routine maintenance tasks steal precious hours. What if you could add a smart, reliable assistant directly into your Bash workflows—one that triages logs, sanity-checks risky commands, and drafts maintenance plans before coffee?
This article shows you how to weave AI into everyday Bash automation for cloud servers. You’ll get practical scripts, package installation steps for apt/dnf/zypper, and real-world patterns you can deploy today.
Why AI + Bash is a powerful combo
Signal over noise: LLMs can compress thousands of log lines into a crisp incident summary, extracting patterns humans might miss when tired or rushed.
Safer ops: A quick “AI explain-and-rate” on a command can catch destructive mistakes before they’re run.
Faster maintenance: Let AI pre-digest pending updates and highlight high-risk packages.
Low friction: You don’t need new tooling or workflows—just Bash,
curl, andjq.
A note on privacy and cost: Don’t ship secrets to third-party APIs. Redact logs before sending. For private environments, run a local model (e.g., Ollama) to keep data on-box. Monitor usage and costs.
Prerequisites and installation
We’ll use:
Bash (preinstalled)
curl
jq
Optionally, a model backend:
- Cloud API (e.g., OpenAI, requires
OPENAI_API_KEY) - Local LLM via Ollama
- Cloud API (e.g., OpenAI, requires
Install common utilities:
Debian/Ubuntu (apt):
sudo apt update sudo apt install -y curl jqRHEL/CentOS/Fedora (dnf):
sudo dnf install -y curl jqopenSUSE (zypper):
sudo zypper refresh sudo zypper install -y curl jq
Optional: Install Ollama (local LLM):
curl -fsSL https://ollama.com/install.sh | sh
# After install, ensure the service is running or start it:
# systemctl --user enable --now ollama (if installed as user service)
# or: sudo systemctl enable --now ollama
# Pull a model:
ollama pull llama3.1
Environment configuration (recommended):
sudo install -m 600 /dev/null /etc/default/ai-bash
sudo sh -c 'cat > /etc/default/ai-bash <<EOF
# Choose: openai or ollama
AI_BACKEND=openai
# For OpenAI:
OPENAI_API_KEY=your_real_key_here
# For Ollama (usually defaults to localhost):
OLLAMA_HOST=http://127.0.0.1:11434
EOF'
1) AI log triage: summarize anomalies on a schedule
This job summarizes the last N lines of a log, redacting sensitive bits, and outputs a short anomaly report. It supports either OpenAI or Ollama.
Script: /usr/local/bin/ai-log-summary.sh
#!/usr/bin/env bash
set -euo pipefail
: "${LINES:=1500}"
LOGFILE="${1:-/var/log/syslog}"
BACKEND="${AI_BACKEND:-${BACKEND:-openai}}"
# Load environment if present
[ -f /etc/default/ai-bash ] && . /etc/default/ai-bash
if [ ! -r "$LOGFILE" ]; then
echo "Log file not readable: $LOGFILE" >&2
exit 1
fi
# Simple redaction: IPs and emails
redact() {
sed -E \
-e 's/[0-9]{1,3}(\.[0-9]{1,3}){3}/[REDACTED_IP]/g' \
-e 's/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/[REDACTED_EMAIL]/g'
}
prompt() {
cat <<'P'
You are an SRE assistant. Given recent server logs:
- Summarize key events and anomalies.
- Group by component.
- Call out errors, warnings, spikes, timeouts, OOMs.
- Hypothesize likely root causes and next diagnostic steps.
- Keep it under 250 words.
P
echo
}
summarize_openai() {
[ -n "${OPENAI_API_KEY:-}" ] || { echo "OPENAI_API_KEY not set" >&2; exit 2; }
local logs="$1"
curl -sS https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${OPENAI_API_KEY}" \
-d @- | jq -r '.choices[0].message.content' <<EOF
{
"model": "gpt-4o-mini",
"temperature": 0.2,
"messages": [
{"role": "system", "content": "You are a concise SRE assistant."},
{"role": "user", "content": $(jq -Rn --arg p "$(prompt)" --arg l "$logs" '$p + "\n\n```\n" + $l + "\n```"')}
]
}
EOF
}
summarize_ollama() {
local logs="$1"
local host="${OLLAMA_HOST:-http://127.0.0.1:11434}"
curl -sS "${host}/api/chat" \
-H "Content-Type: application/json" \
-d @- | jq -r '.message.content' <<EOF
{
"model": "llama3.1",
"stream": false,
"messages": [
{"role": "system", "content": "You are a concise SRE assistant."},
{"role": "user", "content": $(jq -Rn --arg p "$(prompt)" --arg l "$logs" '$p + "\n\n```\n" + $l + "\n```"')}
]
}
EOF
}
logs="$(tail -n "$LINES" "$LOGFILE" | redact)"
case "$BACKEND" in
openai) summarize_openai "$logs" ;;
ollama) summarize_ollama "$logs" ;;
*) echo "Unknown AI_BACKEND: $BACKEND (use openai or ollama)" >&2; exit 3 ;;
esac
Make it executable:
sudo install -m 755 ai-log-summary.sh /usr/local/bin/ai-log-summary.sh
Run ad-hoc:
AI_BACKEND=ollama /usr/local/bin/ai-log-summary.sh /var/log/syslog
Automate with systemd timer:
Unit: /etc/systemd/system/ai-log-summary.service
[Unit]
Description=AI Log Summary
[Service]
Type=oneshot
EnvironmentFile=/etc/default/ai-bash
ExecStart=/usr/local/bin/ai-log-summary.sh /var/log/syslog
Timer: /etc/systemd/system/ai-log-summary.timer
[Unit]
Description=Run AI Log Summary hourly
[Timer]
OnCalendar=hourly
Persistent=true
[Install]
WantedBy=timers.target
Enable:
sudo systemctl daemon-reload
sudo systemctl enable --now ai-log-summary.timer
Tip: Adjust the path to your primary app log (e.g., /var/log/nginx/error.log).
2) AI command “risk advisor”: explain before you run
Wrap dangerous operations in a helper that asks the model to explain the command, rate the risk, and request confirmation.
Script: /usr/local/bin/ai-guard.sh
#!/usr/bin/env bash
set -euo pipefail
: "${AI_RISK_THRESHOLD:=7}"
CMD="${*:-}"
[ -n "$CMD" ] || { echo "Usage: ai-guard.sh '<command>'" >&2; exit 1; }
[ -f /etc/default/ai-bash ] && . /etc/default/ai-bash
BACKEND="${AI_BACKEND:-openai}"
make_prompt() {
cat <<EOF
You are a Linux/SRE assistant. Analyze the following shell command:
$CMD
Tasks:
- Explain what it does.
- Identify destructive actions (delete, overwrite, service stop, network impact).
- Estimate risk 1-10 (10=very risky in production).
- Safer alternative if applicable.
Respond in strict JSON:
{"explanation":"...","risk":N,"notes":"...","alternative":"..."}
EOF
}
ask_openai() {
curl -sS https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${OPENAI_API_KEY}" \
-d @- <<EOF
{"model":"gpt-4o-mini","temperature":0.1,
"messages":[
{"role":"system","content":"You are a precise SRE assistant. Output valid JSON only."},
{"role":"user","content":$(jq -Rn --arg p "$(make_prompt)" '$p')}
]}
EOF
}
ask_ollama() {
local host="${OLLAMA_HOST:-http://127.0.0.1:11434}"
curl -sS "${host}/api/chat" -H "Content-Type: application/json" -d @- <<EOF
{"model":"llama3.1","stream":false,
"messages":[
{"role":"system","content":"You are a precise SRE assistant. Output valid JSON only."},
{"role":"user","content":$(jq -Rn --arg p "$(make_prompt)" '$p')}
]}
EOF
}
resp="$(
if [ "${BACKEND}" = "openai" ]; then
[ -n "${OPENAI_API_KEY:-}" ] || { echo "OPENAI_API_KEY not set" >&2; exit 2; }
ask_openai | jq -r '.choices[0].message.content'
else
ask_ollama | jq -r '.message.content'
fi
)"
# Ensure it's JSON
echo "$resp" | jq . >/dev/null 2>&1 || { echo "Model did not return valid JSON"; echo "$resp"; exit 3; }
explanation="$(echo "$resp" | jq -r '.explanation')"
risk="$(echo "$resp" | jq -r '.risk')"
notes="$(echo "$resp" | jq -r '.notes')"
alt="$(echo "$resp" | jq -r '.alternative')"
echo "AI Guard:"
echo "- Explanation: $explanation"
echo "- Risk: $risk/10"
[ -n "$notes" ] && echo "- Notes: $notes"
[ -n "$alt" ] && echo "- Alternative: $alt"
if [ "$risk" -ge "$AI_RISK_THRESHOLD" ]; then
echo "High risk (>= $AI_RISK_THRESHOLD). Type RUN to execute:"
read -r confirm
[ "$confirm" = "RUN" ] || { echo "Aborted."; exit 4; }
fi
echo "Executing: $CMD"
bash -lc "$CMD"
Usage:
ai-guard.sh "systemctl restart nginx"
ai-guard.sh "rm -rf /var/www/*"
Pro tip: Alias destructive commands through the guard in production shells.
3) AI patch digest: summarize pending updates and risk
A weekly job that gathers upgradable packages and asks AI to highlight notable risks (kernel, OpenSSL, glibc, database servers).
Script: /usr/local/bin/ai-patch-digest.sh
#!/usr/bin/env bash
set -euo pipefail
[ -f /etc/default/ai-bash ] && . /etc/default/ai-bash
BACKEND="${AI_BACKEND:-openai}"
. /etc/os-release
collect_updates() {
case "$ID" in
ubuntu|debian)
sudo apt update -y >/dev/null 2>&1 || true
echo "APT upgradable:"
apt list --upgradable 2>/dev/null | sed -n '1,200p'
echo
echo "Simulated changes:"
apt-get -s upgrade | sed -n '1,200p'
;;
rhel|centos|fedora)
echo "DNF check-update:"
dnf check-update --refresh || true
echo
echo "Simulated upgrade (no changes applied):"
dnf upgrade --assumeno | sed -n '1,200p' || true
;;
opensuse*|sles)
echo "ZYPPER list-updates:"
zypper refresh -f || true
zypper list-updates || true
;;
*)
echo "Unknown distro: $ID"
exit 1
;;
esac
}
updates="$(collect_updates)"
prompt=$(cat <<'P'
You are an SRE assistant. Given pending package updates:
- Summarize notable/high-risk updates (kernel, libc, OpenSSL, docker, database servers, web servers).
- Note CVE hints if visible.
- Recommend maintenance window urgency and whether a reboot is required.
- Keep under 180 words.
P
)
ask_openai() {
curl -sS https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${OPENAI_API_KEY}" \
-d @- <<EOF
{"model":"gpt-4o-mini","temperature":0.2,
"messages":[
{"role":"system","content":"You are a concise SRE assistant."},
{"role":"user","content":$(jq -Rn --arg p "$prompt" --arg u "$updates" '$p + "\n\n```\n" + $u + "\n```"')}
]}
EOF
}
ask_ollama() {
local host="${OLLAMA_HOST:-http://127.0.0.1:11434}"
curl -sS "${host}/api/chat" -H "Content-Type: application/json" -d @- <<EOF
{"model":"llama3.1","stream":false,
"messages":[
{"role":"system","content":"You are a concise SRE assistant."},
{"role":"user","content":$(jq -Rn --arg p "$prompt" --arg u "$updates" '$p + "\n\n```\n" + $u + "\n```"')}
]}
EOF
}
if [ "${BACKEND}" = "openai" ]; then
[ -n "${OPENAI_API_KEY:-}" ] || { echo "OPENAI_API_KEY not set" >&2; exit 2; }
ask_openai | jq -r '.choices[0].message.content'
else
ask_ollama | jq -r '.message.content'
fi
Install:
sudo install -m 755 ai-patch-digest.sh /usr/local/bin/ai-patch-digest.sh
Schedule weekly with systemd:
Service: /etc/systemd/system/ai-patch-digest.service
[Unit]
Description=AI Patch Digest
[Service]
Type=oneshot
EnvironmentFile=/etc/default/ai-bash
ExecStart=/usr/local/bin/ai-patch-digest.sh
Timer: /etc/systemd/system/ai-patch-digest.timer
[Unit]
Description=Run AI Patch Digest weekly
[Timer]
OnCalendar=Sun 02:00
Persistent=true
[Install]
WantedBy=timers.target
Enable:
sudo systemctl daemon-reload
sudo systemctl enable --now ai-patch-digest.timer
4) Incident “first look” helper: from noise to next steps
When paged, run a one-liner to collect a quick situational snapshot and let AI propose immediate checks.
Script: /usr/local/bin/ai-firstlook.sh
#!/usr/bin/env bash
set -euo pipefail
[ -f /etc/default/ai-bash ] && . /etc/default/ai-bash
BACKEND="${AI_BACKEND:-openai}"
collect() {
echo "Top CPU:"
COLUMNS=200 ps -eo pid,pcpu,pmem,comm --sort=-pcpu | head -n 10
echo
echo "Disk pressure:"
df -hT | sed -n '1,20p'
echo
echo "Recent kernel messages:"
dmesg | tail -n 100
echo
echo "Service failures (last hour):"
journalctl -p 3 --since "1 hour ago" | tail -n 200
}
data="$(collect)"
prompt=$(cat <<'P'
You are an on-call SRE assistant. Given system snapshots (CPU, disk, dmesg, errors):
- Identify likely top 2-3 issues.
- Suggest 5 immediate verification/mitigation commands (read-only first).
- Note any reboot indication or data loss risk.
Keep to 150 words.
P
)
ask_openai() {
curl -sS https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${OPENAI_API_KEY}" \
-d @- <<EOF
{"model":"gpt-4o-mini","temperature":0.2,
"messages":[
{"role":"system","content":"You are a concise SRE assistant."},
{"role":"user","content":$(jq -Rn --arg p "$prompt" --arg d "$data" '$p + "\n\n```\n" + $d + "\n```"')}
]}
EOF
}
ask_ollama() {
local host="${OLLAMA_HOST:-http://127.0.0.1:11434}"
curl -sS "${host}/api/chat" -H "Content-Type: application/json" -d @- <<EOF
{"model":"llama3.1","stream":false,
"messages":[
{"role":"system","content":"You are a concise SRE assistant."},
{"role":"user","content":$(jq -Rn --arg p "$prompt" --arg d "$data" '$p + "\n\n```\n" + $d + "\n```"')}
]}
EOF
}
if [ "${BACKEND}" = "openai" ]; then
[ -n "${OPENAI_API_KEY:-}" ] || { echo "OPENAI_API_KEY not set" >&2; exit 2; }
ask_openai | jq -r '.choices[0].message.content'
else
ask_ollama | jq -r '.message.content'
fi
Usage:
sudo /usr/local/bin/ai-firstlook.sh
Operational tips and guardrails
Redaction: Always scrub secrets, tokens, PII from logs before sending to any model.
Access control: Keep
/etc/default/ai-bashmode 600; never check keys into repos.Determinism: Use low temperatures (0.1–0.3) for more stable outputs.
Observability: Log model responses to a secured location for auditability.
Local-first: Prefer Ollama/local models for sensitive environments and to cap cost.
Fail closed: If the model is unavailable, your scripts should exit safely (as above).
Conclusion and next steps
AI won’t replace your SRE instincts, but it can compress noise, spotlight risk, and accelerate routine decisions. Start small:
1) Install curl/jq and pick a backend (OpenAI or Ollama).
2) Enable the AI Log Summary timer.
3) Wrap a couple of risky commands with ai-guard.sh.
4) Add the Patch Digest timer to prep your maintenance windows.
From here, extend prompts to your stack (Nginx, Postgres, Kubernetes logs), or plug these scripts into your incident response runbooks.
If you found this useful, try deploying the log triage script across a staging fleet this week—and measure the saved time on your next alert.