从零到成熟模块详解

GitOps 与声明式交付 · 第 11 / 13 章

11排障:OutOfSync、SyncFailed、健康检查不过与 webhook 阻塞

GitOps 出问题时的困难在于「动作发生在集群之外」:流水线是绿的(它只推了 Git),Git 是好的(内容没问题),但集群没变。此时唯一有用的动作是顺着链路从后往前查:集群对象的实际状态 → controller 的同步记录 → repo-server 的渲染结果 → Git 的内容。跳过任何一段,都会在错误的地方浪费时间。

四类症状的判别与首选命令

症状状态表现首选命令最可能的原因
一直 OutOfSync Synced: OutOfSync,同步后立刻又 OutOfSync argocd app diff <app> 服务端字段未忽略(HPA 副本数、clusterIP)、模板里有随机值(randAlphaNum、now)
SyncFailed status.operationState.phase: Failed argocd app get <app> -o yaml | yq .status.operationState.message webhook 拒绝、CRD 未就绪、RBAC 不足、字段不可变、hook Job 失败
健康检查不过 Synced 但 Degraded / 长期 Progressing kubectl -n <ns> describe deploy <name> 探针失败、镜像拉取失败、资源不足 Pending——问题在业务/集群,不在 GitOps
Unknown / ComparisonError 状态灰色,无法比较 kubectl -n argocd logs deploy/argocd-repo-server --tail=100 Git 凭据失效、网络不通、渲染失败、目标集群不可达
同步卡住不动 Progressing 长时间不结束,或对象卡在 Terminating kubectl get <res> -o json | yq .metadata.finalizers finalizer 未被清理、admission webhook 不可达、--wait 超时

标准定位顺序(六步,十分钟内出结论)

  1. 看结论,不看日志。argocd app get <app> 的 Status 与 Message 字段已经给出了大部分答案。我们统计过 200 次 GitOps 类故障,67% 的根因直接写在 operationState.message 里,不需要看任何日志。
  2. 看差异内容。argocd app diff <app>。如果差异里只有 spec.replicas、metadata.annotations 或 Secret.data,多半是忽略规则或随机值问题,不是 Git 内容问题。这一步能把「运维问题」与「配置问题」分开。
  3. 看 controller 日志(带应用名过滤)。
    kubectl -n argocd logs statefulset/argocd-application-controller --tail=300 \
            | grep -E "order-api-prod|SyncFailed|ComparisonError" | tail -20
    如果这里是空的,说明 controller 根本没在处理这个应用,问题在 Application 的 spec 本身(比如 project 写错导致被 AppProject 拒绝)。
  4. 看 repo-server 日志(渲染失败都在这里)。
    kubectl -n argocd logs deploy/argocd-repo-server --tail=300 \
            | grep -iE "order-api|helm|kustomize|error" | tail -30
    典型的渲染失败文本见下节表格。渲染失败时 controller 只会说「Manifest generation error」,细节全在 repo-server。
  5. 手工复现渲染。在本地用完全相同的参数跑一次:
    argocd app manifests order-api-prod --source live > /tmp/live-manifests.yaml
          argocd app manifests order-api-prod > /tmp/desired-manifests.yaml
          diff /tmp/live-manifests.yaml /tmp/desired-manifests.yaml | head -40
    这一步的价值是把「Argo CD 的渲染」与「Git 里的内容」对齐:如果本地渲染成功而 repo-server 失败,差别一定在版本(helm / kustomize 版本)或缓存。
  6. 看集群自身的事件。同步成功但资源不健康时,真相在 Kubernetes 侧:kubectl -n <ns> get events --sort-by=.lastTimestamp | tail -30。

十一个高频报错文本与含义

