Posted on
Artificial Intelligence

Artificial Intelligence Enterprise Automation

Author
  • User
    linuxbash
    Posts by this author
    Posts by this author

AI + Bash: Practical Enterprise Automation You Can Ship This Week

The fastest way to prove AI’s value in the enterprise isn’t a moonshot project—it’s where your Bash scripts already run. Think about noisy logs at 2 a.m., verbose deployment diffs, or tickets that take 20 minutes of summarizing before you even start. Now imagine those workflows cut to seconds, consistently, with guardrails. That’s the promise of Artificial Intelligence Enterprise Automation, and you can pilot it today from a Linux shell.

This post shows you why AI belongs in your automation toolbelt and how to stand up a minimal, production-minded setup with 3–5 concrete scripts you can adapt. Everything stays Bash-first, auditable, and compatible with common Linux distros.

  • Who it’s for: SREs, platform engineers, devops, and sysadmins

  • What you’ll build:

    • A small AI “ask” function you can call from any script
    • Log triage and incident summarization
    • Deployment/change summaries with risk flags
    • ChatOps notifications
    • Optional systemd timers for hands-off scheduling

Why AI for enterprise automation is worth it

  • Reduce toil: AI turns unstructured noise (logs, alerts, tickets) into structured, actionable summaries and proposed next steps.

  • Compress MTTx: Faster triage and clearer context drive shorter time to acknowledge, resolve, and learn.

  • Standardize quality: Summaries, checklists, and runbooks are consistent, even across rotating on-call engineers.

  • Governable and private: With local models (e.g., Ollama) or VPC-contained inference, you can run AI where your data lives.

Real-world outcomes teams report:

  • 30–50% fewer duplicate/low-signal alerts surfaced to humans after AI pre-triage

  • 60–80% reduction in time spent writing postmortems and change tickets

  • Faster onboarding: new engineers benefit from AI-ed runbook snippets and summaries


Prerequisites and installation

We’ll use:

  • curl and jq for HTTP/JSON

  • Optional: Podman if you prefer running AI in a container

  • Option A: Local LLM via Ollama (keeps data on-box)

  • Option B: Cloud API (e.g., OpenAI) for stronger models where data policy allows

Install base tools:

Debian/Ubuntu (apt):

sudo apt-get update
sudo apt-get install -y curl jq git podman

Fedora/RHEL/CentOS (dnf):

sudo dnf install -y curl jq git podman

openSUSE (zypper):

sudo zypper refresh
sudo zypper install -y curl jq git podman

Option A: Local model with Ollama

Native installer:

curl -fsSL https://ollama.com/install.sh | sh
sudo systemctl enable --now ollama
ollama pull llama3:8b

Or run in a container (Podman):

sudo podman run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama --restart=always ollama/ollama
sudo podman exec -it ollama ollama pull llama3:8b

Ollama API will be at http://localhost:11434.

Option B: Cloud API (example: OpenAI)

Set an API key in your environment (rotate and store securely, e.g., using a secret manager):

export OPENAI_API_KEY="sk-..."

No extra packages needed beyond curl/jq.


A tiny AI wrapper for Bash

This helper function lets your scripts “ask” an AI model with a single call, against either Ollama (local) or OpenAI (cloud). Save as ai.sh:

#!/usr/bin/env bash
set -euo pipefail

# Config
: "${AI_MODE:=ollama}"              # ollama | openai
: "${OLLAMA_HOST:=http://localhost:11434}"
: "${OLLAMA_MODEL:=llama3:8b}"
: "${OPENAI_MODEL:=gpt-4o-mini}"    # adjust per policy/availability

ai_ask() {
  local prompt="$1"

  if [ "${AI_MODE}" = "ollama" ]; then
    curl -sS --max-time 60 \
      -H "Content-Type: application/json" \
      -d "$(jq -n --arg m "$OLLAMA_MODEL" --arg p "$prompt" '{model:$m,prompt:$p,stream:false}')" \
      "${OLLAMA_HOST}/api/generate" | jq -r '.response'
  else
    if [ -z "${OPENAI_API_KEY:-}" ]; then
      echo "OPENAI_API_KEY not set" >&2; return 1
    fi
    curl -sS --max-time 60 https://api.openai.com/v1/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,temperature:0.2,
              messages:[
                {role:"system",content:"You are a concise Linux SRE assistant. Prefer JSON outputs when asked."},
                {role:"user",content:$p}
              ]}')" \
      | jq -r '.choices[0].message.content'
  fi
}

