ข้ามไปที่เนื้อหา

DevOps Delivery Pipeline: Framework ตั้งแต่ต้นจนจบ

DevOps framework ไม่ใช่ tool ตัวเดียว และไม่ใช่ process เดียว แต่เป็นระบบที่ต่อไอเดียของ product ไปจนถึงซอฟต์แวร์ที่รันบน production ครบทั้งเส้น โดยใส่เรื่องคุณภาพและ security ไว้ในทุกขั้น


ต้องมี Framework ไม่ใช่มีแค่ Tool

ทีมส่วนใหญ่เริ่ม DevOps ด้วยการสะสม tool "CI ใช้ Jenkins, container ใช้ Docker, deploy ขึ้น Kubernetes" แบบนี้คือคิดจาก tool ก่อน (tool-first) ผลที่ได้คือ pipeline ที่ต่อกันเป็นท่อนๆ ไม่มีใครตอบได้จริงๆ ว่า commit หนึ่งเดินทางไปเป็น production release ได้ยังไง

framework ไม่เหมือนกัน เพราะกำหนดสี่เรื่องนี้ไว้ชัด:

  • Stage — แต่ละช่วงของเส้นทางมีอะไรเกิดขึ้นบ้าง
  • Gate — ต้องผ่านเงื่อนไขอะไรก่อนถึงจะไป stage ถัดไปได้
  • Feedback loop — ข้อมูลจาก stage ท้ายๆ ไหลกลับมาหา stage ต้นๆ ทางไหน
  • Ownership — stage ไหนใครเป็นเจ้าของ
Idea → Plan → Code → Build → Test → Release → Deploy → Operate → Monitor
  ↑__________________feedback____________________________________|

feedback loop สำคัญที่สุด DevOps framework ที่ไม่มี feedback ก็คือ waterfall ที่เอา Docker มาใส่เท่านั้นเอง


Stage 1: จัดทีมและทำ Product Discovery

"DevOps Team" ไม่ใช่คำตอบ

ข้อผิดพลาดที่เจอบ่อยมากคือตั้ง DevOps team แยกออกมา แล้วให้ทีมนี้คอยเฝ้าประตู สุดท้ายก็ได้กำแพงกั้นระหว่าง dev กับ ops แบบเดิม แค่เปลี่ยนชื่อเรียก DevOps ได้ผลดีที่สุดกับ cross-functional product team ที่ดูแล service ของตัวเองตลอด lifecycle

product team ที่แข็งแรงจะมีหน้าตาประมาณนี้:

Role ความรับผิดชอบ Anti-Pattern
Product Owner ตัดสินว่าจะสร้างอะไร และสร้างไปทำไม เขียน ticket โดยไม่เคยคุยกับ user
Designer (UX/UI) เข้าใจ user แล้วออกแบบ solution ออกแบบอยู่คนเดียว เสร็จแล้วโยนให้ dev
Backend Engineer สร้าง service, API, data layer "เครื่องผมรันได้นะ"
Frontend Engineer สร้าง user interface ไม่สน API contract
Security Engineer ใส่ security ตั้งแต่วันแรก มารีวิวเอาตอนจบ
Platform/SRE ทำ developer tooling และดูแล reliability กุม Kubernetes ไว้เอง แทนที่จะช่วยให้ทีมอื่นทำเองได้
QA Engineer ตรวจคุณภาพทุก stage เขียน test หลัง feature ship ไปแล้ว

Why–What–How Model

ก่อนเขียน code บรรทัดแรก ทีมต้องเห็นตรงกันสามระดับ:

WHY   → Business problem / user need / strategic goal
         "We lose 20% of users at checkout because the payment form is too complex"

WHAT  → The solution space / product requirement
         "A one-click payment flow using saved payment methods"

HOW   → Technical implementation
         "Add a /payments/quick-checkout endpoint that uses tokenized cards from Stripe"

ข้าม WHY เมื่อไหร่ ทีมจะสร้างของผิดได้อย่างคล่องแคล่วมาก

Tool สำหรับ Discovery

ใช้ทำอะไร Tool
ติดตาม Portfolio / Epic Jira, Linear, Shortcut
เอกสารและ wiki Confluence, Notion, Backstage
Diagram และ architecture Miro, draw.io, Excalidraw
Security architecture Threat Dragon, OWASP Threat Modeling
API design Stoplight, Swagger Editor, Redocly

Stage 2: Source Code Management

ทุกอย่างเป็น Code

DevOps ทุกวันนี้มองทุกอย่างเป็น code ไม่ใช่แค่ application logic แต่รวม infrastructure, test, security policy และเอกสารด้วย นี่คือพื้นฐานที่ทำให้สร้างทุกอย่างซ้ำได้เหมือนเดิม (reproducibility)

repository/
├── src/                  # Application code
│   ├── api/
│   ├── services/
│   └── models/
├── tests/                # All test types
│   ├── unit/
│   ├── integration/
│   ├── e2e/
│   └── performance/
├── infra/                # Infrastructure as Code
│   ├── terraform/
│   └── helm/
├── .github/workflows/    # CI/CD pipelines
├── .pre-commit-config.yaml
├── Dockerfile
└── docker-compose.yml

Branching Strategy

เลือก branching strategy ตามรอบการ release ของทีม:

main (trunk)
  │
  ├── feature/add-payment (short-lived, < 2 days)
  ├── feature/user-profile (short-lived, < 2 days)
  │
  └── tags: v1.2.0, v1.2.1, v1.3.0
  • developer ทุกคน merge เข้า main ทุกวัน
  • งานที่ยังไม่เสร็จซ่อนไว้หลัง feature flag
  • เหมาะกับทีมที่ CI แข็งและ test coverage สูง
  • merge conflict ลดลงเยอะมาก

main │ ├── feature/checkout-redesign │ └── PR → code review → merge ├── fix/payment-timeout │ └── PR → code review → merge

  • ง่าย: main ต้อง deploy ได้ตลอดเวลา
  • ทุก change ต้องผ่าน PR
  • เหมาะกับทีม web ที่ทำ continuous deployment
main ─────────────────────────────────────────
                ↑ merge at release
release/1.2 ───────────────
            ↑ cut
develop ─────────────────────────────────────
          ↑ merge feature branches
