用 Argo CD 搭建 GitOps 持续交付

适用场景

希望把 Kubernetes 的部署状态收敛到 Git 仓库,由集群持续拉取并对账,而不是在 CI 里直接执行 kubectl apply。适合多环境、多集群和需要审计变更记录的团队。

前置条件

步骤

  1. 安装 Argo CD:
kubectl create namespace argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
kubectl -n argocd rollout status deploy/argocd-server
  1. 暴露 UI 并获取初始密码:
kubectl -n argocd port-forward svc/argocd-server 8080:443
kubectl -n argocd get secret argocd-initial-admin-secret \
  -o jsonpath='{.data.password}' | base64 -d

生产环境建议通过 Ingress/Gateway 暴露,并接入 OIDC 登录,不要长期使用 port-forward 和 admin 本地账号。

  1. 登录并准备仓库:
argocd login localhost:8080 --username admin --insecure
argocd repo add https://github.com/example/gitops.git \
  --username git --password "$GIT_TOKEN"
  1. 创建 Application:
argocd app create demo \
  --repo https://github.com/example/gitops.git \
  --path apps/demo/overlays/prod \
  --dest-server https://kubernetes.default.svc \
  --dest-namespace demo \
  --sync-policy automated \
  --auto-prune \
  --self-heal
  1. 先手动同步一次并观察差异:
argocd app diff demo
argocd app sync demo
argocd app get demo
  1. 确认稳定后再开启自动同步。删除资源前先确认 auto-prune 的影响范围,生产环境可先用 --sync-option Prune=false 做灰度。

  2. 需要按团队隔离时,创建 AppProject 限制可部署的仓库、集群和命名空间:

argocd proj create team-a \
  --src https://github.com/example/gitops.git \
  --dest https://kubernetes.default.svc,demo

验证

回滚

常见坑

相关命令