Module 36 Capstone 5 labs Module cuối

Full Enterprise Capstone: Private + Public + Hybrid + Multi-cloud

Dự án cuối khóa tổng hợp toàn bộ 35 module: thiết kế kiến trúc enterprise end-to-end, provision hạ tầng bằng IaC multi-cloud, triển khai CI/CD + GitOps, bật Observability + SRE + DevSecOps, và bảo vệ final report trước hội đồng kỹ thuật.

Công cụ thực hành Terraform/OpenTofu, kubectl, Helm, ArgoCD, GitHub Actions, Prometheus, Grafana
Nền tảng Azure (AKS), AWS (EKS/Lambda), on-prem (kind/k3s), GitHub, Vault
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)

Capstone — Dự án tích hợp toàn khóa

Module này không dạy kỹ năng mới — nó yêu cầu bạn vận dụng đồng thời kiến thức từ M01–M35. Mỗi lab là một tầng của hệ thống enterprise thực tế: hạ tầng → CI/CD → bảo mật → quan sát → trình bày. Hoàn thành capstone = bạn có 1 portfolio project hoàn chỉnh, end-to-end, có thể trình diễn trong phỏng vấn.

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

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

1.1. Kiến trúc Enterprise Multi-cloud — Nguyên tắc thiết kế

Theo Multi-Cloud Strategy for Cloud Architects (Jeroen Mulder), kiến trúc multi-cloud enterprise cần tuân 5 nguyên tắc cốt lõi: (1) Cloud-agnostic abstraction — dùng Kubernetes, Terraform, và open standards để tránh vendor lock-in; (2) Data gravity awareness — đặt compute gần data, không kéo dữ liệu nhạy cảm qua WAN; (3) Unified Identity — một IdP trung tâm (Azure AD / Okta) liên kết tất cả clouds; (4) Network segmentation — Zero Trust, không trust ngầm giữa clouds; (5) Cost visibility — FinOps từ ngày 1, tag mọi resource theo team/service.

1.2. Kiến trúc tổng thể Capstone

┌─────────────────────────────────────────────────────────────────────────┐
│                        ENTERPRISE CAPSTONE ARCHITECTURE                 │
├──────────────────┬──────────────────────┬───────────────────────────────┤
│   PRIVATE CLOUD  │    PUBLIC CLOUD       │    EDGE / HYBRID              │
│   (on-prem k3s)  │    (Azure + AWS)      │    (VPN / Private Link)       │
│                  │                       │                               │
│  PostgreSQL      │  AKS (prod)           │  ExpressRoute / Site-to-Site  │
│  Vault (secrets) │  EKS (dr/multi-region)│  Azure Private Endpoint       │
│  Internal APIs   │  ACR / ECR (registry) │  DNS Private Zone             │
│  Monitoring      │  Azure Monitor        │                               │
│  (Prometheus)    │  AWS CloudWatch       │                               │
├──────────────────┴──────────────────────┴───────────────────────────────┤
│                        GITOPS / CI/CD LAYER                             │
│  GitHub (source) → GitHub Actions (CI) → ACR (image) → ArgoCD (CD)     │
│  Terraform Cloud / OpenTofu → dev → staging → prod promotion            │
├─────────────────────────────────────────────────────────────────────────┤
│                        PLATFORM SERVICES                                │
│  Observability: Prometheus + Grafana + Loki + Tempo (traces)            │
│  Security: Trivy + OPA/Gatekeeper + Falco + Vault                       │
│  FinOps: Azure Cost Management + AWS Cost Explorer + Kubecost           │
└─────────────────────────────────────────────────────────────────────────┘

1.3. The DevOps Handbook — Value Stream trong Capstone

Từ The DevOps Handbook, 2nd Ed. (Gene Kim et al.), capstone này thể hiện đầy đủ Three Ways:

1.4. Multi-cloud vs Hybrid — Khi nào dùng gì?

PatternUse caseTrade-off chính
HybridData sovereignty, compliance (GDPR, PCI), latency-sensitive workloadsNetwork complexity, egress cost
Multi-cloud (active-active)DR, vendor diversity, best-of-breed services (Azure AI + AWS S3)Operational overhead, skill spread
Multi-cloud (active-passive)Business continuity, pilot migrationCost of idle standby, data sync complexity
Private-first + cloud burstCapEx-heavy environments, peak load handlingAutomation complexity để trigger burst

1.5. FinOps & Capstone Cost Governance

Multi-cloud mà không có FinOps = bill shock. Nguyên tắc: tag everything (team, env, service); set budget alerts trước khi deploy; dùng spot/preemptible nodes cho non-prod; review rightsizing recommendations hàng tuần. Kubecost cung cấp cost per namespace/deployment trực tiếp trong K8s — công cụ thiết yếu cho multi-tenant cluster.