feature/* ────────
hotfix/*  ──── (cherry-pick to main and develop)
  • เหมาะกับ product ที่ release เป็นรอบตามตาราง
  • ขั้นตอนเยอะกว่า merge conflict ก็เยอะกว่า
  • ถ้า deploy ได้บ่อยอยู่แล้ว เลี่ยงไปเลย

Code Quality Gate (Pre-Commit)

ดัก code แย่ๆ ไว้ตั้งแต่ก่อนเข้า repository:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-json
      - id: check-merge-conflict
      - id: detect-private-key        # Catch secrets early
      - id: check-added-large-files
        args: ['--maxkb=500']

  - repo: https://github.com/psf/black
    rev: 24.3.0
    hooks:
      - id: black

  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.3.0
    hooks:
      - id: ruff
        args: [--fix]

  - repo: https://github.com/Yelp/detect-secrets
    rev: v1.4.0
    hooks:
      - id: detect-secrets
        args: ['--baseline', '.secrets.baseline']

  - repo: https://github.com/python-jsonschema/check-jsonschema
    rev: 0.28.0
    hooks:
      - id: check-github-workflows

Static Analysis Tool

Tool หาอะไรเจอ ใช้ตอนไหน
SonarQube Code smell, bug, coverage, duplication CI pipeline, PR gate
Snyk ช่องโหว่ใน open-source dependency (SCA) CI pipeline, รันทุกคืน
Checkmarx SAST — หาช่องโหว่ security ใน code CI pipeline
Semgrep เขียน security rule เองได้, SAST ที่เร็ว Pre-commit, CI
Veracode SAST/DAST ระดับ enterprise มี compliance report ให้ อุตสาหกรรมที่มี regulator คุม
Black Duck ตรวจ license compliance + ช่องโหว่ OSS Gate ด้านกฎหมายและ compliance

Stage 3: Build Phase

Build ทำอะไรบ้าง

build คือขั้นที่เปลี่ยน source code ให้เป็น artifact ที่เอาไป deploy ได้ build ที่ดีต้อง:

  • Reproducible — input เดิม ได้ output เดิมทุกครั้ง
  • เร็ว — build ช้า งานก็สะดุด
  • ไม่ผูกกับเครื่องใคร — ไม่พึ่งเครื่องของ developer คนไหนเลย
# Example: pyproject.toml with pinned dependencies (reproducible builds)
[tool.poetry]
name = "payment-service"
version = "0.1.0"

[tool.poetry.dependencies]
python = "^3.12"
fastapi = "0.110.0"
sqlalchemy = "2.0.28"
pydantic = "2.6.3"

[tool.poetry.group.dev.dependencies]
pytest = "7.4.4"
pytest-cov = "4.1.0"
black = "24.3.0"

เลือก Build Tool

Ecosystem Build Tool Package Registry
Python pip, Poetry, uv PyPI, Nexus/JFrog ที่ตั้งเอง
Java Maven, Gradle Maven Central, Artifactory
JavaScript/TS npm, pnpm, yarn npmjs, Verdaccio
Go go build pkg.go.dev, GOPROXY
.NET MSBuild, dotnet NuGet, Artifactory

Test ระหว่าง Build: Testing Pyramid

        /\
       /  \
      / E2E \         ← Few, slow, expensive (Selenium, Playwright)
     /──────\
    /  Integ  \       ← Some (API tests, DB tests, contract tests)
   /────────────\
  /   Unit Tests  \   ← Many, fast, cheap (pytest, JUnit)
 /──────────────────\
/  Static Analysis   \ ← All code, always (SonarQube, Semgrep)

ตัวอย่าง unit test (Python/pytest):

# tests/unit/test_payment_service.py
import pytest
from decimal import Decimal
from services.payment import PaymentService, InsufficientFundsError

class TestPaymentService:
    def test_process_payment_success(self):
        service = PaymentService(gateway=MockGateway())
        result = service.process(amount=Decimal("99.99"), currency="USD")
        assert result.status == "approved"
        assert result.transaction_id is not None

    def test_process_payment_insufficient_funds(self):
        gateway = MockGateway(decline_reason="insufficient_funds")
        service = PaymentService(gateway=gateway)

        with pytest.raises(InsufficientFundsError):
            service.process(amount=Decimal("999.99"), currency="USD")

    def test_process_payment_invalid_amount(self):
        service = PaymentService(gateway=MockGateway())
        with pytest.raises(ValueError, match="Amount must be positive"):
            service.process(amount=Decimal("-10.00"), currency="USD")

เก็บ Artifact ไว้ที่ไหน

code ชุดเดียวกันไม่ต้อง build ซ้ำ build เสร็จแล้วเก็บ artifact ไว้ใน registry:

Build → Artifact Registry (Nexus / JFrog Artifactory / GitHub Packages)
           │
           ├── Python wheels (.whl)
           ├── Java JARs
           ├── npm packages
           └── Container images (see Stage 4)

ทำไมต้องมี artifact registry:

  1. Build ครั้งเดียว deploy กี่รอบก็ได้ dev, staging และ prod ใช้ binary ตัวเดียวกัน
  2. Rollback ได้ทันที เพราะ artifact เก่ายังอยู่
  3. Security scan ครั้งเดียวพอ ไม่ต้องสแกนใหม่ทุก environment
  4. ดู license compliance ได้จากที่เดียว

Stage 4: Containerization และ Image Security

Container Build Pipeline

build container image ไม่ได้จบที่ docker build image pipeline ระดับ production มีขั้นตอนประมาณนี้:

Source Code
    │
    ▼
Dockerfile / Buildpacks
    │
    ▼
Build → OCI Image
    │
    ▼
SBOM Generation (CycloneDX / SPDX)
    │
    ▼
SCA Scan (Trivy / Snyk / Black Duck)
    │
    ├── PASS → Push to Registry
    └── FAIL → Block pipeline, notify team
    │
    ▼
Container Registry (Harbor / ECR / Docker Hub / jFrog)
    │
    ▼
Image Signing (Cosign / Notary)

เขียน Dockerfile ให้ปลอดภัย

FROM python:latest           # unpinned = non-reproducible

WORKDIR /app
COPY . .
RUN pip install -r requirements.txt

RUN apt-get install -y curl vim wget  # unnecessary tools

CMD ["python", "app.py"]

# Problems: runs as root, unpinned base, installs debug tools
# Stage 1: Build dependencies
FROM python:3.12.3-slim AS builder

WORKDIR /build
COPY pyproject.toml poetry.lock ./

RUN pip install --no-cache-dir poetry==1.8.2 && \
    poetry export -f requirements.txt --output requirements.txt --without-hashes

# Stage 2: Runtime image
FROM python:3.12.3-slim AS runtime

# Create non-root user
RUN groupadd -r appuser && useradd -r -g appuser appuser

WORKDIR /app

# Install only runtime dependencies
COPY --from=builder /build/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt && \
    rm -rf /root/.cache

COPY --chown=appuser:appuser src/ ./src/

USER appuser

EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8080/health || exit 1

CMD ["python", "-m", "uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]

SBOM: Software Bill of Materials

SBOM คือรายการส่วนผสมของซอฟต์แวร์ บอกได้ชัดว่าใน container image มี open-source component ตัวไหนบ้าง พอมีช่องโหว่ใหม่ประกาศออกมา หรือต้องตรวจ license ก็ใช้ SBOM ตัวนี้แหละ

# Generate SBOM with Syft
syft payment-service:v1.2.0 -o cyclonedx-json > sbom.json

# Scan SBOM for vulnerabilities with Grype
grype sbom:./sbom.json --fail-on high

# Scan with Trivy
trivy image --severity HIGH,CRITICAL payment-service:v1.2.0

# Sign the image after scanning passes
cosign sign --key cosign.key payment-service:v1.2.0

อ่าน output ของ Trivy ยังไง:

payment-service:v1.2.0 (debian 12.5)

Total: 3 (HIGH: 2, CRITICAL: 1)

┌──────────────┬────────────────┬──────────┬───────────────────┬──────────────────────┐
│   Library    │ Vulnerability  │ Severity │ Installed Version │    Fixed Version     │
├──────────────┼────────────────┼──────────┼───────────────────┼──────────────────────┤
│ libssl3      │ CVE-2024-XXXX  │ CRITICAL │ 3.0.11-1          │ 3.0.13-1             │
│ cryptography │ CVE-2024-YYYY  │ HIGH     │ 42.0.0            │ 42.0.5               │
│ requests     │ CVE-2024-ZZZZ  │ HIGH     │ 2.31.0            │ 2.32.0               │
└──────────────┴────────────────┴──────────┴───────────────────┴──────────────────────┘

เลือก Container Registry

Registry เหมาะกับ จุดเด่น
Harbor ตั้งเอง, ระบบ air-gapped RBAC, มี scanner ในตัว, replication
Amazon ECR ทีมที่อยู่บน AWS ใช้ IAM ได้เลย, มี lifecycle policy
Google Artifact Registry ทีมที่อยู่บน GCP เก็บได้หลาย format (Docker, Maven, npm)
Docker Hub Open source / ทีมเล็ก public registry ใหญ่ที่สุด
jFrog Container Registry Enterprise, multi-cloud ใช้ได้กับทุก format, security ครบ

Stage 5: Release Management

Semantic Versioning

ทุก release ต้องมีเลข version ที่ชัดเจน และเครื่องอ่านได้:

MAJOR.MINOR.PATCH[-PRERELEASE][+BUILD]

v1.2.3
│ │ └── PATCH: backward-compatible bug fixes
│ └──── MINOR: backward-compatible new features
└────── MAJOR: breaking changes

ตัวอย่าง: - v1.0.0 → stable release ตัวแรก - v1.1.0 → เพิ่ม feature ใหม่ (ยัง backward compatible) - v1.1.1 → แก้ bug - v2.0.0 → API เปลี่ยนแบบ breaking - v1.2.0-rc.1 → Release candidate

Release อัตโนมัติด้วย Conventional Commits

ใช้ Conventional Commits แล้วให้เครื่อง bump version และเขียน changelog ให้เอง:

feat: add one-click payment support     → bumps MINOR (1.2.0 → 1.3.0)
fix: correct tax calculation rounding   → bumps PATCH  (1.3.0 → 1.3.1)
feat!: redesign checkout API            → bumps MAJOR  (1.3.1 → 2.0.0)
docs: update API reference              → no version bump
chore: upgrade dependencies             → no version bump
# .releaserc.yml — semantic-release configuration
branches:
  - main
  - name: beta
    prerelease: true

plugins:
  - "@semantic-release/commit-analyzer"
  - "@semantic-release/release-notes-generator"
  - "@semantic-release/changelog"
  - "@semantic-release/git"
  - "@semantic-release/github"

verifyConditions:
  - "@semantic-release/github"

prepare:
  - "@semantic-release/changelog"
  - "@semantic-release/git"

publish:
  - "@semantic-release/github"

บันทึกทุก Release

ทุก release ควรมีบันทึกแบบนี้:

## Release v1.3.0 — 2026-05-18

### Changes
- feat: one-click payment with saved cards (#234)
- feat: support Apple Pay and Google Pay (#241)
- fix: correct tax calculation for EU customers (#238)

### Security
- Updated cryptography from 42.0.0 to 42.0.5 (CVE-2024-YYYY)

### Breaking Changes
None

### Deployment Notes
- Run migration: `alembic upgrade head`
- Set new env var: `PAYMENT_TOKENIZATION_KEY`

### Metrics Baseline (before deployment)
- Error rate: 0.02%
- p99 latency: 180ms
- Deployment frequency: 3x/week

Stage 6: Test ให้ครบทุกระดับ

Test มีหลายระดับ

test ไม่ได้มีแค่ unit test ทีมที่ทำ test มาจนโตแล้วจะไล่ครบทุกระดับ ตั้งแต่ test เร็วๆ ที่รันบนเครื่อง developer ไปจนถึงการ validate บน production ที่ช้ากว่าแต่ใกล้ของจริงที่สุด:

← Faster / Cheaper / More Isolated          Slower / More Real →

Unit → Integration → Contract → E2E → Performance → Chaos → Production

Test แต่ละแบบ

test function หรือ class ทีละตัวแบบแยกเดี่ยว dependency ภายนอก mock ทิ้งให้หมด

# Fast, no I/O, no network
def test_order_total_with_discount():
    order = Order(
        items=[
            OrderItem(product_id="P1", quantity=2, unit_price=Decimal("50.00")),
            OrderItem(product_id="P2", quantity=1, unit_price=Decimal("30.00")),
        ]
    )
    coupon = Coupon(code="SAVE20", discount_percent=20)

    total = order.calculate_total(coupon=coupon)

    assert total == Decimal("104.00")  # (100 + 30) * 0.8

เป้าหมาย: code coverage > 80% และทั้ง suite รันจบใน < 60 วินาที

test ว่า component ต่างๆ ทำงานร่วมกันได้จริง ใช้ database จริง (รันใน Docker) และ message queue จริง

# tests/integration/test_order_repository.py
import pytest
from sqlalchemy import create_engine
from repositories.order_repository import SQLOrderRepository

@pytest.fixture(scope="session")
def test_db():
    engine = create_engine("postgresql://test:test@localhost:5433/testdb")
    # Run migrations
    run_migrations(engine)
    yield engine
    engine.dispose()

def test_save_and_retrieve_order(test_db):
    repo = SQLOrderRepository(test_db)
    order = Order.create(customer_id="C001", items=[...])

    repo.save(order)
    retrieved = repo.find_by_id(order.id)

    assert retrieved.id == order.id
    assert len(retrieved.items) == len(order.items)

เช็กว่า consumer กับ provider ยังตกลง API contract ตรงกัน โดยไม่ต้องเปิดทั้งสองฝั่งให้รันพร้อมกัน

# Consumer side (using Pact)
from pact import Consumer, Provider

pact = Consumer("payment-service").has_pact_with(
    Provider("user-service"),
    host_name="localhost",
    port=1234
)

def test_get_user_payment_methods():
    (pact
     .given("User U001 has two saved payment methods")
     .upon_receiving("a request for payment methods")
     .with_request("GET", "/users/U001/payment-methods")
     .will_respond_with(200, body={
         "user_id": "U001",
         "methods": like([{
             "id": "PM001",
             "type": "credit_card",
             "last_four": "4242"
         }])
     }))

    with pact:
        result = get_user_payment_methods("U001")
        assert len(result) >= 1

test user journey ทั้งเส้น ผ่าน UI หรือ API endpoint จริง

# Using Playwright (Python)
from playwright.sync_api import Page

def test_complete_checkout_flow(page: Page):
    # Navigate to product
    page.goto("https://staging.myapp.com/products/laptop-pro")
    page.click("[data-testid='add-to-cart']")

    # Go to checkout
    page.click("[data-testid='checkout-button']")
    page.fill("[name='email']", "test@example.com")

    # Payment
    page.fill("[name='card-number']", "4242 4242 4242 4242")
    page.fill("[name='expiry']", "12/28")
    page.fill("[name='cvv']", "123")
    page.click("[data-testid='place-order']")

    # Verify confirmation
    page.wait_for_selector("[data-testid='order-confirmation']")
    assert "Order confirmed" in page.inner_text("h1")

เช็กว่าระบบยังทำงานถูกต้องตอนเจอ load หนัก

# locustfile.py
from locust import HttpUser, task, between

class CheckoutUser(HttpUser):
    wait_time = between(1, 3)

    @task(3)
    def browse_products(self):
        self.client.get("/api/products?category=electronics")

    @task(2)
    def view_product(self):
        self.client.get("/api/products/laptop-pro")

    @task(1)
    def add_to_cart(self):
        self.client.post("/api/cart/items", json={
            "product_id": "laptop-pro",
            "quantity": 1
        })

รัน: locust --headless --users 1000 --spawn-rate 100 --run-time 5m

Performance SLO ที่ test ต้องผ่าน: - p50 response time < 100ms - p99 response time < 500ms - Error rate < 0.1% ตอน peak load - Throughput > 1,000 RPS

Security Testing: DAST และ IAST

DAST (Dynamic Application Security Testing) ยิงโจมตี application ที่รันอยู่จากข้างนอก:

# OWASP ZAP automated scan against staging
docker run -t owasp/zap2docker-stable zap-baseline.py \
    -t https://staging.myapp.com \
    -r zap-report.html \
    --exit-code 1

# Fail the pipeline if HIGH or CRITICAL issues found

IAST (Interactive Application Security Testing) ฝังตัววัดไว้ใน application แล้วจับช่องโหว่จากข้างในระหว่างที่ test รัน:

  • Contrast Security
  • Seeker by Synopsys
  • HCL AppScan IAST

QA Tool ที่ใช้กันอยู่

หมวด Tool ใช้ทำอะไร
Browser automation Selenium, Playwright, Cypress E2E web testing
Mobile testing Appium, Detox iOS/Android automation
Visual regression Applitools, Percy จับ UI regression
API testing Postman, REST Assured, httpx API contract และ functional
Performance JMeter, Locust, k6, Blazemeter Load และ stress testing
Service virtualization WireMock, Mockoon mock dependency ภายนอก
Cross-browser cloud Saucelabs, BrowserStack test บนหลาย browser และ device

Stage 7: Deployment Strategy

เลือก Deployment Strategy ให้เหมาะ

ไม่ใช่ทุก change ต้อง deploy ด้วยวิธีเดียวกัน เลือก strategy ตามระดับความเสี่ยง:

Strategy ความเสี่ยง ความเร็ว Rollback ใช้ตอนไหน
Recreate สูง เร็ว ช้า ใช้กับ dev environment เท่านั้น
Rolling Update กลาง กลาง กลาง ค่า default ของ service ที่ traffic ไม่เยอะ
Blue-Green ต่ำ เร็ว ทันที service สำคัญ, มี DB migration
Canary ต่ำมาก ช้า ทันที feature ใหม่ที่ยังไม่รู้ผลกระทบ
A/B Testing ต่ำมาก ช้าที่สุด ทันที ทดลอง feature
Shadow ไม่มี ช้าที่สุด N/A ลอง ML model กับ traffic จริงบน production

Blue-Green Deployment

มีสอง environment หน้าตาเหมือนกันเป๊ะ สลับ traffic ได้ในพริบตา ไม่มี downtime เลย

                   ┌──────────────────┐
                   │   Load Balancer  │
                   └────────┬─────────┘
                            │ 100% traffic
                     ┌──────▼──────┐
                     │  Blue (v1)  │  ← Currently live
                     └─────────────┘

[Deploy v2 to Green environment]

                   ┌──────────────────┐
                   │   Load Balancer  │
                   └────────┬─────────┘
                            │ 100% traffic
                     ┌──────▼──────┐
                     │  Green (v2) │  ← Switch over (instant)
                     └─────────────┘
                     ┌─────────────┐
                     │  Blue (v1)  │  ← Keep alive for rollback
                     └─────────────┘

Blue-Green บน Kubernetes ด้วย Argo Rollouts:

# rollout.yaml
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: payment-service
spec:
  replicas: 10
  strategy:
    blueGreen:
      activeService: payment-service-active
      previewService: payment-service-preview
      autoPromotionEnabled: false       # Manual promotion required
      scaleDownDelaySeconds: 600        # Keep blue alive 10 min
      prePromotionAnalysis:
        templates:
        - templateName: error-rate-check
        args:
        - name: service-name
          value: payment-service-preview

Canary Deployment

ส่ง traffic ไปหา version ใหม่ทีละนิดก่อน ถ้า metric ยังดีอยู่ก็ค่อยๆ เพิ่มสัดส่วนขึ้น

v1 (stable) ──────── 95% ──────────────→ Users
v2 (canary) ────────  5% ──────────────→ Users

[Monitor: error rate, latency, business metrics]

v1 (stable) ──────── 70% ──────────────→ Users
v2 (canary) ──────── 30% ──────────────→ Users

[All good → promote]

v2 (stable) ──────── 100% ─────────────→ Users
# Kubernetes Canary with Argo Rollouts
spec:
  strategy:
    canary:
      steps:
      - setWeight: 5          # 5% traffic to canary
      - pause: {duration: 5m} # Wait 5 minutes
      - analysis:             # Automated analysis
          templates:
          - templateName: canary-analysis
      - setWeight: 20         # 20% if analysis passes
      - pause: {duration: 10m}
      - setWeight: 50
      - pause: {duration: 10m}
      - setWeight: 100        # Full promotion
      canaryService: payment-service-canary
      stableService: payment-service-stable
      trafficRouting:
        istio:
          virtualService:
            name: payment-service-vsvc

Feature Flag: Deployment ≠ Release

deploy code กับ release feature ให้ user เป็นคนละเรื่องกัน แยกออกจากกันได้:

# Using feature flags (LaunchDarkly / Unleash / Flagsmith)
from ldclient import LDClient

def checkout(user_id: str, cart: Cart) -> CheckoutResult:
    client = LDClient(sdk_key=settings.LAUNCH_DARKLY_KEY)

    user = {"key": user_id, "email": get_user_email(user_id)}

    if client.variation("one-click-checkout", user, False):
        # New one-click flow — only shown to flagged users
        return one_click_checkout(cart)
    else:
        # Original flow for everyone else
        return standard_checkout(cart)

ทำแบบนี้แล้วคุณจะ: - deploy ขึ้น production ได้ โดยยังไม่เปิด feature - เปิดให้คนในบริษัทลองใช้ก่อน (dogfooding) - ค่อยๆ เปิดให้ user 1% → 10% → 100% - ปิด feature ได้ทันที (kill switch) ถ้ามีอะไรพัง


Stage 8: ตรวจหลัง Deploy

Smoke Test บน Production

deploy เสร็จปุ๊บ รัน test ชุดเล็กๆ ที่ครอบ critical path ทันที เพื่อเช็กว่า service ขึ้นมาจริง:

# tests/smoke/test_payment_smoke.py
import httpx
import pytest

BASE_URL = os.getenv("TARGET_URL", "https://api.myapp.com")

def test_health_check():
    response = httpx.get(f"{BASE_URL}/health")
    assert response.status_code == 200
    assert response.json()["status"] == "healthy"

def test_payment_endpoint_responds():
    response = httpx.get(f"{BASE_URL}/api/v1/payments/methods")
    assert response.status_code in [200, 401]  # OK or needs auth, not 500

def test_critical_dependency_connectivity():
    response = httpx.get(f"{BASE_URL}/health/deep")
    health = response.json()
    assert health["database"] == "connected"
    assert health["cache"] == "connected"
    # Payment gateway may be external, check degraded mode
    assert health["payment_gateway"] in ["connected", "degraded"]

Infrastructure Vulnerability Scanning

deploy แล้วอย่าลืม scan ตัว infrastructure ด้วย:

# Tenable Nessus — scan deployed infrastructure
nessus --target payment-service.prod.internal \
       --policy "PCI DSS Compliance" \
       --output-format pdf \
       --output-file infra-scan-report.pdf

# Falco — real-time container runtime security
# Detects unusual activity in running containers
cat /etc/falco/falco_rules.yaml
# Falco rule: detect container trying to write to /etc
- rule: Write to /etc in container
  desc: Attempt to write to /etc directory in a container
  condition: >
    container and
    open_write and
    fd.name startswith /etc
  output: "File opened for writing under /etc (%user.name %proc.name %fd.name)"
  priority: ERROR

Chaos Engineering

ลงมือทำให้ระบบบน production พังเองก่อน จะได้เจอจุดอ่อนก่อนที่จุดอ่อนจะไปเจอ user:

# chaos-monkey.py — simplified chaos test
import random
import subprocess
from kubernetes import client, config

def random_pod_kill(namespace: str, label_selector: str):
    """Kill a random pod to test resilience."""
    config.load_kube_config()
    v1 = client.CoreV1Api()

    pods = v1.list_namespaced_pod(
        namespace=namespace,
        label_selector=label_selector
    )

    if not pods.items:
        raise ValueError(f"No pods found matching {label_selector}")

    target = random.choice(pods.items)
    print(f"Killing pod: {target.metadata.name}")

    v1.delete_namespaced_pod(
        name=target.metadata.name,
        namespace=namespace
    )

    # System should recover automatically via Kubernetes

Chaos Engineering ห้าระดับ:

  1. Level 1: ฆ่า pod สักตัวแบบสุ่ม — Kubernetes สร้าง pod ใหม่ขึ้นมาแทนไหม?
  2. Level 2: ปิดทั้ง availability zone — traffic ย้ายไป zone อื่นไหม?
  3. Level 3: ใส่ latency ให้ dependency สำคัญ — circuit breaker ตัดวงจรไหม?
  4. Level 4: อัด CPU/memory ของ node ให้เต็ม — HPA scale out ไหม?
  5. Level 5: จำลอง database failover — application กลับมาทำงานต่อได้ไหม?

Stage 9: Monitoring และ Observability

Observability สามเสาหลัก

log, metric และ trace ตอบคนละคำถาม แต่ต้องใช้คู่กัน:

LOGS     → What happened? (events, errors, audit trail)
METRICS  → How is the system performing? (numbers over time)
TRACES   → Why is this request slow? (distributed request path)

Metric: RED Method

ทุก service ต้องเก็บ metric สามตัวนี้:

Metric Prometheus Query เงื่อนไข Alert
Rate (RPS) rate(http_requests_total[5m]) ต่ำกว่า 50% ของ baseline
Errors rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) > 1%
Duration histogram_quantile(0.99, http_request_duration_seconds_bucket) > 500ms
# Instrumenting a FastAPI service
from prometheus_client import Counter, Histogram, generate_latest
from fastapi import FastAPI, Request
import time

REQUEST_COUNT = Counter(
    "http_requests_total",
    "Total HTTP requests",
    ["method", "endpoint", "status_code"]
)
REQUEST_DURATION = Histogram(
    "http_request_duration_seconds",
    "HTTP request duration",
    ["method", "endpoint"],
    buckets=[0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5]
)

app = FastAPI()

@app.middleware("http")
async def metrics_middleware(request: Request, call_next):
    start = time.time()
    response = await call_next(request)
    duration = time.time() - start

    REQUEST_COUNT.labels(
        method=request.method,
        endpoint=request.url.path,
        status_code=response.status_code
    ).inc()

    REQUEST_DURATION.labels(
        method=request.method,
        endpoint=request.url.path
    ).observe(duration)

    return response

@app.get("/metrics")
def metrics():
    return generate_latest()

Structured Logging

log ที่ไม่มีโครงสร้างก็แค่ noise ส่วน structured log ค้นได้ filter ได้ query ได้:

# Hard to parse, hard to search
print(f"Processing payment for user {user_id}, amount {amount}")
print(f"Error: payment failed - {error}")
import structlog

log = structlog.get_logger()

log.info(
    "payment.processing",
    user_id=user_id,
    amount=str(amount),
    currency=currency,
    payment_method_id=payment_method_id,
    trace_id=get_trace_id()
)

log.error(
    "payment.failed",
    user_id=user_id,
    error_code=error.code,
    error_message=str(error),
    payment_method_id=payment_method_id,
    trace_id=get_trace_id()
)

Output (JSON):

{
  "timestamp": "2026-05-18T10:23:41.123Z",
  "level": "error",
  "event": "payment.failed",
  "user_id": "U001",
  "error_code": "card_declined",
  "error_message": "Your card has insufficient funds",
  "payment_method_id": "PM005",
  "trace_id": "abc123def456"
}

Distributed Tracing ด้วย OpenTelemetry

trace ช่วยให้ตามดู request ตัวเดียวที่วิ่งผ่านหลาย service ได้ตลอดทาง:

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter

# Setup
provider = TracerProvider()
provider.add_span_processor(
    BatchSpanProcessor(OTLPSpanExporter(endpoint="http://otel-collector:4317"))
)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("payment-service")

# Instrument code
async def process_payment(payment_request: PaymentRequest):
    with tracer.start_as_current_span("process_payment") as span:
        span.set_attribute("user.id", payment_request.user_id)
        span.set_attribute("payment.amount", float(payment_request.amount))
        span.set_attribute("payment.currency", payment_request.currency)

        try:
            # Each downstream call creates a child span automatically
            user = await user_service.get_user(payment_request.user_id)
            result = await payment_gateway.charge(payment_request)

            span.set_attribute("payment.transaction_id", result.transaction_id)
            span.set_status(trace.StatusCode.OK)
            return result

        except Exception as e:
            span.record_exception(e)
            span.set_status(trace.StatusCode.ERROR, str(e))
            raise

Alert ตาม SLO

อย่า alert ตามอาการของระบบ ให้ alert ตอนที่ user ได้รับผลกระทบ:

# SLO definition (YAML for Pyrra / Sloth)
apiVersion: pyrra.dev/v1alpha1
kind: ServiceLevelObjective
metadata:
  name: payment-service-availability
spec:
  target: "99.9"          # 99.9% success rate
  window: 30d             # Measured over 30 days
  indicator:
    ratio:
      errors:
        metric: http_requests_total{job="payment-service",status=~"5.."}
      total:
        metric: http_requests_total{job="payment-service"}

  # Alert when we're burning error budget too fast
  alerting:
    burnRateAlerts:
    - short: 5m
      long: 1h
      burnRate: 14.4      # 1h burn: page immediately
      severity: critical
    - short: 30m
      long: 6h
      burnRate: 6         # 6h burn: warn the team
      severity: warning

เลือก Observability Platform

Platform เหมาะกับ จุดแข็ง
Grafana + Prometheus + Loki + Tempo ตั้งเอง, อยากคุมค่าใช้จ่าย LGTM stack ครบชุด, open source
Datadog Enterprise, multi-cloud all-in-one ใช้งานลื่นที่สุด
Dynatrace องค์กรใหญ่, AI-ops Auto-instrumentation, Davis AI
New Relic Full-stack observability free tier ให้เยอะ
Elastic Stack (ELK/EFK) workload ที่ log เยอะ search และ analytics แรง
Splunk ใช้ทั้ง security และ ops มี SIEM ในตัว
AppDynamics (Appdynamic) Enterprise ที่ใช้ Java/.NET APM ละเอียด, ดู business metric ได้

Stage 10: Continuous Improvement และ Feedback Loop

DORA Metrics: ตัวชี้ทิศ

งานวิจัย DORA ของ Google พบ metric สี่ตัวที่บอกได้ว่าองค์กร engineering ไหนทำงานได้ระดับสูง:

Metric Elite High Medium Low
Deployment Frequency หลายครั้ง/วัน รายวัน–รายสัปดาห์ รายสัปดาห์–รายเดือน < รายเดือน
Lead Time for Changes < 1 ชั่วโมง 1 วัน – 1 สัปดาห์ 1 สัปดาห์ – 1 เดือน > 1 เดือน
Change Failure Rate < 5% 5–10% 10–15% > 15%
MTTR < 1 ชั่วโมง < 1 วัน < 1 สัปดาห์ > 1 เดือน

วัด DORA จริงๆ ทำยังไง:

# Simple DORA metric calculator
from datetime import datetime, timedelta
from dataclasses import dataclass
from typing import List

@dataclass
class Deployment:
    deployed_at: datetime
    lead_time_hours: float  # commit to production
    failed: bool

@dataclass
class Incident:
    started_at: datetime
    resolved_at: datetime
    caused_by_deployment: bool

def calculate_dora_metrics(
    deployments: List[Deployment],
    incidents: List[Incident],
    window_days: int = 30
) -> dict:
    cutoff = datetime.now() - timedelta(days=window_days)
    recent_deploys = [d for d in deployments if d.deployed_at > cutoff]
    recent_incidents = [i for i in incidents if i.started_at > cutoff]

    # Deployment Frequency
    deploy_freq = len(recent_deploys) / window_days  # per day

    # Lead Time (average)
    avg_lead_time = sum(d.lead_time_hours for d in recent_deploys) / len(recent_deploys)

    # Change Failure Rate
    failed = [d for d in recent_deploys if d.failed]
    cfr = len(failed) / len(recent_deploys) * 100

    # MTTR
    deployment_incidents = [i for i in recent_incidents if i.caused_by_deployment]
    if deployment_incidents:
        avg_mttr = sum(
            (i.resolved_at - i.started_at).total_seconds() / 3600
            for i in deployment_incidents
        ) / len(deployment_incidents)
    else:
        avg_mttr = 0

    return {
        "deployment_frequency_per_day": round(deploy_freq, 2),
        "avg_lead_time_hours": round(avg_lead_time, 1),
        "change_failure_rate_pct": round(cfr, 1),
        "mean_time_to_recover_hours": round(avg_mttr, 1),
    }

Value Stream Mapping

map value stream ทั้งเส้น แล้วจะเห็นว่าเวลาใน delivery process หายไปตรงไหนบ้าง:

[Idea Created]──3 days──[Dev Starts]──5 days──[Code Review]──1 day──[CI/CD]──2h──[Staging]──3 days──[Production]

Total Lead Time: 12+ days
Value-Added Time: ~6 hours (actual coding + pipeline)
Waste: ~11.5 days (waiting, handoffs, approvals)

ความสูญเปล่าที่เจอบ่อยและควรตัดทิ้ง:

ความสูญเปล่า ตัวอย่าง แก้ยังไง
Overproduction สร้าง feature ที่ไม่มีใครใช้ ผูกงานกับ OKR, ทำ user research
Waiting PR รอ review อยู่ 3 วัน ตั้ง SLA การ review PR, ทำงานแบบ async
Over-processing approve มือ 15 ขั้น ทำ automation, เชื่อผล test
Defects ไปเจอ bug บน production ย้าย test มาไว้ต้นทาง (shift left)
Transportation Email → Jira → Slack → ประชุม มี source of truth ที่เดียว
Partially done feature branch เปิดค้างเป็นสัปดาห์ Trunk-based dev + feature flag
Motion สลับไปมาระหว่าง 6 project ตั้ง WIP limit, ให้ทีมโฟกัส

Blameless Post-Mortem

ระบบพังเมื่อไหร่ ให้เรียนรู้จากเหตุการณ์ โดยไม่หาคนผิด:

## Incident Report: Payment Service Outage — 2026-05-10

**Summary**: Payment service unavailable for 23 minutes, affecting ~4,200 users.

### Timeline
- 14:32 — Deployment of v2.1.0 began
- 14:38 — Deployment complete, health checks passing
- 14:41 — First alert: error rate >5%
- 14:43 — On-call engineer paged
- 14:47 — Root cause identified: new Redis connection pool exhausted
- 14:55 — Rollback initiated
- 15:01 — Service restored, error rate < 0.1%

### Root Cause
New feature added Redis caching but used default pool size (10 connections).
Under production load, pool exhausted causing connection timeouts.

### Why Didn't We Catch This?
- Load test used only 100 concurrent users (production peaks at 2,000)
- Redis connection pool size not monitored as a metric
- No staging environment that matches production scale

### Action Items
| Action | Owner | Due Date |
|--------|-------|---------|
| Add Redis connection pool utilization to dashboards | SRE Team | 2026-05-12 |
| Update load tests to use production-scale traffic | QA Team | 2026-05-18 |
| Add Redis pool exhaustion alert | SRE Team | 2026-05-12 |
| Create staging environment at 25% production scale | Platform Team | 2026-06-01 |

### What Went Well
- Alert fired within 3 minutes of degradation
- Rollback procedure executed without confusion
- On-call runbook was accurate and helpful

ประกอบทุกอย่างเข้าด้วยกัน: CI/CD Pipeline ฉบับเต็ม

นี่คือ GitHub Actions pipeline ฉบับเต็มที่ครอบทุก stage:

# .github/workflows/ci-cd.yml
name: CI/CD Pipeline

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

env:
  REGISTRY: harbor.mycompany.com
  IMAGE_NAME: payment-service
  PYTHON_VERSION: "3.12"

jobs:
  # ─── Stage 1: Code Quality ──────────────────────────────────────
  code-quality:
    name: Code Quality
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: ${{ env.PYTHON_VERSION }}

      - name: Install dependencies
        run: pip install poetry && poetry install

      - name: Lint and format check
        run: |
          poetry run black --check .
          poetry run ruff check .

      - name: SAST — Semgrep
        uses: semgrep/semgrep-action@v1
        with:
          config: p/python p/owasp-top-ten

      - name: SonarQube scan
        uses: SonarSource/sonarqube-scan-action@v2
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}

  # ─── Stage 2: Unit Tests ────────────────────────────────────────
  unit-tests:
    name: Unit Tests
    runs-on: ubuntu-latest
    needs: code-quality
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: ${{ env.PYTHON_VERSION }}

      - name: Install and test
        run: |
          pip install poetry && poetry install
          poetry run pytest tests/unit \
            --cov=src \
            --cov-report=xml \
            --cov-fail-under=80 \
            -v

      - name: Upload coverage
        uses: codecov/codecov-action@v4
        with:
          token: ${{ secrets.CODECOV_TOKEN }}

  # ─── Stage 3: Integration Tests ─────────────────────────────────
  integration-tests:
    name: Integration Tests
    runs-on: ubuntu-latest
    needs: unit-tests
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: testpass
          POSTGRES_DB: testdb
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
      redis:
        image: redis:7
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 10s

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: ${{ env.PYTHON_VERSION }}

      - name: Run integration tests
        env:
          DATABASE_URL: postgresql://postgres:testpass@localhost/testdb
          REDIS_URL: redis://localhost:6379
        run: |
          pip install poetry && poetry install
          poetry run pytest tests/integration -v

  # ─── Stage 4: Build and Scan Image ──────────────────────────────
  build-image:
    name: Build & Scan Image
    runs-on: ubuntu-latest
    needs: integration-tests
    if: github.event_name == 'push'
    outputs:
      image-digest: ${{ steps.build.outputs.digest }}
    steps:
      - uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Login to registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_PASSWORD }}

      - name: Build image
        id: build
        uses: docker/build-push-action@v5
        with:
          context: .
          push: false
          load: true
          tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Generate SBOM
        uses: anchore/sbom-action@v0
        with:
          image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
          format: cyclonedx-json
          output-file: sbom.json

      - name: Scan image — Trivy
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
          format: table
          exit-code: 1
          severity: HIGH,CRITICAL

      - name: Push image
        if: success()
        run: |
          docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}

      - name: Sign image
        uses: sigstore/cosign-installer@v3
        run: |
          cosign sign --key env://COSIGN_PRIVATE_KEY \
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
        env:
          COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}

  # ─── Stage 5: Deploy to Staging ─────────────────────────────────
  deploy-staging:
    name: Deploy to Staging
    runs-on: ubuntu-latest
    needs: build-image
    environment: staging
    steps:
      - uses: actions/checkout@v4

      - name: Update image tag in GitOps repo
        run: |
          git clone https://x-token:${{ secrets.GITOPS_TOKEN }}@github.com/myorg/gitops-repo.git
          cd gitops-repo
          yq e '.spec.template.spec.containers[0].image = "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}"' \
            -i apps/payment-service/staging/deployment.yaml
          git commit -am "chore: deploy payment-service ${{ github.sha }} to staging"
          git push

      - name: Wait for ArgoCD sync
        run: |
          argocd app wait payment-service-staging \
            --timeout 300 \
            --health

      - name: Run smoke tests
        run: |
          poetry run pytest tests/smoke \
            --base-url=https://payment-staging.mycompany.com

  # ─── Stage 6: Deploy to Production ──────────────────────────────
  deploy-production:
    name: Deploy to Production
    runs-on: ubuntu-latest
    needs: deploy-staging
    environment: production
    steps:
      - uses: actions/checkout@v4

      - name: Update image tag in GitOps repo (production)
        run: |
          git clone https://x-token:${{ secrets.GITOPS_TOKEN }}@github.com/myorg/gitops-repo.git
          cd gitops-repo
          yq e '.spec.template.spec.containers[0].image = "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}"' \
            -i apps/payment-service/production/deployment.yaml
          git commit -am "chore: deploy payment-service ${{ github.sha }} to production"
          git push

      - name: Create GitHub release
        uses: semantic-release/semantic-release@v23

      - name: Notify team
        uses: slackapi/slack-github-action@v1
        with:
          payload: |
            {
              "text": "✅ payment-service deployed to production",
              "blocks": [
                {
                  "type": "section",
                  "text": {
                    "type": "mrkdwn",
                    "text": "*payment-service* deployed to production\nCommit: ${{ github.sha }}\nTriggered by: ${{ github.actor }}"
                  }
                }
              ]
            }
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}

DevOps Framework ในภาพเดียว

┌─────────────────────────────────────────────────────────────────────┐
│                    DevOps Delivery Framework                         │
├─────────┬────────────────────┬──────────────────────────────────────┤
│ Stage   │ Gate (Must Pass)   │ Key Tools                            │
├─────────┼────────────────────┼──────────────────────────────────────┤
│ Plan    │ Requirements clear │ Jira, Confluence, Miro               │
├─────────┼────────────────────┼──────────────────────────────────────┤
│ Code    │ PR approved,       │ GitHub/GitLab, SonarQube, Semgrep,   │
│         │ SAST clean         │ Snyk, pre-commit                     │
├─────────┼────────────────────┼──────────────────────────────────────┤
│ Build   │ Unit tests pass,   │ Maven/Poetry/npm, JFrog, Nexus,      │
│         │ coverage > 80%     │ JUnit, pytest                        │
├─────────┼────────────────────┼──────────────────────────────────────┤
│ Package │ Image scan clean,  │ Docker, Trivy, Snyk, Harbor, Cosign  │
│         │ image signed       │ Syft (SBOM), ECR                     │
├─────────┼────────────────────┼──────────────────────────────────────┤
│ Test    │ Integration pass,  │ Pytest, Selenium, Playwright, k6,    │
│         │ no HIGH CVEs       │ OWASP ZAP, Pact, WireMock            │
├─────────┼────────────────────┼──────────────────────────────────────┤
│ Release │ Version bumped,    │ semantic-release, GitHub Releases,   │
│         │ changelog updated  │ Conventional Commits                 │
├─────────┼────────────────────┼──────────────────────────────────────┤
│ Deploy  │ Smoke tests pass,  │ Argo CD, Argo Rollouts, Helm,        │
│         │ health checks OK   │ Kubernetes, Istio                    │
├─────────┼────────────────────┼──────────────────────────────────────┤
│ Operate │ SLOs met           │ Prometheus, Grafana, AlertManager,   │
│         │                    │ PagerDuty, Runbooks                  │
├─────────┼────────────────────┼──────────────────────────────────────┤
│ Monitor │ DORA targets met   │ Datadog, Grafana, Loki, Tempo,       │
│         │                    │ Dynatrace, Elastic Stack             │
└─────────┴────────────────────┴──────────────────────────────────────┘
              ↑_______________ Feedback Loop _______________↑

สรุป

ถ้าเริ่มจากศูนย์ อย่าพยายามทำทุกอย่างในทีเดียว ไล่ทำตาม roadmap นี้ตามลำดับ:

เดือนที่ 1 — Foundation

  • ใช้ version control และบังคับ PR review
  • ใส่ pre-commit hook (lint, ดักจับ secret)
  • เขียน unit test พื้นฐาน (เป้า coverage 50%)
  • ทำ application ให้รันใน container
  • ตั้ง CI pipeline พื้นฐาน (lint → test → build)

เดือนที่ 2 — Quality และ Security

  • เพิ่ม integration test
  • เพิ่ม SAST scanning ใน CI
  • เพิ่ม container image scanning
  • ตั้ง artifact registry
  • ใช้ Conventional Commits + semantic versioning

เดือนที่ 3 — Automation และ Deployment

  • deploy ไป staging อัตโนมัติ
  • เพิ่ม smoke test หลัง deploy
  • ใช้ blue-green หรือ canary deployment
  • ตั้ง GitOps ด้วย Argo CD

เดือนที่ 4+ — Observability และ Improvement

  • เปลี่ยนมาใช้ structured logging
  • เก็บ Prometheus metric (RED method)
  • ตั้ง distributed tracing (OpenTelemetry)
  • กำหนดและ monitor SLO
  • ติดตามและรีวิว DORA metric ทุกเดือน
  • ลองทำ chaos engineering experiment ครั้งแรก

DevOps framework ไม่มีวันเสร็จ ทีมโตขึ้น product โตขึ้น technology เปลี่ยนไป framework ก็ต้องเปลี่ยนตาม เป้าหมายไม่ใช่ pipeline ที่สมบูรณ์แบบตั้งแต่วันแรก แต่คือการปิด feedback loop ระหว่างสิ่งที่เกิดจริงบน production กับการตัดสินใจฝั่ง development ไปเรื่อยๆ เริ่มจากเล็กๆ วัดทุกอย่าง แล้วปรับไปทีละรอบ

มีคำถามหรืออยากคุยต่อ ทักมาได้ทาง LinkedIn, X หรือ email

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.