Make it executable and source it where needed:

chmod +x ai.sh
. ./ai.sh

Tip: Move ai.sh to a shared repo or /usr/local/lib/ai.sh and source it from multiple scripts.


1) AI log triage in one file

Use AI to summarize the last N lines of a log, extract top errors, suspected root causes, and recommended next steps in JSON so other tooling can consume it.

Save as ai-log-triage.sh:

#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "${SCRIPT_DIR}/ai.sh"

LOG_FILE="${1:-/var/log/syslog}"
LINES="${LINES:-500}"

if [ ! -r "$LOG_FILE" ]; then
  echo "Cannot read $LOG_FILE" >&2
  exit 1
fi

SNIPPET="$(tail -n "$LINES" "$LOG_FILE" | sed 's/[[:cntrl:]]//g' | tail -c 18000)" # cap size

read -r -d '' PROMPT << 'EOF' || true
You are triaging Linux service logs. Return JSON with keys:

- top_errors: array of {message, count}

- probable_causes: array of strings

- recommended_actions: array of strings (bash-friendly, safe, reversible)

- severity: one of ["low","medium","high"]
Focus on patterns, stack traces, and repeated messages. No extra text—JSON only.
EOF

OUT="$(ai_ask "$PROMPT

LOG SNIPPET START
$SNIPPET
LOG SNIPPET END
")"

echo "$OUT" | jq .

Usage:

AI_MODE=ollama ./ai-log-triage.sh /var/log/nginx/error.log
# or
AI_MODE=openai OPENAI_API_KEY=... ./ai-log-triage.sh

Optional: send to Slack as a one-liner after the jq pretty-print:

[ -n "${SLACK_WEBHOOK_URL:-}" ] && curl -s -X POST -H 'Content-type: application/json' \
  --data "$(jq -n --arg t "Log triage $(date -Is)" --arg b "$(echo "$OUT" | jq -c .)" '{text: ($t + "\n```" + $b + "```")}')" \
  "$SLACK_WEBHOOK_URL" >/dev/null

2) Change and deployment diffs, summarized with risk flags

Pipe a git diff or changelog to AI and get risks, blast radius, and verification steps. Great for PR templates, tickets, or CAB notes.

Save as ai-change-summary.sh:

#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "${SCRIPT_DIR}/ai.sh"

DIFF_INPUT="${1:-}"
if [ -z "$DIFF_INPUT" ]; then
  DIFF_INPUT="$(git --no-pager diff --staged || true)"
fi

SNIPPET="$(printf "%s" "$DIFF_INPUT" | tail -c 20000)"

read -r -d '' PROMPT << 'EOF' || true
Summarize the following change. Output JSON with:

- summary: short sentence

- risk_level: low|medium|high

- affected_components: array of strings

- blast_radius: brief description

- rollback_plan: 2–4 bullet steps

- post_deploy_checks: 3–5 commands or endpoints to verify

- compliance_flags: array of strings (e.g., "secrets_touched","network_policy_change") if applicable
No extra commentary—JSON only.
EOF

ai_ask "$PROMPT

CHANGE DIFF START
$SNIPPET
CHANGE DIFF END
" | jq .

Usage:

# For current staged changes:
AI_MODE=ollama ./ai-change-summary.sh

# For a specific range:
git diff v1.2.3..HEAD | AI_MODE=openai OPENAI_API_KEY=... ./ai-change-summary.sh -

3) Lightweight “self-healing” suggestions (human-in-the-loop)

AI can propose a safe, reversible Bash snippet. You review and run. Keep humans approving until you’re confident.

Save as ai-remedy-proposer.sh:

#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "${SCRIPT_DIR}/ai.sh"

SYMPTOM="${1:-"High 5xx rate on frontend in the last 10 minutes"}"
CONTEXT_LOG="$(journalctl -u frontend.service -n 200 -o short-iso 2>/dev/null | tail -c 15000)"