2. Thực hành (Labs)

LAB-176

Thiết kế Kiến trúc Enterprise End-to-End

CLI · VS Code · Mermaid · Git

🎯 Mục tiêu: Tạo Architecture Decision Record (ADR) và diagram đầy đủ cho hệ thống capstone multi-cloud; xác định rõ private/public/hybrid boundaries, network topology, identity federation, và data flow.

🧰 Công cụ / nền tảng: VS Code + Mermaid extension, Git, GitHub. Tùy chọn: draw.io (diagrams.net) cho diagram phức tạp.

📦 Chuẩn bị: Repo capstone mới trên GitHub; VS Code với Markdown Mermaid extension; đã đọc lý thuyết 1.2 (kiến trúc tổng thể).

▶️ Các bước (CLI):

# 1. Tạo repo capstone
mkdir ~/capstone-enterprise && cd ~/capstone-enterprise
git init
mkdir -p docs/adr infra/terraform infra/k8s app

# 2. Viết ADR-001 (Architecture Decision Record)
cat > docs/adr/ADR-001-multi-cloud-strategy.md <<'EOF'
# ADR-001: Multi-Cloud Architecture Strategy

## Status: Accepted
## Date: 2026-05-23

## Context
Doanh nghiệp cần: (a) giữ DB nhạy cảm on-prem (data sovereignty),
(b) co giãn nhanh trên Azure cho workload chính,
(c) DR trên AWS us-east-1, (d) CI/CD hoàn toàn tự động.

## Decision
Hybrid + Multi-cloud: private k3s (on-prem) + Azure AKS (primary prod)
+ AWS EKS (DR/burst). Kết nối qua Azure VPN Gateway + Site-to-Site VPN.
IaC: Terraform với separate state per cloud. GitOps: ArgoCD.

## Consequences
(+) Data sovereignty đảm bảo; vendor diversity cho DR.
(-) Tăng complexity vận hành; cần team hiểu cả Azure và AWS.
(-) Egress cost cần monitor liên tục (FinOps).
EOF

# 3. Tạo architecture diagram (Mermaid)
cat > docs/architecture.md <<'EOF'
# Capstone Architecture

## Network Topology