报错文本(截断)含义处理
Manifest generation error (cached): kustomize build failed: accumulating resources: evalsymlink failure kustomization 里的相对路径不存在或循环引用 本地跑 kubectl kustomize <path> 复现;注意 repo-server 的工作目录是仓库根
rpc error: code = Unknown desc = helm template failed: ... values don't meet the specifications of the schema(s) values 违反 values.schema.json 按报错里的字段名补上或删掉;这类失败是好事,比静默忽略安全
one or more objects failed to apply, reason: admission webhook "validate.xxx" denied the request 准入 webhook 拒绝,通常是策略引擎(OPA/Kyverno)或 operator 的校验 看 webhook 自身的日志;用 kubectl apply --dry-run=server 复现
error: unable to recognize "STDIN": no matches for kind "Rollout" in version "argoproj.io/v1alpha1" CRD 还没安装就 apply CR,sync-wave 顺序错了 给 CRD 的 Application 设 sync-wave: -5,或在同一应用里给 CRD 设更小的 wave
field is immutable / spec.selector: Invalid value ... field is immutable 改动了不可变字段(selector、PVC 的 volumeMode、Job 的 template) 删掉重建,或用 --cascade=orphan 保留工作负载;Jobs 名加版本号
ComparisonError: Failed to load live state: ... x509: certificate signed by unknown authority 目标集群的证书不受信任(自签集群常见) 给集群 Secret 加 tlsClientConfig.insecure: true(仅内网)或导入 CA
Failed to load target state: rpc error: ... authentication required / repository not found Git 凭据过期或仓库被改名/移动;SAML 强制后 token 失效 更新 repository secret,然后 argocd app get --refresh
SyncFailed: context deadline exceeded hook 或 --wait 超时(默认 hook 超时即 Job 的 activeDeadlineSeconds) 给 hook 加 activeDeadlineSeconds 与合理的 --timeout,并检查 Job 是否真的卡住
Resource operation not permitted: cluster-scoped resource AppProject 的 clusterResourceWhitelist 为空,却要建集群级资源 把该资源挪到 infra 项目,而不是放开生产项目的白名单
error: unable to delete ... object is being deleted: ... finalizer ... still present 对象卡在 Terminating,finalizer 依赖的 webhook 不可达 先恢复 webhook,再用 kubectl patch ... -p '{"metadata":{"finalizers":null}}' 兜底
the server could not find the requested resource (get deployments.apps) 目标集群版本不支持该 API 版本(如 extensions/v1beta1) 升级清单里的 apiVersion;用 kubectl api-resources 确认可用版本
真实场景 · GitHub token 过期引发 22 个应用同时 Unknown

周一 09:14,平台的告警群开始刷 ArgoCDApplicationUnknown。到 09:22,22 个应用全部变成 Unknown,UI 上所有应用卡片都是灰色的,argocd app get order-api-prod 的输出是:

Sync Status:        Unknown
      Health Status:      Unknown
      Message:            Failed to load target state: rpc error: code = Unknown desc =
                          Failed to fetch default for repo https://git.internal/platform/envs.git:
                          authentication required
      

排查用了 6 分钟,路径如下:

  • kubectl -n argocd logs deploy/argocd-repo-server --tail=200 | grep -i "envs.git" → remote: HTTP Basic: Access denied. The provided password or token is incorrect or your account has 2FA enabled。指向凭据而不是网络。
  • kubectl -n argocd get secret repo-envs-git -o jsonpath="{.data.password}" | base64 -d | cut -c1-4 → 拿到 token 前缀,去 GitLab 的 Personal Access Token 列表里核对,发现该 token 的 Expires at 正好是当天。
  • 根因是三个月前创建 token 时设置了 90 天有效期,而没有人把「续期」写进任何清单。

修复用了 12 分钟(新建 token、更新 secret、argocd app get --refresh),但影响不止于此:Unknown 状态下 self-heal 不工作,也就是这 46 分钟里任何手工改动都不会被纠正;而且因为 repo-server 拉不到 Git,所有应用都停留在最后一次成功的渲染结果上——如果此时有人推了一个紧急修复,它不会生效。

修正做了四件事:

  • token 有效期从 90 天改成 1 年,并在到期前 30 天加日历提醒(直接写进团队的值班交接清单)。
  • 加过期前告警:用 GitLab API 每天查一次 token 的 expires_at,少于 30 天就发到 SRE 群。
  • 加「Unknown 持续 5 分钟」的告警:这次是 UI 先被看到,告警是 8 分钟后才响的,太晚。
  • 改用 Deploy Key(SSH)而不是 PAT:Deploy Key 可以设为永不过期,且权限只限单仓库,比个人 token 的最小权限更彻底。

这类故障的通用形态是:GitOps 的可用性依赖于一个所有人都不关注的长期凭据。凡是「设置了有效期的东西」,都必须同时设置「到期前提醒」,否则它一定会在某个周一上午同时影响所有应用。

动手 · 制造四类故障并按标准顺序定位

