Skip to content

13 — GitOps 与 ArgoCD 深度教材

GitOps 是声明式持续交付的最佳实践。ArgoCD 是最流行的 GitOps 控制器。本章覆盖 GitOps 原则、ArgoCD 架构、多环境管理、密钥管理。


1. GitOps 四大原则

1. 声明式:所有配置以 YAML/JSON 声明期望状态
2. 版本化:Git 是唯一的真实来源(Single Source of Truth)
3. 自动拉取:控制器自动从 Git 拉取并应用到集群
4. 持续调谐:控制器不断对比 Git 与集群状态,自动修复漂移

两种模式:
  Pull 模式(推荐):ArgoCD/Flux 从 Git 拉取 → 应用到集群
  Push 模式(不推荐):CI/CD 管道 kubectl apply → 集群
  
Pull 模式优势:
  - 不需要集群凭证暴露在 CI 中
  - 控制器在集群内运行,有实时状态反馈
  - 自动检测和修复配置漂移

2. ArgoCD 架构

ArgoCD 核心组件:
┌───────────────────────────────────────┐
│  API Server(UI + CLI + Webhook)      │
├───────────────────────────────────────┤
│  Repo Server(Git clone + 渲染)       │
├───────────────────────────────────────┤
│  Application Controller(对比 + 同步) │
├───────────────────────────────────────┤
│  Redis(缓存渲染结果)                 │
└───────────────────────────────────────┘

工作流程:
  Git Push → Webhook 通知 ArgoCD → Repo Server 拉取并渲染
  → Application Controller 对比渲染结果与集群状态
  → 如果有差异且自动同步开启 → 应用到集群
  → 状态更新到 UI

3. ArgoCD 生产配置

3.1 Application 定义

yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: web-app
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/org/k8s-manifests.git
    targetRevision: main
    path: overlays/production    # Kustomize 路径
    # 或 Helm:
    # chart: mychart
    # helm:
    #   valueFiles: [values-prod.yaml]
  destination:
    server: https://kubernetes.default.svc
    namespace: production
  syncPolicy:
    automated:
      prune: true              # 删除 Git 中不存在的资源
      selfHeal: true           # 自动修复配置漂移
    syncOptions:
    - CreateNamespace=true
    - PruneLast=true           # 先创建后删除(避免服务中断)
    retry:
      limit: 5
      backoff:
        duration: 5s
        factor: 2

3.2 App of Apps 模式

yaml
# 父 Application 管理子 Applications
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: apps-root
  namespace: argocd
spec:
  source:
    repoURL: https://github.com/org/k8s-manifests.git
    path: apps/                 # 目录下包含多个 Application YAML
  destination:
    server: https://kubernetes.default.svc
    namespace: argocd
---
# apps/web-app.yaml(子 Application)
# apps/monitoring.yaml
# apps/ingress.yaml

4. 密钥管理

ArgoCD + 密钥方案对比:
1. Sealed Secrets:加密 Secret 存入 Git,集群内解密
2. External Secrets Operator:从 Vault/AWS SM 拉取
3. SOPS + age/GPG:文件级加密
4. ArgoCD Vault Plugin:直接从 Vault 注入
yaml
# External Secrets Operator(生产推荐)
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: db-credentials
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: vault-backend
    kind: ClusterSecretStore
  target:
    name: db-credentials
  data:
  - secretKey: password
    remoteRef:
      key: secret/data/production/db
      property: password

5. 面试高频问题

Q: ArgoCD Sync 失败怎么排查?

1. argocd app get <name> → 查看 Sync Status 和 Health
2. argocd app diff <name> → 查看期望与实际差异
3. 检查 Git 仓库访问:Secret 中的 SSH key 或 token
4. 检查渲染错误:argocd app manifests <name>
5. 检查资源冲突:手动 kubectl apply 看报错
6. 常见原因:RBAC 不足、资源配额超限、Image 不存在