\`\`\`mermaid
graph TB
  subgraph OnPrem["Private Cloud (on-prem k3s)"]
    DB[(PostgreSQL\nDB nhạy cảm)]
    VAULT[HashiCorp\nVault]
    PROM[Prometheus\nAgent]
  end

  subgraph AzureProd["Azure — Primary Production"]
    AKS[AKS Cluster\nprod namespace]
    ACR[Azure Container\nRegistry]
    KV[Azure Key Vault\n+ Private Endpoint]
    AGW[Application Gateway\n+ WAF]
  end

  subgraph AWS["AWS — DR / Burst"]
    EKS[EKS Cluster\ndr namespace]
    ECR[Elastic Container\nRegistry]
    R53[Route 53\nHealth Check]
  end

  subgraph CICD["CI/CD Layer (GitHub)"]
    GH[GitHub\nSource of Truth]
    GHA[GitHub Actions\nCI Pipeline]
    ARGO[ArgoCD\nCD / GitOps]
  end

  DEV([Developer]) -->|git push| GH
  GH --> GHA
  GHA -->|docker build + scan| ACR
  GHA -->|docker build + scan| ECR
  GHA -->|update manifests| ARGO
  ARGO -->|sync| AKS
  ARGO -->|sync| EKS

  AKS -->|VPN S2S| DB
  AKS --> KV
  AGW --> AKS
  R53 -->|failover| EKS
  PROM -->|remote_write| AKS
\`\`\`

## Data Flow

\`\`\`mermaid
sequenceDiagram
  participant U as User
  participant AGW as App Gateway (WAF)
  participant AKS as AKS (prod)
  participant DB as PostgreSQL (on-prem)
  participant VAULT as Vault

  U->>AGW: HTTPS request
  AGW->>AKS: Forward (TLS termination)
  AKS->>VAULT: Get DB credentials
  VAULT-->>AKS: Dynamic secret (TTL 1h)
  AKS->>DB: Query via VPN tunnel
  DB-->>AKS: Result
  AKS-->>U: Response
\`\`\`
EOF

# 4. Commit
git add docs/
git commit -m "feat: add ADR-001 and full architecture diagrams"
git remote add origin https://github.com/<username>/capstone-enterprise.git
git push -u origin main

🖥️ Đối chiếu GUI / Portal:

Dùng diagrams.net (draw.io) để vẽ diagram visual nếu muốn, xuất sang PNG rồi nhúng vào docs. GitHub render Mermaid inline từ file .md — không cần tool riêng.

✅ Kết quả mong đợi: File ADR-001 có đủ Context/Decision/Consequences; file architecture.md render 2 diagram (network topology + data flow sequence) đúng trên GitHub; repo đã push public.

🧹 Cleanup: Không xóa — đây là living documentation, cập nhật khi kiến trúc thay đổi ở các lab tiếp theo.

LAB-177

Provision Hạ tầng Multi-cloud bằng Terraform/OpenTofu

CLI · Terraform/OpenTofu · Azure CLI · AWS CLI

🎯 Mục tiêu: Dùng Terraform (hoặc OpenTofu) provision AKS (Azure) + VPC/EKS (AWS) + on-prem k3s local — remote state tách biệt mỗi cloud, environment promotion từ dev → staging → prod qua workspace/tfvars.

🧰 Công cụ / nền tảng: Terraform ≥1.8 hoặc OpenTofu ≥1.7, Azure CLI (az), AWS CLI v2, kubectl, kubeconfig merge tool. Tùy chọn: Terraform Cloud (free tier) cho remote state.

📦 Chuẩn bị: az loginaws configure đã xong; subscription Azure có quota cho AKS; AWS account có IAM user đủ quyền EKS; Docker Desktop hoặc kind cho on-prem local.

▶️ Các bước (CLI):

# ── 1. Cấu trúc thư mục IaC ──────────────────────────────────────────────
cd ~/capstone-enterprise/infra/terraform
mkdir -p azure/aks aws/eks shared/networking

# ── 2. Azure AKS module ───────────────────────────────────────────────────
cat > azure/aks/main.tf <<'EOF'
terraform {
  required_providers {
    azurerm = { source = "hashicorp/azurerm", version = "~> 3.100" }
  }
  backend "azurerm" {
    resource_group_name  = "tfstate-rg"
    storage_account_name = "tfstatecapstone"
    container_name       = "tfstate"
    key                  = "azure-aks.tfstate"
  }
}

provider "azurerm" { features {} }

variable "environment" { default = "dev" }
variable "location"    { default = "Southeast Asia" }

resource "azurerm_resource_group" "main" {
  name     = "capstone-${var.environment}-rg"
  location = var.location
  tags     = { env = var.environment, managed_by = "terraform" }
}

resource "azurerm_kubernetes_cluster" "aks" {
  name                = "capstone-${var.environment}-aks"
  location            = azurerm_resource_group.main.location
  resource_group_name = azurerm_resource_group.main.name
  dns_prefix          = "capstone-${var.environment}"

  default_node_pool {
    name       = "system"
    node_count = var.environment == "prod" ? 3 : 1
    vm_size    = var.environment == "prod" ? "Standard_D4s_v5" : "Standard_B2s"
  }

  identity { type = "SystemAssigned" }

  tags = { env = var.environment }
}

output "kube_config" {
  value     = azurerm_kubernetes_cluster.aks.kube_config_raw
  sensitive = true
}
EOF

# ── 3. Tạo remote state storage trên Azure ───────────────────────────────
az group create --name tfstate-rg --location southeastasia
az storage account create \
  --name tfstatecapstone \
  --resource-group tfstate-rg \
  --sku Standard_LRS \
  --encryption-services blob

az storage container create \
  --name tfstate \
  --account-name tfstatecapstone

# ── 4. Provision môi trường dev ──────────────────────────────────────────
cd azure/aks
terraform init
terraform workspace new dev
terraform apply -var="environment=dev" -auto-approve

# Lấy kubeconfig
terraform output -raw kube_config > ~/.kube/capstone-dev.yaml
export KUBECONFIG=~/.kube/capstone-dev.yaml
kubectl get nodes

# ── 5. AWS EKS module (simplified) ──────────────────────────────────────
cat > ../../aws/eks/main.tf <<'EOF'
terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 5.50" }
  }
  backend "s3" {
    bucket = "capstone-tfstate-aws"
    key    = "aws-eks.tfstate"
    region = "us-east-1"
  }
}

provider "aws" { region = "us-east-1" }

variable "environment" { default = "dr" }

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"
  name    = "capstone-${var.environment}-vpc"
  cidr    = "10.1.0.0/16"
  azs     = ["us-east-1a", "us-east-1b"]
  private_subnets = ["10.1.1.0/24", "10.1.2.0/24"]
  public_subnets  = ["10.1.101.0/24", "10.1.102.0/24"]
  enable_nat_gateway = true
}

module "eks" {
  source  = "terraform-aws-modules/eks/aws"
  version = "~> 20.0"
  cluster_name    = "capstone-${var.environment}-eks"
  cluster_version = "1.30"
  vpc_id          = module.vpc.vpc_id
  subnet_ids      = module.vpc.private_subnets
  eks_managed_node_groups = {
    main = {
      min_size     = 1
      max_size     = 3
      desired_size = 1
      instance_types = ["t3.medium"]
    }
  }
}
EOF

# ── 6. On-prem: khởi động k3s local (nếu Linux/WSL2) ───────────────────
# Trên WSL2 hoặc Linux VM:
curl -sfL https://get.k3s.io | sh -s - --write-kubeconfig-mode 644
export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
kubectl get nodes

# Nếu Windows thuần: dùng kind
kind create cluster --name capstone-onprem

# ── 7. Commit ────────────────────────────────────────────────────────────
cd ~/capstone-enterprise
git add infra/terraform/
git commit -m "feat: add multi-cloud Terraform modules (AKS + EKS + on-prem)"
git push

🖥️ Đối chiếu GUI / Portal:

Azure Portal: Resource Groups → "capstone-dev-rg" → Kubernetes Service — xem cluster health, node pools, kubeconfig download. AWS Console: EKS → Clusters → capstone-dr-eks → xem nodes. Terraform Cloud: workspaces tab để thấy state files per environment.

✅ Kết quả mong đợi: kubectl get nodes trả về nodes Ready cho cả 3 môi trường (dev AKS, DR EKS, local k3s/kind); remote state files tồn tại trên Azure Blob + AWS S3; terraform workspace list hiển thị dev/staging/prod.

🧹 Cleanup: terraform destroy -var="environment=dev" khi không dùng (tiết kiệm cost). Prod env chỉ destroy sau khi hoàn thành LAB-180.

LAB-178

Deploy App bằng CI/CD + GitOps (GitHub Actions + ArgoCD)

CLI · GitHub Actions · ArgoCD · Helm · kubectl

🎯 Mục tiêu: Xây CI pipeline (build → test → scan → push image) trên GitHub Actions và CD pipeline (ArgoCD App of Apps) với image update automation, rollout strategy canary, và automatic rollback khi SLO vi phạm.

🧰 Công cụ / nền tảng: GitHub Actions, ArgoCD ≥2.10, Helm ≥3.14, Trivy (image scan), Azure Container Registry, kubectl.

📦 Chuẩn bị: AKS cluster từ LAB-177 đang chạy; ACR đã tạo; GitHub repo có Secrets: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_SUBSCRIPTION_ID (dùng OIDC workload identity — không hardcode password).

▶️ Các bước (CLI):

# ── 1. Cài ArgoCD vào AKS ────────────────────────────────────────────────
kubectl create namespace argocd
kubectl apply -n argocd \
  -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

# Chờ ArgoCD ready
kubectl wait --for=condition=available deployment/argocd-server \
  -n argocd --timeout=120s

# Lấy admin password
kubectl -n argocd get secret argocd-initial-admin-secret \
  -o jsonpath="{.data.password}" | base64 -d; echo

# Port-forward để vào UI (local)
kubectl port-forward svc/argocd-server -n argocd 8080:443 &
# Truy cập: https://localhost:8080 (admin / password-bên-trên)

# ── 2. Tạo App của App (App of Apps pattern) ─────────────────────────────
mkdir -p ~/capstone-enterprise/infra/k8s/argocd
cat > ~/capstone-enterprise/infra/k8s/argocd/root-app.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: root-app
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/<username>/capstone-enterprise
    targetRevision: main
    path: infra/k8s/apps
  destination:
    server: https://kubernetes.default.svc
    namespace: argocd
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
EOF

kubectl apply -f ~/capstone-enterprise/infra/k8s/argocd/root-app.yaml

# ── 3. GitHub Actions CI workflow ────────────────────────────────────────
mkdir -p ~/capstone-enterprise/.github/workflows
cat > ~/capstone-enterprise/.github/workflows/ci.yml <<'EOF'
name: CI Pipeline

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

permissions:
  id-token: write   # OIDC workload identity
  contents: read

jobs:
  build-test-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Login to Azure (OIDC)
        uses: azure/login@v2
        with:
          client-id: ${{ secrets.AZURE_CLIENT_ID }}
          tenant-id: ${{ secrets.AZURE_TENANT_ID }}
          subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}

      - name: Login to ACR
        run: az acr login --name capstoneacr

      - name: Build Docker image
        run: |
          docker build -t capstoneacr.azurecr.io/app:${{ github.sha }} ./app

      - name: Scan image with Trivy
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: capstoneacr.azurecr.io/app:${{ github.sha }}
          format: table
          exit-code: 1          # fail CI nếu có CRITICAL vuln
          severity: CRITICAL,HIGH

      - name: Push image
        if: github.ref == 'refs/heads/main'
        run: |
          docker push capstoneacr.azurecr.io/app:${{ github.sha }}

      - name: Update GitOps manifest
        if: github.ref == 'refs/heads/main'
        run: |
          sed -i "s|image:.*|image: capstoneacr.azurecr.io/app:${{ github.sha }}|" \
            infra/k8s/apps/deployment.yaml
          git config user.email "[email protected]"
          git config user.name "GitHub Actions"
          git add infra/k8s/apps/deployment.yaml
          git commit -m "chore: update image to ${{ github.sha }}" || echo "No change"
          git push
EOF

# ── 4. Canary rollout với Argo Rollouts (optional nâng cao) ──────────────
kubectl create namespace argo-rollouts
kubectl apply -n argo-rollouts \
  -f https://github.com/argoproj/argo-rollouts/releases/latest/download/install.yaml

cat > ~/capstone-enterprise/infra/k8s/apps/rollout.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: capstone-app
  namespace: prod
spec:
  replicas: 4
  strategy:
    canary:
      steps:
        - setWeight: 20
        - pause: {duration: 2m}
        - setWeight: 50
        - pause: {duration: 2m}
        - setWeight: 100
      analysis:
        templates:
          - templateName: success-rate
        startingStep: 2
  selector:
    matchLabels:
      app: capstone-app
  template:
    metadata:
      labels:
        app: capstone-app
    spec:
      containers:
        - name: app
          image: capstoneacr.azurecr.io/app:latest
          ports:
            - containerPort: 8080
EOF

# ── 5. Commit ────────────────────────────────────────────────────────────
cd ~/capstone-enterprise
git add .github/ infra/k8s/
git commit -m "feat: add GitHub Actions CI + ArgoCD App of Apps + canary rollout"
git push

🖥️ Đối chiếu GUI / Portal:

ArgoCD UI (https://localhost:8080): xem sync status, diff, app tree. GitHub Actions: tab Actions → xem pipeline log từng step. Argo Rollouts Dashboard: kubectl argo rollouts dashboard — visualize canary stages.

✅ Kết quả mong đợi: GitHub Actions pipeline xanh; Trivy scan không có CRITICAL; ArgoCD root-app synced; image tag trên deployment.yaml tự động cập nhật sau mỗi push; canary rollout thực hiện 20% → 50% → 100% trong ~4 phút.

🧹 Cleanup: kubectl delete -n argocd -f root-app.yaml khi cần reset. Giữ workflow CI cho production use.

LAB-179

Bật Full Observability + DevSecOps Gate + FinOps

CLI · Helm · kubectl · Prometheus · Grafana · OPA

🎯 Mục tiêu: Cài kube-prometheus-stack (Prometheus + Grafana + Alertmanager + Loki) bằng Helm; tạo SLO dashboard và alert rule; bật OPA/Gatekeeper policy gate (no-latest-tag, resource-limits-required); cài Kubecost để track cost per namespace.

🧰 Công cụ / nền tảng: Helm ≥3.14, kubectl, Prometheus Operator, Grafana, Loki, OPA Gatekeeper, Kubecost (free tier), Falco (runtime security).

📦 Chuẩn bị: AKS cluster từ LAB-177; Helm repos đã add; namespace monitoring và security tồn tại.

▶️ Các bước (CLI):

# ── 1. Cài kube-prometheus-stack ──────────────────────────────────────────
helm repo add prometheus-community \
  https://prometheus-community.github.io/helm-charts
helm repo update

kubectl create namespace monitoring

helm install kube-prom-stack prometheus-community/kube-prometheus-stack \
  --namespace monitoring \
  --set grafana.adminPassword="CapstoneP@ss2026" \
  --set prometheus.prometheusSpec.retention="15d" \
  --set alertmanager.enabled=true

# Chờ pods ready
kubectl -n monitoring wait --for=condition=ready pod -l app.kubernetes.io/name=grafana \
  --timeout=120s

# Port-forward Grafana
kubectl port-forward -n monitoring svc/kube-prom-stack-grafana 3000:80 &
# Truy cập: http://localhost:3000 (admin / CapstoneP@ss2026)

# ── 2. Tạo SLO alert rule ─────────────────────────────────────────────────
cat > ~/capstone-enterprise/infra/k8s/monitoring/slo-alert.yaml <<'EOF'
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: capstone-slo-alerts
  namespace: monitoring
  labels:
    release: kube-prom-stack
spec:
  groups:
    - name: capstone-slo
      rules:
        - alert: ErrorBudgetBurning
          expr: |
            (
              1 - (
                sum(rate(http_requests_total{job="capstone-app",code!~"5.."}[5m]))
                /
                sum(rate(http_requests_total{job="capstone-app"}[5m]))
              )
            ) > 0.01
          for: 5m
          labels:
            severity: critical
          annotations:
            summary: "SLO violation: Error rate >1% (target 99% availability)"
            runbook: "https://github.com/<username>/capstone-enterprise/wiki/runbook-api"
EOF
kubectl apply -f ~/capstone-enterprise/infra/k8s/monitoring/slo-alert.yaml

# ── 3. Cài Loki (log aggregation) ────────────────────────────────────────
helm repo add grafana https://grafana.github.io/helm-charts
helm install loki grafana/loki-stack \
  --namespace monitoring \
  --set promtail.enabled=true \
  --set loki.persistence.enabled=false

# Kiểm tra Loki datasource trong Grafana → Explore → Loki
# Query: {namespace="prod"} |= "error"

# ── 4. OPA Gatekeeper — policy gate ──────────────────────────────────────
kubectl apply -f \
  https://raw.githubusercontent.com/open-policy-agent/gatekeeper/release-3.16/deploy/gatekeeper.yaml

# Policy: cấm image tag "latest"
cat > ~/capstone-enterprise/infra/k8s/policies/no-latest-tag.yaml <<'EOF'
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: nolatesttag
spec:
  crd:
    spec:
      names:
        kind: NoLatestTag
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package nolatesttag
        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          endswith(container.image, ":latest")
          msg := sprintf("Image %v sử dụng tag :latest — không được phép trong prod", [container.image])
        }
---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: NoLatestTag
metadata:
  name: deny-latest-tag
spec:
  match:
    namespaces: ["prod"]
EOF
kubectl apply -f ~/capstone-enterprise/infra/k8s/policies/no-latest-tag.yaml

# Test policy
kubectl run test-latest --image=nginx:latest -n prod 2>&1 | grep -i "denied\|violation" || \
  echo "Policy chưa active — chờ 30s rồi thử lại"

# ── 5. Kubecost — FinOps cost tracking ───────────────────────────────────
helm repo add kubecost https://kubecost.github.io/cost-analyzer
helm install kubecost kubecost/cost-analyzer \
  --namespace kubecost --create-namespace \
  --set kubecostToken="aGVsbUBrdWJlY29zdC5jb20=xm343yadf98"

kubectl port-forward -n kubecost svc/kubecost-cost-analyzer 9090:9090 &
# Truy cập: http://localhost:9090

# Xem cost per namespace
curl -s "http://localhost:9090/model/allocation?window=7d&aggregate=namespace" | \
  python3 -m json.tool | grep -A3 '"prod"'

# ── 6. Falco — runtime security ──────────────────────────────────────────
helm repo add falcosecurity https://falcosecurity.github.io/charts
helm install falco falcosecurity/falco \
  --namespace security --create-namespace \
  --set falco.grpc.enabled=true \
  --set falco.grpcOutput.enabled=true

# Xem Falco alerts
kubectl logs -n security -l app.kubernetes.io/name=falco --tail=20

# ── 7. Commit ────────────────────────────────────────────────────────────
cd ~/capstone-enterprise
git add infra/k8s/monitoring/ infra/k8s/policies/
git commit -m "feat: add full observability stack + OPA policies + Kubecost + Falco"
git push

🖥️ Đối chiếu GUI / Portal:

Grafana (localhost:3000): Import dashboard ID 15760 (Kubernetes Cluster) và ID 13659 (Loki). Azure Monitor: AKS → Insights → xem node/pod metrics không cần cài thêm. Kubecost UI (localhost:9090): Cost Allocation → By Namespace — xem cost mỗi 7 ngày.

✅ Kết quả mong đợi: Grafana hiển thị cluster dashboard real-time; SLO alert rule tồn tại trong Prometheus; OPA từ chối deploy image với tag :latest vào namespace prod; Kubecost hiển thị cost breakdown per namespace; Falco log không có critical alerts khi chạy workload bình thường.

🧹 Cleanup: helm uninstall kubecost -n kubecost nếu cần giải phóng resources trước LAB-180. Giữ monitoring stack để demo trong final presentation.

LAB-180

Bảo vệ Final Report — Presentation & Technical Review

CLI · VS Code · Git · Markdown · GitHub Pages

🎯 Mục tiêu: Viết final technical report đầy đủ (architecture, DORA metrics, cost analysis, security posture, lessons learned); tạo slide deck trình bày; publish lên GitHub Pages làm portfolio showcase; thực hiện peer review theo checklist.

🧰 Công cụ / nền tảng: VS Code, Git, GitHub Pages, Mermaid, tùy chọn: Slidev (presentation-as-code) hoặc Markdown + Pandoc để xuất PDF.

📦 Chuẩn bị: Tất cả LAB-176 đến LAB-179 đã hoàn thành; số liệu DORA thực tế từ GitHub Actions và Prometheus; cost report từ Kubecost.

▶️ Các bước (CLI):

# ── 1. Tạo final report ───────────────────────────────────────────────────
mkdir -p ~/capstone-enterprise/docs/final-report
cat > ~/capstone-enterprise/docs/final-report/README.md <<'EOF'
# Full Enterprise Capstone — Final Report

**Author:** [Tên của bạn] | **Date:** 2026-05-23 | **Instructor:** Trần Văn Hòa (MCT)

---

## 1. Executive Summary
Hệ thống enterprise multi-cloud đã được thiết kế và triển khai thành công với:
- **Private cloud** (on-prem k3s): PostgreSQL + Vault
- **Public cloud — Azure** (AKS): production workloads
- **Public cloud — AWS** (EKS): disaster recovery
- **GitOps CI/CD**: GitHub Actions + ArgoCD, lead time <45 phút
- **Full observability**: Prometheus + Grafana + Loki + Falco
- **DevSecOps**: Trivy + OPA Gatekeeper + secret scanning

---

## 2. Architecture Summary

\`\`\`mermaid
graph LR
  DEV[Developer] -->|push| GH[GitHub]
  GH --> CI[GitHub Actions CI]
  CI -->|scan + build| ACR[Azure ACR]
  CI -->|update manifests| ARGO[ArgoCD]
  ARGO -->|sync| AKS[AKS prod]
  ARGO -->|sync DR| EKS[AWS EKS]
  AKS -->|VPN| ONPREM[(On-prem k3s\nDB + Vault)]
\`\`\`

---

## 3. DORA Metrics (Trước vs Sau)

| Metric | Baseline | Post-Capstone | Cải thiện |
|--------|----------|---------------|-----------|
| Deployment Frequency | 1 lần/tuần | 8 lần/ngày | +5600% |
| Lead Time for Changes | 3 ngày | 43 phút | -97.5% |
| Change Failure Rate | 18% | 3.5% | -81% |
| MTTR | 3.5 giờ | 14 phút | -93% |

---

## 4. Security Posture

| Control | Tool | Trạng thái |
|---------|------|-----------|
| Image vulnerability scan | Trivy | ✅ Block CRITICAL in CI |
| Runtime anomaly detection | Falco | ✅ Active, 0 critical alerts |
| Admission policy (no-latest-tag) | OPA Gatekeeper | ✅ Enforced in prod |
| Secret management | HashiCorp Vault | ✅ Dynamic secrets, TTL 1h |
| mTLS between services | Cilium / Istio | 🔄 In progress |

---

## 5. Cost Analysis (7 ngày — từ Kubecost)

| Namespace | Daily Cost | Notes |
|-----------|-----------|-------|
| prod | $4.20/day | AKS 3 nodes D4s_v5 |
| monitoring | $0.80/day | Prometheus + Grafana |
| argocd | $0.15/day | 2 pods |
| **Total Azure** | **$5.15/day** | ~$155/tháng |
| AWS EKS (DR, idle) | $1.20/day | t3.medium x1 |
| **Grand Total** | **$6.35/day** | ~$190/tháng |

**Tối ưu FinOps:** Spot nodes cho monitoring/argocd namespace → tiết kiệm ~40%.

---

## 6. Lessons Learned

1. **GitOps giảm toán tử manual** đáng kể — nhưng cần chuẩn hóa manifest directory structure từ đầu.
2. **Remote state isolation per cloud** là must-have — không dùng chung state file cho Azure + AWS.
3. **OPA policy nên bật từ dev**, không chỉ prod — phát hiện vi phạm sớm hơn.
4. **Vault dynamic secrets** phức tạp hơn static secrets nhưng worth it cho prod security.
5. **FinOps cần setup từ ngày 1** — Kubecost retroactive analysis ít hữu ích hơn realtime alerts.

---

## 7. Kiến trúc tiếp theo (Next Steps)

- [ ] Bật Istio service mesh + mTLS giữa các services
- [ ] Thêm Chaos Engineering (Chaos Mesh) — fire drill hàng tháng
- [ ] Multi-region active-active với Azure Traffic Manager
- [ ] Platform Engineering: self-service IDP bằng Backstage
EOF

# ── 2. Tạo GitHub Pages để publish report ────────────────────────────────
# Trong repo settings → Pages → Source: GitHub Actions
cat > ~/capstone-enterprise/.github/workflows/publish-docs.yml <<'EOF'
name: Publish Documentation

on:
  push:
    branches: [main]
    paths:
      - 'docs/**'

permissions:
  contents: read
  pages: write
  id-token: write

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/configure-pages@v5
      - uses: actions/upload-pages-artifact@v3
        with:
          path: docs/final-report
      - id: deployment
        uses: actions/deploy-pages@v4
EOF

# ── 3. Peer review checklist ─────────────────────────────────────────────
cat > ~/capstone-enterprise/docs/final-report/review-checklist.md <<'EOF'
# Peer Review Checklist — Capstone Final Report

## Architecture (LAB-176)
- [ ] ADR-001 có đủ Context / Decision / Consequences
- [ ] Network topology diagram đúng: private/public/hybrid boundaries rõ
- [ ] Data flow sequence diagram mô tả đúng luồng auth + data

## Infrastructure (LAB-177)
- [ ] Terraform remote state tách biệt per cloud
- [ ] Environment promotion (dev/staging/prod) hoạt động
- [ ] `terraform plan` không có unexpected changes

## CI/CD + GitOps (LAB-178)
- [ ] GitHub Actions pipeline xanh trên main branch
- [ ] Trivy scan block CRITICAL vulnerabilities
- [ ] ArgoCD tự động sync sau manifest update
- [ ] Canary rollout đã test với 20% → 50% → 100%

## Observability + Security (LAB-179)
- [ ] Grafana dashboard có data (không empty panels)
- [ ] SLO alert rule tồn tại trong Prometheus
- [ ] OPA từ chối deploy với image:latest vào prod
- [ ] Kubecost hiển thị cost per namespace
- [ ] Falco running, không có critical runtime alerts

## Final Report (LAB-180)
- [ ] DORA metrics có số liệu thực tế (không phải placeholder)
- [ ] Cost analysis có breakdown rõ ràng
- [ ] Lessons learned ≥5 điểm cụ thể
- [ ] GitHub Pages link accessible
- [ ] Tất cả code committed và pushed
EOF

# ── 4. Final commit + tag release ────────────────────────────────────────
cd ~/capstone-enterprise
git add .
git commit -m "feat: complete capstone final report with DORA metrics, cost analysis, and lessons learned"
git tag -a v1.0.0 -m "Capstone v1.0.0 — Full Enterprise Multi-cloud Implementation"
git push --follow-tags

🖥️ Đối chiếu GUI / Portal:

GitHub Pages: Settings → Pages → xem URL dạng https://<username>.github.io/capstone-enterprise/ — report accessible public. GitHub Releases: tag v1.0.0 xuất hiện → tạo Release note từ commit history. Grafana: export dashboard JSON để nhúng screenshot vào report.

✅ Kết quả mong đợi: Final report accessible qua GitHub Pages URL; DORA metrics bảng có số liệu thực tế (không phải ví dụ); peer review checklist đầy đủ tick; git tag v1.0.0 tồn tại; repo có ≥20 commits phản ánh toàn bộ quá trình làm capstone.

🧹 Cleanup: Sau khi bảo vệ xong: terraform destroy tất cả cloud resources để tránh bill. Giữ GitHub repo và GitHub Pages — đây là portfolio showcase vĩnh viễn.

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

Bối cảnh — Tập đoàn tài chính RegTech

Công ty fintech có core banking on-prem (yêu cầu PCI-DSS — không được đưa data thẻ lên public cloud), nhưng muốn chạy analytics và mobile API trên Azure, với DR trên AWS. Đội kỹ thuật 8 người, release hiện tại 1 lần/tháng vì sợ rủi ro. CEO muốn release 2 tuần/lần, CISO muốn zero-trust.

Giải pháp Capstone áp dụng

  • LAB-176 (Architecture): ADR ghi rõ: card data ở on-prem k3s (PCI scope); mobile API và analytics trên AKS (out-of-scope); ExpressRoute thay VPN để đảm bảo latency và bandwidth.
  • LAB-177 (IaC): Terraform modules riêng cho PCI-scoped (on-prem) và non-PCI (Azure/AWS) với separate state để audit trail tách biệt.
  • LAB-178 (CI/CD): Hai pipeline: pipeline-prod (stricter — cần 2 approvals + security scan) và pipeline-staging (tự động). Feature flags tách deploy khỏi release.
  • LAB-179 (Observability + Security): Falco alert cho bất kỳ process access vào /proc trên PCI nodes; OPA policy cấm privileged containers; Vault cấp dynamic DB credentials TTL 15 phút cho PCI workloads.
  • Kết quả sau 6 tháng: Deployment frequency: 1/tháng → 12/tháng; Change Failure Rate: 25% → 4%; PCI audit passed lần đầu tiên không có findings; CISO satisfied vì zero-trust enforced tự động qua OPA + Vault.

Chúc mừng hoàn thành khóa học!

Bạn đã hoàn thành toàn bộ 36 module của Full Cloud & DevOps Engineer 2026–2027 — từ DevOps Mindset (M01) đến Full Enterprise Capstone (M36). Capstone này là bằng chứng năng lực thực chiến. Tiếp tục: cập nhật portfolio → thi certification → apply job → grow.

Xem toàn bộ 36 Module

📚 Nguồn tham khảo

Module 35: Certification Roadmap & Portfolio Hoàn thành khóa học
Zalo