GitOps với Argo CD và pipeline CI/CD
Với Kustomize và Helm, manifest của notes-api đã gọn gàng. Nhưng ai chạy kubectl apply -k hay helm upgrade? Đến giờ vẫn là bạn, từ laptop. Bài này đưa bước cuối cùng vào tự động hóa: GitOps, nơi git trở thành nguồn sự thật duy nhất và một agent trong cluster tự đồng bộ cluster theo git. Bạn sẽ cài Argo CD lên cluster hoc-k8s, giao cho nó quản lý notes-api, thử cố tình làm lệch cluster, rollback bằng git revert, rồi ghép thành pipeline CI/CD hoàn chỉnh từ git push code tới Pod mới.
Vì sao cần GitOps
Triển khai bằng tay hoặc bằng script có những vấn đề quen thuộc:
- Ai đã đổi gì? Lúc 2 giờ sáng ai đó
kubectl edittăng memory limit để chữa cháy. Một tháng sau không ai biết vì sao prod khác file trong git. - Cluster trôi khỏi file: lần
applysau ghi đè bản chữa cháy, sự cố quay lại. - Chìa khóa cluster rải khắp nơi: laptop của từng người, biến bí mật của CI, đều giữ kubeconfig có quyền ghi vào prod.
- Rollback mơ hồ: "bản tốt hôm qua" là commit nào, values nào?
Nhớ lại chương 1: Kubernetes vận hành bằng vòng lặp điều hòa, controller liên tục kéo trạng thái thật về trạng thái mong muốn trong etcd. GitOps mở rộng đúng ý tưởng đó thêm một tầng: trạng thái mong muốn nằm trong git, và một controller liên tục kéo cluster về khớp với git.
Bốn nguyên tắc của OpenGitOps
Dự án OpenGitOps (thuộc CNCF) định nghĩa GitOps bằng bốn nguyên tắc:
| Nguyên tắc | Ý nghĩa | Với notes-api |
|---|---|---|
| Khai báo (declarative) | Hệ thống được mô tả bằng trạng thái mong muốn, không bằng chuỗi lệnh | Thư mục k8s/ Kustomize |
| Có phiên bản và bất biến (versioned and immutable) | Trạng thái mong muốn lưu ở nơi giữ lịch sử đầy đủ, không sửa được quá khứ | Mỗi thay đổi là một commit |
| Kéo tự động (pulled automatically) | Agent tự lấy trạng thái mong muốn từ nguồn | Argo CD đọc repo định kỳ |
| Điều hòa liên tục (continuously reconciled) | Agent liên tục so sánh và sửa lệch | kubectl scale bằng tay bị trả lại |
Push hay pull
| Push (CI chạy kubectl) | Pull (agent trong cluster) | |
|---|---|---|
| Chìa khóa cluster | Nằm trong CI, thường quyền rộng | Ở lại trong cluster; CI chỉ cần quyền ghi repo |
| API server | Phải mở cho CI truy cập được | Không cần mở ra ngoài; agent chỉ đi ra tới git |
| Phát hiện lệch | Không, chỉ áp dụng khi pipeline chạy | Liên tục |
| Kiểm toán | Log của CI | Lịch sử git, pull request, review |
| Rollback | Chạy lại pipeline cũ | git revert |
| Nhiều cluster | Mỗi cluster thêm một bộ chìa khóa trong CI | Mỗi cluster tự kéo |
Điểm bảo mật quan trọng nhất: kẻ chiếm được CI trong mô hình push có ngay quyền admin cluster; trong mô hình pull, họ chỉ sửa được repo, nơi có branch protection và review.
Cơ chế: Argo CD làm gì
Argo CD là công cụ GitOps phổ biến nhất (dự án graduated của CNCF), chạy như một nhóm controller trong namespace argocd:
- repo-server: clone repo, chạy
kustomize buildhoặchelm template, trả về manifest mong muốn. - application-controller: so manifest mong muốn với trạng thái thật trong cluster, tính độ lệch, áp dụng khi cần.
- argocd-server: giao diện web, API cho CLI
argocd. Ngoài ra córedis(cache),dex(đăng nhập SSO),applicationset-controller,notifications-controller.
Đơn vị quản lý là CRD Application: "lấy thư mục này ở repo này, revision này, áp vào cluster này, namespace này". Mỗi Application có hai trạng thái độc lập:
| Sync status | Ý nghĩa | Health status | Ý nghĩa |
|---|---|---|---|
Synced | Cluster khớp git | Healthy | Tài nguyên chạy tốt (Deployment đủ bản sao sẵn sàng...) |
OutOfSync | Cluster khác git | Progressing | Đang tiến tới trạng thái tốt (rollout chưa xong) |
Unknown | Không so sánh được (lỗi repo, lỗi render) | Degraded | Hỏng: Pod crash, rollout quá hạn |
Suspended, Missing | Tạm dừng; chưa tồn tại trong cluster |
Synced + Degraded là tình huống quen: cluster đúng y như git, nhưng thứ trong git đang hỏng (ví dụ tag image không tồn tại).
Sync policy quyết định Argo CD tự động tới đâu: thủ công (chỉ báo OutOfSync, chờ bạn bấm Sync), automated (tự sync khi git đổi), thêm prune (xóa tài nguyên đã bị xóa khỏi git) và selfHeal (sửa lệch khi ai đó đổi cluster bằng tay). Mặc định Argo CD kiểm tra repo khoảng 3 phút một lần; cấu hình webhook từ GitHub để nhận thay đổi ngay.
Thực hành
Bước 1: repo cấu hình
Tạo repo công khai notes-gitops trên GitHub (công khai để Argo CD đọc không cần thông tin đăng nhập; repo riêng tư thì thêm bằng argocd repo add). Đẩy thư mục k8s/ của bài Kustomize lên, dev đang ở image 1.0:
mkdir notes-gitops && cd notes-gitops
cp -r ../k8s .
git init -b main && git add . && git commit -m "notes-api: base + overlays dev/prod"
git remote add origin https://github.com/<github-user>/notes-gitops.git
git push -u origin mainBước 2: cài Argo CD
kubectl create namespace argocd
kubectl apply -n argocd --server-side --force-conflicts \
-f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
kubectl -n argocd wait --for=condition=Available deployment --all --timeout=5m
kubectl -n argocd get podsNAME READY STATUS RESTARTS AGE
argocd-application-controller-0 1/1 Running 0 95s
argocd-applicationset-controller-6d5f8b7c9-x2k4p 1/1 Running 0 95s
argocd-dex-server-7f9c6d8b5-q8w2n 1/1 Running 0 95s
argocd-notifications-controller-5c8f7d9b6-m4t7r 1/1 Running 0 95s
argocd-redis-6b7c8d9f5-h2j6k 1/1 Running 0 95s
argocd-repo-server-7d8f9c6b5-p3r8s 1/1 Running 0 95s
argocd-server-5f6c7d8b9-w9z2x 1/1 Running 0 95s--server-side vì vài CRD của Argo CD quá lớn cho annotation last-applied-configuration. Lấy mật khẩu admin ban đầu và mở giao diện (giữ terminal port-forward chạy):
kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath='{.data.password}' | base64 -d; echo
kubectl port-forward svc/argocd-server -n argocd 8443:443Mở https://localhost:8443 (chứng chỉ tự ký, trình duyệt sẽ cảnh báo), đăng nhập admin. Cài CLI (brew install argocd, hoặc binary argocd-linux-amd64 ở trang releases của argoproj/argo-cd) rồi đăng nhập từ terminal khác:
argocd login localhost:8443 --username admin --insecure
argocd account update-password
kubectl -n argocd delete secret argocd-initial-admin-secret # đã đổi mật khẩu thì không cần nữa--insecure chỉ vì chứng chỉ tự ký trong lab.
Bước 3: Application cho notes-api
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: notes-api
namespace: argocd
finalizers:
- resources-finalizer.argocd.argoproj.io # xóa Application thì xóa luôn tài nguyên
spec:
project: default
source:
repoURL: https://github.com/<github-user>/notes-gitops.git
targetRevision: main
path: k8s/overlays/dev
destination:
server: https://kubernetes.default.svc # chính cluster đang chạy Argo CD
namespace: notes
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=truesource: repo, nhánh (hoặc tag, commit), thư mục. Argo CD tự nhận ra thư mục cókustomization.yamllà Kustomize, cóChart.yamllà Helm.destination: cluster và namespace mặc định cho tài nguyên không ghi namespace.CreateNamespace=true: tạo namespace nếu chưa có.
kubectl apply -f notes-api-app.yaml
argocd app get notes-apiName: argocd/notes-api
Project: default
Server: https://kubernetes.default.svc
Namespace: notes
Source:
- Repo: https://github.com/<github-user>/notes-gitops.git
Target: main
Path: k8s/overlays/dev
Sync Policy: Automated (Prune)
Sync Status: Synced to main (4e1c2d7)
Health Status: Healthy
GROUP KIND NAMESPACE NAME STATUS HEALTH
ConfigMap notes notes-app-config-5hgbddhgt9 Synced
ConfigMap notes notes-config-mdghf966m9 Synced
Service notes notes-api Synced Healthy
apps Deployment notes notes-api Synced Healthy
gateway.networking.k8s.io HTTPRoute notes notes-api SyncedTài nguyên đã tồn tại từ bài Kustomize nên Argo CD chỉ "nhận nuôi": manifest giống hệt, không Pod nào bị tạo lại. Argo CD đánh dấu tài nguyên thuộc Application nào (bản 3.x mặc định bằng annotation argocd.argoproj.io/tracking-id), và prune chỉ xóa tài nguyên mang dấu của chính nó: Postgres, Redis, Secret notes-db tạo bằng tay không bị đụng tới. Trong giao diện web, bạn thấy cây Application → Deployment → ReplicaSet → Pod.
Bước 4: cố tình làm lệch cluster
kubectl -n notes scale deploy notes-api --replicas=5
kubectl -n notes get deploy notes-api -wdeployment.apps/notes-api scaled
NAME READY UP-TO-DATE AVAILABLE AGE
notes-api 1/5 5 1 52m
notes-api 1/1 1 1 52mChỉ vài giây sau, selfHeal kéo số bản sao về 1 như overlay dev. kubectl edit, kubectl set image cũng chịu chung số phận: muốn đổi thì đổi trong git. Tắt selfHeal để chỉ quan sát: Application chuyển OutOfSync, argocd app diff notes-api cho thấy chính xác cluster lệch git ở đâu.
Bước 5: triển khai và rollback bằng git
cd notes-gitops/k8s/overlays/dev
kustomize edit set image notes-api=notes-api:1.1
git commit -am "dev: notes-api 1.1" && git push
argocd app get notes-api --refresh > /dev/null # không muốn đợi chu kỳ 3 phút
kubectl -n notes rollout status deploy/notes-api
curl -s localhost:30080/health; echodeployment "notes-api" successfully rolled out
{"status":"ok","version":"1.1"}Bản 1.1 có lỗi? Rollback bằng git, như mọi thay đổi khác:
git revert HEAD --no-edit && git push
argocd app get notes-api --refresh > /dev/null
kubectl -n notes rollout status deploy/notes-api
curl -s localhost:30080/health; echo
argocd app history notes-apideployment "notes-api" successfully rolled out
{"status":"ok"}
ID DATE REVISION
0 2026-11-28 14:02:11 +0700 +07 main (4e1c2d7)
1 2026-11-28 14:09:37 +0700 +07 main (9b31f0a)
2 2026-11-28 14:12:05 +0700 +07 main (c27d4e8)Lịch sử git ghi lại ai triển khai gì, khi nào, ai rollback. Argo CD cũng có argocd app rollback, nhưng lệnh này bị từ chối khi bật automated (sync tự động sẽ ghi đè ngay), và nó làm cluster lệch git; git revert mới đúng tinh thần GitOps.
Nguồn Helm
Argo CD dùng Helm như một bộ render: chạy helm template rồi tự apply, nên release không hiện trong helm list và vòng đời do Argo CD quản lý. Chart trong git:
source:
repoURL: https://github.com/<github-user>/notes-gitops.git
targetRevision: main
path: charts/notes-api
helm:
releaseName: notes
valueFiles:
- values-dev.yamlChart từ Helm repository:
source:
repoURL: https://stefanprodan.github.io/podinfo
chart: podinfo
targetRevision: 6.17.0
helm:
valuesObject:
replicaCount: 2App of apps và ApplicationSet
Khi có hàng chục Application, bạn cũng không muốn kubectl apply từng cái. App of apps: một Application cha trỏ tới thư mục chứa manifest các Application con, nên thêm ứng dụng mới chỉ là thêm một file vào git. ApplicationSet sinh nhiều Application từ một mẫu và một generator (danh sách, cluster đã đăng ký, thư mục trong git, pull request...):
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: notes-api
namespace: argocd
spec:
goTemplate: true
goTemplateOptions: ["missingkey=error"]
generators:
- list:
elements:
- env: dev
cluster: https://kubernetes.default.svc
- env: prod
cluster: https://prod.example.com:6443
template:
metadata:
name: "notes-api-{{.env}}"
spec:
project: default
source:
repoURL: https://github.com/<github-user>/notes-gitops.git
targetRevision: main
path: "k8s/overlays/{{.env}}"
destination:
server: "{{.cluster}}"
namespace: notes
syncPolicy:
automated:
prune: true
selfHeal: truePipeline CI/CD hoàn chỉnh
Mô hình phổ biến dùng hai repo: repo ứng dụng (code, Dockerfile) và repo cấu hình (manifest). Tách ra để quyền truy cập khác nhau, lịch sử triển khai không lẫn với lịch sử code, và commit sửa tag không kích hoạt lại CI build. Phần build và push image bạn đã làm ở chương CI/CD của khóa Docker; ta chỉ thêm job cập nhật repo cấu hình:
name: build-deploy
on:
push:
branches: [main]
env:
IMAGE: ghcr.io/${{ github.repository_owner }}/notes-api
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
outputs:
tag: ${{ steps.tag.outputs.tag }}
steps:
- uses: actions/checkout@v5
- id: tag
run: echo "tag=sha-${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ env.IMAGE }}:${{ steps.tag.outputs.tag }}
update-config:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
with:
repository: ${{ github.repository_owner }}/notes-gitops
token: ${{ secrets.GITOPS_TOKEN }} # token chỉ có quyền ghi repo notes-gitops
- name: Cài kustomize
run: |
curl -s "https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install_kustomize.sh" | bash
sudo mv kustomize /usr/local/bin/
- name: Cập nhật tag cho dev
env:
TAG: ${{ needs.build.outputs.tag }}
run: |
cd k8s/overlays/dev
kustomize edit set image notes-api=${IMAGE}:${TAG}
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git commit -am "deploy(dev): notes-api ${TAG}"
git push- Tag theo commit (
sha-abc1234) là bất biến: mỗi bản build một tag, git luôn chỉ rõ đang chạy code nào. Đừng dùnglatest. - Pipeline không có kubeconfig nào.
GITOPS_TOKEN(fine-grained token hoặc deploy key) chỉ ghi được repo cấu hình. - Lên prod: một pull request sửa
newTagtrongoverlays/prod, có review, merge là triển khai. - GHCR yêu cầu tên owner viết thường; image riêng tư cần
imagePullSecretstrong cluster. Trên kind của lab, cách đơn giản vẫn làkind load docker-image.
Thay cho job update-config, Argo CD Image Updater có thể theo dõi registry, thấy tag mới khớp quy tắc thì tự cập nhật Application và ghi ngược commit vào git (write-back).
Flux là công cụ GitOps lớn thứ hai (cũng graduated CNCF), theo hướng "chỉ có CRD và controller": GitRepository khai báo nguồn, Kustomization (của Flux, khác file của Kustomize) hoặc HelmRelease khai báo cái cần áp dụng; flux bootstrap github cài Flux và tự quản lý chính nó từ git. Flux không có giao diện web đi kèm như Argo CD. Hai công cụ cùng nguyên tắc, chọn theo thói quen của team.
Secret trong GitOps
GitOps muốn mọi thứ trong git, nhưng Secret của chương 7 chỉ là base64, không được commit. Ba hướng phổ biến:
- Sealed Secrets: mã hóa Secret bằng khóa công khai của controller trong cluster thành
SealedSecret, an toàn để commit; chỉ controller giải mã được và tạo Secret thật. - External Secrets Operator: commit
ExternalSecretchỉ chứa tham chiếu ("lấy khóanotes/dbtừ Vault/AWS Secrets Manager"); operator đọc kho bí mật và tạo Secret. - SOPS: mã hóa giá trị trong file YAML bằng KMS/age; Flux giải mã sẵn, Argo CD cần plugin.
Với notes-api, notes-db sẽ trở thành SealedSecret hoặc ExternalSecret nằm trong k8s/base.
Bẫy thường gặp
1. HPA và replicas giành nhau. Overlay prod ghi replicas: 3, HPA nâng lên 7: Argo CD thấy OutOfSync, selfHeal kéo về 3, HPA lại nâng. Cách tốt nhất là bỏ replicas khỏi manifest khi đã có HPA. Nếu không bỏ được, bảo Argo CD bỏ qua trường đó:
spec:
ignoreDifferences:
- group: apps
kind: Deployment
name: notes-api
jsonPointers:
- /spec/replicas
syncPolicy:
syncOptions:
- RespectIgnoreDifferences=trueRespectIgnoreDifferences=true để chính lúc sync cũng không ghi đè trường này.
2. Chữa cháy bằng kubectl rồi thấy nó biến mất. Đó là selfHeal làm đúng việc. Sửa qua git; khẩn cấp thật thì tạm tắt auto-sync, chữa, rồi đưa thay đổi vào git ngay.
3. prune và finalizer xóa nhiều hơn bạn nghĩ. Đổi tên tài nguyên trong git là tài nguyên cũ bị xóa; xóa Application có finalizer là xóa sạch tài nguyên của nó. Muốn giữ tài nguyên khi gỡ Application: argocd app delete notes-api --cascade=false.
4. Synced nhưng Degraded hoặc mãi Progressing. Git đúng cú pháp nhưng ứng dụng hỏng: tag image không tồn tại (ImagePullBackOff), probe thất bại. Argo CD triển khai đúng thứ bạn commit; gỡ lỗi như chương 13 rồi sửa trong git.
5. Hai bên cùng quản lý một tài nguyên. Argo CD và một người chạy helm upgrade, hoặc hai Application cùng sinh Deployment notes-api: chúng ghi đè nhau liên tục. Mỗi tài nguyên chỉ một chủ.
6. Tag thay đổi được. Đẩy lại notes-api:1.1 với nội dung mới: git không đổi nên Argo CD không làm gì, và các node đã có image cũ không kéo lại. Luôn dùng tag mới cho mỗi bản build.
Tóm tắt
- GitOps: git là nguồn sự thật, agent trong cluster kéo và điều hòa liên tục; bốn nguyên tắc OpenGitOps: khai báo, có phiên bản và bất biến, kéo tự động, điều hòa liên tục.
- Pull an toàn hơn push: chìa khóa cluster ở lại trong cluster, CI chỉ ghi repo; có phát hiện lệch, kiểm toán và rollback qua git.
- Argo CD: repo-server render Kustomize/Helm, application-controller so sánh và đồng bộ; CRD Application gồm
source,destination,syncPolicy(automated,prune,selfHeal,CreateNamespace=true). - Sync status (
Synced/OutOfSync) và health status (Healthy/Progressing/Degraded...) là hai trục độc lập. - Rollback bằng
git revert; app of apps và ApplicationSet quản lý nhiều ứng dụng, nhiều cluster; Flux là lựa chọn tương đương. - Pipeline: CI build và đẩy image tag bất biến, rồi
kustomize edit set imagevà commit vào repo cấu hình (hoặc Image Updater); Argo CD làm phần còn lại. - Secret vào git bằng Sealed Secrets, External Secrets hoặc SOPS; HPA cần bỏ
replicaskhỏi manifest hoặc dùngignoreDifferences.
Comments