read -r -d '' PROMPT << 'EOF' || true
Given the symptom and recent logs, propose a minimal, SAFE, and REVERSIBLE Bash remediation snippet.
Constraints:

- Read-only or no-op first if possible (e.g., dry-run flags)

- Add an echo describing what it does

- No destructive commands (rm -rf, truncation, etc.)
Output JSON: { rationale, script }
EOF

RES="$(ai_ask "$PROMPT

SYMPTOM:
$SYMPTOM

RECENT LOGS:
$CONTEXT_LOG
")"

echo "$RES" | jq -r '.rationale'
echo
echo "# Proposed script:"
echo "$RES" | jq -r '.script' > /tmp/remedy.sh
chmod +x /tmp/remedy.sh
echo "/tmp/remedy.sh written. Review before running."

4) Automate on a schedule with systemd timers

Run the log triage every 15 minutes and send a message if severity is medium/high.

Create ~/.config/systemd/user/ai-log-triage.service:

[Unit]
Description=AI Log Triage (user)

[Service]
Type=oneshot
Environment=AI_MODE=ollama
EnvironmentFile=%h/.config/ai.env
ExecStart=%h/bin/ai-log-triage-cron.sh

Create ~/.config/systemd/user/ai-log-triage.timer:

[Unit]
Description=Run AI Log Triage every 15 minutes

[Timer]
OnCalendar=*:0/15
Persistent=true

[Install]
WantedBy=timers.target

Helper script ~/bin/ai-log-triage-cron.sh:

#!/usr/bin/env bash
set -euo pipefail
. "$HOME/bin/ai.sh"
OUT="$(AI_MODE="${AI_MODE:-ollama}" "$HOME/bin/ai-log-triage.sh" /var/log/syslog || true)"

SEV="$(echo "$OUT" | jq -r '.severity // "low"')"
if [ "$SEV" = "medium" ] || [ "$SEV" = "high" ]; then
  [ -n "${SLACK_WEBHOOK_URL:-}" ] && curl -s -X POST -H 'Content-type: application/json' \
    --data "$(jq -n --arg t "AI triage $(date -Is) severity=$SEV" --arg b "$(echo "$OUT" | jq -c .)" '{text: ($t + "\n```" + $b + "```")}')" \
    "$SLACK_WEBHOOK_URL" >/dev/null
fi

Enable:

systemctl --user daemon-reload
systemctl --user enable --now ai-log-triage.timer
systemctl --user list-timers | grep ai-log-triage

Note: systemd user sessions may require lingering enabled:

loginctl enable-linger "$USER"

Governance, security, and ROI

  • Data boundaries:

    • Prefer local models (Ollama) for sensitive logs.
    • If using cloud, scrub secrets before sending. Add redaction:
    redacted="$(echo "$SNIPPET" | sed -E 's/(password|token|apikey)=[^ ]+/REDACTED/gi')"
    
  • Prompt discipline:

    • Always request JSON. Validate with jq before acting.
    • Keep temperature low for deterministic outputs.
  • Access control:

    • Store keys in a secret manager or read from EnvironmentFile owned by root with 600 perms.
  • Observability:

    • Log prompts/responses to a secure audit trail.
    • Track success metrics (reduced pages, faster MTTR) to justify further investment.

Putting it all together: a day-1 pilot plan

  • Hour 0–1: Install prerequisites and Ollama or set OPENAI_API_KEY.

  • Hour 1–2: Wire up ai.sh and run ai-log-triage.sh against your nosiest log.

  • Hour 2–3: Add Slack notifications and a systemd timer.

  • Hour 3–4: Try ai-change-summary.sh in your CI to enrich PRs or tickets.

Start small, measure results, and expand to more services as trust grows.


Call to action

  • Grab the snippets, point them at your real logs and diffs, and see immediate value.

  • Add one guardrail (JSON-only, redaction, approval gate) for every automation you ship.

  • Next step: integrate with your incident and ticketing system to auto-fill summaries and checklists.

If you want a ready-to-use starter repo with these scripts and unit files, assemble the files above into a single repo, add a README with your distro’s apt/dnf/zypper instructions, and standardize the ai.sh wrapper across your team. Your on-call will thank you.