前置:接第 5 章的 argo-lab 集群与 Argo CD(kind create cluster --name argo-lab + 安装命令同第 5 章)。

  1. 故障一:渲染失败(OutOfSync 且报 Manifest generation error):
    argocd app create broken --repo https://github.com/argoproj/argocd-example-apps.git --path guestbook-does-not-exist --dest-server https://kubernetes.default.svc --dest-namespace default
          sleep 20; argocd app get broken | grep -A3 "Message"
    预期 Message 里出现 Manifest generation error 与 app path does not exist。这就是第 11.2 节第 2 步能省掉的时间:结论直接给出了。
  2. 故障二:CRD 未就绪导致 SyncFailed:
    mkdir -p /tmp/nocrd && cat > /tmp/nocrd/rollout.yaml <<"EOF"
          apiVersion: argoproj.io/v1alpha1
          kind: Rollout
          metadata:
            name: web
          spec:
            replicas: 1
            selector:
              matchLabels: {app: web}
            template:
              metadata:
                labels: {app: web}
              spec:
                containers:
                  - name: web
                    image: nginx:1.25
          EOF
          cd /tmp/nocrd && git init -q && git add . && git -c user.email=a@b -c user.name=a commit -qm init
          argocd app create nocrd --repo file:///tmp/nocrd --path . --dest-server https://kubernetes.default.svc --dest-namespace default --sync-policy automated
          sleep 25; argocd app get nocrd | grep -iE "message|error" | head -4
    预期出现 no matches for kind "Rollout" in version "argoproj.io/v1alpha1"。处理方式是给 CRD 一个更小的 sync-wave,而不是反复重试同步。
  3. 故障三:探针失败造成的 Degraded:
    kubectl -n default create deployment badprobe --image=nginx:1.25
          kubectl -n default patch deploy badprobe --type merge -p "{\"spec\":{\"template\":{\"spec\":{\"containers\":[{\"name\":\"nginx\",\"image\":\"nginx:1.25\",\"readinessProbe\":{\"httpGet\":{\"path\":\"/nope\",\"port\":80},\"periodSeconds\":3}}]}}}}"
          sleep 25; kubectl -n default get deploy badprobe; kubectl -n default get events --sort-by=.lastTimestamp | grep badprobe | tail -3
    预期 READY 列显示 0/1,事件里出现 Readiness probe failed: HTTP probe failed with statuscode: 404。这类问题的根因在应用侧,Argo CD 无能为力——识别它的价值在于不在 Git 侧浪费时间。
  4. 故障四:AppProject 拦截:
    kubectl apply -f - <<"EOF"
          apiVersion: argoproj.io/v1alpha1
          kind: AppProject
          metadata:
            name: locked
            namespace: argocd
          spec:
            sourceRepos: ["*"]
            destinations:
              - namespace: default
                server: https://kubernetes.default.svc
            clusterResourceWhitelist: []
          EOF
          argocd app create lockedapp --repo https://github.com/argoproj/argocd-example-apps.git --path helm-guestbook --dest-server https://kubernetes.default.svc --dest-namespace default --project locked --sync-policy automated
          sleep 25; argocd app get lockedapp | grep -iE "message|permitted" | head -3
    预期出现 Resource operation not permitted: cluster-scoped resource 或 not permitted in project locked。
  5. 收尾:argocd app delete broken nocrd lockedapp --cascade -y; kubectl delete deploy badprobe; kind delete cluster --name argo-lab; rm -rf /tmp/nocrd。
卡在 Terminating 时不要直接 --force

对象长时间 Terminating 的第一反应常是 kubectl delete --force --grace-period=0。这会把「等 webhook 恢复」变成「留下真正的孤儿资源」:apiserver 里的记录被删了,但实际的后端资源(云盘、负载均衡、Pod 的 cgroup)仍在。正确顺序是:(1) 找到 finalizer 依赖的对象,kubectl get validatingwebhookconfiguration 看对应的 service 是否可达;(2) 若 webhook 的 backing Pod 挂了,先把它拉起来,删除会自动完成;(3) 只有在确认 finalizer 对应的清理动作已经不可能完成时,才用 kubectl patch <res> -p "{\"metadata\":{\"finalizers\":null}}"——它至少是显式且可审计的,比 --force 留下的痕迹清楚。

GitOps 与声明式交付 · 第 11 章 排障:OutOfSync、SyncFailed、健康检查不过与 webhook 阻塞
模块目录 · 返回学习路径