Module 33 Advanced 5 labs

ChatOps & AIOps Incident Response

Vận hành qua chat (Teams/Slack/GitHub comment) bằng bot command, webhook automation, và tận dụng AI (Microsoft Copilot in Azure, AIOps) để phát hiện anomaly, triage incident tự động, rút ngắn MTTR.

Công cụ thực hành Azure CLI, Bot Framework, Incoming Webhook, Prometheus, Alertmanager, Copilot in Azure
Nền tảng Microsoft Teams / Slack, Azure Monitor, GitHub Actions, Azure OpenAI
Thời điểm phát hành 23/05/2026
Ngày biên soạn 23/05/2026
Người biên soạn Trần Văn Hòa — Microsoft Certified Trainer (MCT)

Mục tiêu học tập

1. Lý thuyết cốt lõi

1.1. ChatOps là gì?

ChatOps (xuất phát từ GitHub's Hubot, ~2013) là mô hình vận hành nơi toàn bộ hành động ops — deploy, rollback, scale, restart — được kích hoạt trực tiếp từ chat thay vì SSH vào server hoặc mở dashboard riêng. Nguyên tắc: conversation-driven development — mọi người đều thấy lệnh ai chạy, kết quả ra sao, tại sao. Điều này tạo ra audit trail tự nhiên và giảm "hero ops" (chỉ một người biết cách fix).

Luồng ChatOps điển hình

  1. Engineer gõ lệnh trong chat channel: @opsbot deploy app-frontend v2.1.0 to prod
  2. Bot nhận lệnh → gọi CI/CD API (GitHub Actions, Azure DevOps) → trigger pipeline.
  3. Kết quả (success/failure + link pipeline) được bot phản hồi ngay trong channel.
  4. Toàn bộ team thấy ai làm gì, lúc nào — không cần báo cáo riêng.

1.2. Webhook Automation — kết nối monitoring với chat

Incoming Webhook là URL endpoint mà bạn POST JSON để tạo message trong channel. Azure Monitor, Prometheus Alertmanager, Grafana đều hỗ trợ webhook receiver. Khi CPU vượt ngưỡng 90%, Alertmanager POST một card vào Teams channel với thông tin: service, severity, value, runbook link — toàn team on-call nhận ngay, không cần check email.

Outgoing Webhook / Bot Framework cho phép chiều ngược lại: chat message kích hoạt action. Microsoft Teams hỗ trợ Outgoing Webhook (HMAC-signed POST) hoặc Bot Framework SDK để xây bot đầy đủ hơn.

1.3. AIOps — trí tuệ nhân tạo vào vận hành

AIOps (Gartner, 2016) áp dụng ML vào observability data để tự động phát hiện anomaly, correlate events, và đề xuất root cause — giảm alert fatigue (quá nhiều alert giả). Ba năng lực cốt lõi:

1.4. Microsoft Copilot in Azure — AI copilot trong incident triage

Copilot in Azure (GA 2025) tích hợp LLM trực tiếp vào Azure Portal và CLI. Trong bối cảnh incident, Copilot có thể: (1) phân tích log từ Log Analytics bằng ngôn ngữ tự nhiên ("Tại sao pod bị OOMKilled 3 lần trong 1 giờ?"), (2) đề xuất lệnh fix phù hợp ngữ cảnh resource, (3) giải thích metric cho on-call engineer mới. Copilot hoạt động trong context của user's RBAC — chỉ xem/làm những gì user được phép. Tích hợp với Teams qua Copilot for Microsoft 365 cho phép tag @Copilot ngay trong incident channel.

1.5. Incident Response với ChatOps — vòng đời

Giai đoạnHành động ChatOpsCông cụ
DetectAlert tự động POST vào #incidents channelAlertmanager / Azure Monitor Webhook
Triage@bot ack INC-042 + Copilot phân tích logBot Framework, Copilot in Azure
Mitigate@bot rollback app-api to v1.9.2GitHub Actions / Azure DevOps Pipeline
Resolve@bot resolve INC-042 → cập nhật status pagePagerDuty / OpsGenie API
LearnBot tổng hợp timeline, export postmortem draftCopilot for M365, Confluence API

2. Thực hành (Labs)

LAB-001

Cấu hình Incoming Webhook gửi alert vào Microsoft Teams

Teams · curl · PowerShell

🎯 Mục tiêu: Gửi message JSON từ terminal vào Teams channel qua Incoming Webhook — mô phỏng cách monitoring system gửi alert.

🧰 Công cụ / nền tảng: Microsoft Teams (free/work account), PowerShell hoặc curl (WSL2/Linux).

📦 Chuẩn bị: Có Teams workspace; tạo channel #ops-alerts.

▶️ Các bước:

# BƯỚC 1: Tạo Incoming Webhook trong Teams
# Teams → channel #ops-alerts → (...) → Connectors → Incoming Webhook
# Đặt tên: "OpsAlert-Bot", upload icon → Create → Copy URL
# URL dạng: https://xxx.webhook.office.com/webhookb2/...

# BƯỚC 2: Lưu URL vào biến môi trường (PowerShell)
$WEBHOOK_URL = "https://xxx.webhook.office.com/webhookb2/PASTE_YOUR_URL_HERE"

# BƯỚC 3: Gửi test message (PowerShell)
$body = @{
    "@type"      = "MessageCard"
    "@context"   = "http://schema.org/extensions"
    "summary"    = "Test Alert"
    "themeColor" = "FF0000"
    "title"      = "🚨 [CRITICAL] CPU > 90% — app-api-prod"
    "sections"   = @(@{
        "facts" = @(
            @{ "name" = "Service";   "value" = "app-api" }
            @{ "name" = "Host";      "value" = "vm-prod-01" }
            @{ "name" = "Value";     "value" = "CPU 94%" }
            @{ "name" = "Severity";  "value" = "critical" }
            @{ "name" = "Runbook";   "value" = "https://wiki/runbook/cpu-high" }
        )
    })
} | ConvertTo-Json -Depth 5

Invoke-RestMethod -Uri $WEBHOOK_URL -Method Post -Body $body -ContentType "application/json"

# BƯỚC 4 (Linux/WSL2 — curl tương đương):
# curl -H "Content-Type: application/json" \
#   -d '{"@type":"MessageCard","themeColor":"FF0000","title":"🚨 CPU > 90%","text":"app-api-prod | CPU 94%"}' \
#   "$WEBHOOK_URL"

✅ Kết quả mong đợi: Teams channel #ops-alerts hiển thị card màu đỏ với đầy đủ thông tin service, host, value, severity, link runbook. Terminal trả về 1 (success).

🧹 Cleanup: Vào Teams Connectors → xóa Webhook để tránh URL bị lộ. Không commit $WEBHOOK_URL vào git.

LAB-002

Bot command ChatOps: deploy/rollback qua GitHub Actions

GitHub Actions · Slash Command · REST API

🎯 Mục tiêu: Trigger GitHub Actions workflow từ comment /deploy v2.1.0 trên GitHub Issue — mô phỏng ChatOps command trong GitHub context.

🧰 Công cụ / nền tảng: GitHub (free account), GitHub Actions, GitHub CLI (gh).

📦 Chuẩn bị: Cài gh CLI; có repo GitHub; Personal Access Token với scope repo (lưu vào GH_TOKEN secret).

▶️ Các bước:

# BƯỚC 1: Tạo workflow lắng nghe issue_comment event
# File: .github/workflows/chatops-deploy.yml

cat > .github/workflows/chatops-deploy.yml <<'EOF'
name: ChatOps Deploy

on:
  issue_comment:
    types: [created]

jobs:
  parse-command:
    if: startsWith(github.event.comment.body, '/deploy')
    runs-on: ubuntu-latest
    steps:
      - name: Parse version from comment
        id: parse
        run: |
          VERSION=$(echo "${{ github.event.comment.body }}" | awk '{print $2}')
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: React with eyes emoji (ack)
        run: |
          gh api repos/${{ github.repository }}/issues/comments/${{ github.event.comment.id }}/reactions \
            -X POST -f content=eyes
        env:
          GH_TOKEN: ${{ secrets.GH_TOKEN }}

      - name: Simulate deploy
        run: |
          echo "Deploying version ${{ steps.parse.outputs.version }} to production..."
          echo "✅ Deploy ${{ steps.parse.outputs.version }} completed successfully!"
          # Thực tế: gọi kubectl set image, az webapp deploy, etc.

      - name: Post result as comment
        run: |
          gh issue comment ${{ github.event.issue.number }} \
            --body "✅ **ChatOps Deploy**: version \`${{ steps.parse.outputs.version }}\` deployed to prod by @${{ github.actor }}" \
            --repo ${{ github.repository }}
        env:
          GH_TOKEN: ${{ secrets.GH_TOKEN }}
EOF

# BƯỚC 2: Commit và push workflow
git add .github/workflows/chatops-deploy.yml
git commit -m "feat: add chatops deploy workflow"
git push

# BƯỚC 3: Tạo issue và test command
gh issue create --title "Deploy tracking" --body "Tracking deployments via ChatOps"
# Lấy issue number từ output, ví dụ #1
gh issue comment 1 --body "/deploy v2.1.0"

# BƯỚC 4: Theo dõi pipeline run
gh run list --workflow=chatops-deploy.yml --limit 3
gh run watch   # xem live log

✅ Kết quả mong đợi: Sau khi comment /deploy v2.1.0, workflow trigger → bot react 👀 trên comment → pipeline chạy → bot comment lại "✅ ChatOps Deploy: version v2.1.0 deployed to prod by @username". gh run list thấy status completed.

🧹 Cleanup: gh issue close 1; xóa workflow nếu không cần: git rm .github/workflows/chatops-deploy.yml && git commit -m "chore: remove chatops demo".

LAB-003

Alertmanager → Teams: cấu hình webhook receiver

Prometheus · Alertmanager · Docker · Teams Webhook

🎯 Mục tiêu: Cấu hình Prometheus Alertmanager gửi alert vào Teams channel khi một rule bị trigger — pipeline alert tự động đầy đủ.

🧰 Công cụ / nền tảng: Docker Desktop, Prometheus, Alertmanager, promteams (connector), Teams Incoming Webhook.

📦 Chuẩn bị: Docker chạy được; đã có Teams Webhook URL từ LAB-001.

▶️ Các bước:

# BƯỚC 1: Tạo cấu trúc thư mục
mkdir chatops-lab3 && cd chatops-lab3
mkdir prometheus alertmanager

# BƯỚC 2: prometheus/prometheus.yml
cat > prometheus/prometheus.yml <<'EOF'
global:
  scrape_interval: 15s
  evaluation_interval: 15s

alerting:
  alertmanagers:
    - static_configs:
        - targets: ['alertmanager:9093']

rule_files:
  - "/etc/prometheus/rules/*.yml"

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']
EOF

# BƯỚC 3: prometheus/rules/test.yml — rule cố ý luôn fire để test
cat > prometheus/rules/test.yml <<'EOF'
groups:
  - name: test-alerts
    rules:
      - alert: HighCPUSimulated
        expr: vector(1)   # luôn = 1, tức là luôn fire
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "Simulated CPU spike on {{ $labels.instance }}"
          description: "CPU usage exceeded 90% threshold (lab simulation)"
EOF

# BƯỚC 4: alertmanager/alertmanager.yml
# Thay WEBHOOK_URL bằng URL thật từ LAB-001
cat > alertmanager/alertmanager.yml <<'EOF'
global:
  resolve_timeout: 5m

route:
  group_by: ['alertname', 'severity']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 12h
  receiver: 'teams-webhook'

receivers:
  - name: 'teams-webhook'
    webhook_configs:
      - url: 'http://promteams:2000/connector'
        send_resolved: true
EOF

# BƯỚC 5: docker-compose.yml
cat > docker-compose.yml <<'EOF'
version: '3.8'
services:
  prometheus:
    image: prom/prometheus:latest
    ports: ["9090:9090"]
    volumes:
      - ./prometheus:/etc/prometheus
    command: ["--config.file=/etc/prometheus/prometheus.yml", "--web.enable-lifecycle"]

  alertmanager:
    image: prom/alertmanager:latest
    ports: ["9093:9093"]
    volumes:
      - ./alertmanager:/etc/alertmanager
    command: ["--config.file=/etc/alertmanager/alertmanager.yml"]

  promteams:
    image: bzon/prometheus-msteams:latest
    ports: ["2000:2000"]
    environment:
      - TEAMS_INCOMING_WEBHOOK_URL=PASTE_YOUR_TEAMS_WEBHOOK_URL_HERE
      - TEAMS_REQUEST_URI=connector
EOF

# BƯỚC 6: Chạy stack
docker compose up -d

# BƯỚC 7: Kiểm tra Prometheus alerts
Start-Process "http://localhost:9090/alerts"   # PowerShell: mở browser
# Hoặc: curl http://localhost:9090/api/v1/alerts | python -m json.tool

# BƯỚC 8: Kiểm tra Alertmanager
Start-Process "http://localhost:9093"

# Chờ ~2 phút để alert fire và promteams forward sang Teams

✅ Kết quả mong đợi: Sau 2–3 phút, Teams channel #ops-alerts nhận card màu đỏ "HighCPUSimulated — CRITICAL". Prometheus UI tại localhost:9090/alerts hiển thị alert state = firing.

🧹 Cleanup: docker compose down -v dừng và xóa toàn bộ containers + volumes.

LAB-004

AIOps: Anomaly Detection với Azure Monitor & KQL

Azure Monitor · Log Analytics · KQL · Azure CLI

🎯 Mục tiêu: Bật Anomaly Detection trên Azure Monitor metric, viết KQL query phát hiện error spike trong application logs, tạo alert rule tự động.

🧰 Công cụ / nền tảng: Azure CLI, Azure Portal, Log Analytics Workspace, Azure Monitor.

📦 Chuẩn bị: Azure subscription (free tier đủ); Azure CLI đã az login; có App Service hoặc VM với Application Insights enabled.

▶️ Các bước:

# BƯỚC 1: Tạo resource group và Log Analytics Workspace
$RG = "rg-aiops-lab"
$LAW = "law-aiops-lab"
$LOCATION = "southeastasia"

az group create --name $RG --location $LOCATION

az monitor log-analytics workspace create `
  --resource-group $RG `
  --workspace-name $LAW `
  --location $LOCATION

# Lấy workspace ID và key
$WORKSPACE_ID = az monitor log-analytics workspace show `
  --resource-group $RG --workspace-name $LAW `
  --query customerId -o tsv

Write-Host "Workspace ID: $WORKSPACE_ID"

# BƯỚC 2: Tạo Azure Monitor Alert Rule với Dynamic Threshold (Anomaly Detection)
# Trước tiên, tạo Action Group gửi webhook vào Teams
$WEBHOOK_URL = "PASTE_YOUR_TEAMS_WEBHOOK_URL_HERE"

az monitor action-group create `
  --resource-group $RG `
  --name "ag-teams-alert" `
  --short-name "TeamsAlert" `
  --action webhook "teams-notify" `
    --webhook-service-uri $WEBHOOK_URL

# BƯỚC 3: Tạo metric alert với Dynamic threshold (AIOps anomaly detection)
# Ví dụ: monitor CPU % của một VM
$VM_ID = $(az vm show --resource-group $RG --name "REPLACE_WITH_YOUR_VM_NAME" --query id -o tsv)

az monitor metrics alert create `
  --name "alert-cpu-anomaly" `
  --resource-group $RG `
  --scopes $VM_ID `
  --condition "avg Percentage CPU dynamic gt 2 of 4 since P1D" `
  --window-size 5m `
  --evaluation-frequency 1m `
  --severity 2 `
  --description "AIOps: CPU anomaly detected via dynamic threshold" `
  --action "/subscriptions/$(az account show --query id -o tsv)/resourceGroups/$RG/providers/microsoft.insights/actionGroups/ag-teams-alert"

# BƯỚC 4: KQL query trong Log Analytics — phát hiện error spike
# Mở Log Analytics trong Azure Portal → Logs → chạy query:
# Hoặc dùng az monitor log-analytics query

az monitor log-analytics query `
  --workspace $WORKSPACE_ID `
  --analytics-query @'
AppRequests
| where TimeGenerated > ago(1h)
| summarize
    total = count(),
    errors = countif(ResultCode >= 500)
    by bin(TimeGenerated, 5m)
| extend error_rate = round(toreal(errors) / toreal(total) * 100, 2)
| where error_rate > 5
| project TimeGenerated, total, errors, error_rate
| order by TimeGenerated desc
'@ `
  --timespan P1H

# BƯỚC 5: Xem danh sách alert rules đã tạo
az monitor metrics alert list --resource-group $RG --output table

✅ Kết quả mong đợi: Alert rule alert-cpu-anomaly ở state Enabled. KQL query trả về bảng gồm cột TimeGenerated, total, errors, error_rate; nếu error_rate > 5% thì hiện row (nếu không có lỗi thực tế, bảng empty — đó là kết quả đúng). Alert rule tự động gửi Teams notification khi metric lệch khỏi dynamic baseline.

🧹 Cleanup: az group delete --name $RG --yes --no-wait xóa toàn bộ resource.

LAB-005

Copilot in Azure: AI-assisted incident triage

Azure Portal · Copilot in Azure · Log Analytics · KQL

🎯 Mục tiêu: Dùng Copilot in Azure để phân tích log bằng natural language, nhận đề xuất lệnh fix, và tạo incident summary tự động.

🧰 Công cụ / nền tảng: Azure Portal (Copilot in Azure), Log Analytics Workspace, Azure CLI.

📦 Chuẩn bị: Azure subscription có Copilot in Azure enabled (Preview/GA); Log Analytics Workspace có dữ liệu (từ LAB-004 hoặc demo workspace). Tài khoản phải có role ≥ Reader trên workspace.

▶️ Các bước:

# ===== PHẦN A: Dùng Copilot in Azure Portal (GUI) =====

# BƯỚC 1: Vào Azure Portal → click icon Copilot (góc trên phải) hoặc nhấn "Copilot" button
# Copilot panel mở ở bên phải màn hình

# BƯỚC 2: Đặt câu hỏi về incident (natural language):
# Prompt mẫu 1 — phân tích log:
#   "Show me the top 5 errors in my Log Analytics workspace
#    from the last 2 hours and explain what might be causing them"

# Copilot sẽ:
# 1. Tự động detect workspace trong subscription
# 2. Generate KQL query phù hợp
# 3. Chạy query và hiển thị kết quả
# 4. Giải thích nguyên nhân tiềm ẩn bằng tiếng Anh

# BƯỚC 3: Follow-up prompts trong Copilot:
#   "What Azure CLI command should I run to restart the failing pods in my AKS cluster?"
#   → Copilot trả về lệnh cụ thể với context của subscription bạn

#   "Is there a spike in failed requests for my App Service in the last 30 minutes?"
#   → Copilot chạy query và vẽ biểu đồ nếu có dữ liệu

# BƯỚC 4: Sử dụng Copilot để tạo incident summary
#   "Summarize what happened with my resources in the last 1 hour
#    and create a draft incident report"
#   → Copilot tổng hợp: resources bị ảnh hưởng, thời gian, metrics, suggested actions

# ===== PHẦN B: Dùng AI Shell + Copilot qua CLI =====
# (AI Shell là CLI companion của Copilot in Azure)

# BƯỚC 5: Cài AI Shell (Windows)
winget install Microsoft.AIShell

# BƯỚC 6: Khởi động AI Shell và kết nối Copilot in Azure agent
aish start
# Trong AI Shell prompt:
# /agent use azure    -- kết nối Copilot in Azure agent

# BƯỚC 7: Query qua AI Shell
# @azure show me all failed deployments in resource group rg-aiops-lab in last 24 hours
# @azure what kubectl commands should I run to debug a CrashLoopBackOff pod?

# BƯỚC 8: Ghi lại kết quả — tạo incident report template
$report = @"
## Incident Report — $(Get-Date -Format 'yyyy-MM-dd HH:mm')
**Analyzed by:** Copilot in Azure + Manual triage
**Resources affected:** [từ Copilot output]
**Root cause hypothesis:** [từ Copilot suggestion]
**Actions taken:** [list lệnh đã chạy]
**Resolution:** [kết quả]
**MTTR:** [thời gian từ detect đến resolve]
"@

$report | Out-File -FilePath "incident-$(Get-Date -Format 'yyyyMMdd-HHmm').md"
Write-Host "Incident report saved."

✅ Kết quả mong đợi: Copilot in Azure tự generate KQL, trả về phân tích log bằng ngôn ngữ tự nhiên, đề xuất lệnh fix cụ thể (ví dụ: kubectl rollout restart deployment/app-api -n production). File incident-YYYYMMDD-HHMM.md được tạo với draft postmortem. AI Shell phản hồi @azure queries với context của subscription thực.

🧹 Cleanup: Đóng AI Shell: exit. Xóa incident report nếu chứa thông tin nhạy cảm: Remove-Item incident-*.md.

3. Tình huống doanh nghiệp thực tế

Bối cảnh — Fintech với 50+ microservices

Một công ty fintech có 50+ microservices trên AKS. Mỗi tháng xảy ra ~15 P2 incidents. On-call engineer mất trung bình 45 phút chỉ để "tìm hiểu chuyện gì đang xảy ra" trước khi bắt đầu fix. MTTR = 2.5 giờ. Đội muốn giảm MTTR xuống <1 giờ.

Giải pháp ChatOps + AIOps

  • ChatOps: Toàn bộ alert từ Azure Monitor → Teams channel #p2-incidents. Bot tự tạo incident ticket (Azure DevOps Work Item) và assign on-call. Engineer chạy @bot ack INC-nnn ngay trong Teams — không cần mở tool khác.
  • AIOps Event Correlation: Azure Monitor dùng Smart Detection (Anomaly Detection) tự động group 20 alerts liên quan thành 1 incident — giảm alert fatigue từ 20 notification xuống 1.
  • Copilot triage: On-call engineer tag @Copilot trong Teams incident thread: "What's the root cause?". Copilot phân tích log, xác định service X bị memory leak do deployment mới 30 phút trước, đề xuất rollback command.
  • ChatOps rollback: @bot rollback service-x to v1.8.3 — pipeline chạy, kết quả phản hồi trong 3 phút.
  • Kết quả: MTTR giảm từ 2.5 giờ xuống 48 phút. "Tìm hiểu chuyện gì xảy ra" giảm từ 45 → 8 phút nhờ Copilot triage. Blameless postmortem được Copilot draft tự động sau mỗi incident.

📚 Nguồn tham khảo

Module 32: NoOps & Auto-Remediation Module 34: Enterprise Governance
Zalo