mcpField
G
gitops-principles

gitops-principles

github.com/julianobarbosa云与 DevOps1458 次安装2 天前更新
代码仓库

关于 gitops-principles

面向 Kubernetes 团队的 GitOps 实践参考指南,涵盖仓库与分支模式、持续协调、安全和运维,并涉及 Azure Arc 与 AKS。

主要功能

  1. 01OpenGitOps 原则
  2. 02仓库与分支模式
  3. 03同步策略与配置
  4. 04安全与密钥实践
  5. 05健康检查与故障排查

适用场景

  1. 01选择 Kubernetes 仓库布局
  2. 02规划开发、预发布和生产环境晋级
  3. 03检查漂移、同步与回滚行为

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/julianobarbosa/claude-code-skills --skill gitops-principles

安装后在 Claude Code 中输入/gitops-principles确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
anti-patterns.md
azure-arc-integration.md
core-principles.md
patterns-and-practices.md
tooling-ecosystem.md
troubleshooting.md
scripts/
gitops-health-check.sh
templates/
application.yaml
applicationset.yaml
kustomization.yaml

详细介绍

GitOps 原则技能

在 Kubernetes 环境中实施 GitOps 方法论的完整指南——这是一种运维框架,其中 Git 是声明式基础设施和应用的唯一事实来源。

什么是 GitOps?

GitOps 是一组实践,使用 Git 仓库作为定义基础设施和应用期望状态的事实来源。自动化流程会确保生产环境与仓库中描述的状态一致。

OpenGitOps 定义(CNCF)

OpenGitOps 项目(CNCF 的一部分)确立了 GitOps 的四项核心原则:

原则描述
1. 声明式必须以声明式方式描述整个系统
2. 版本化且不可变以强制实现不可变性、版本控制和保留策略的方式存储期望状态
3. 自动拉取软件 Agent 会自动从源拉取期望状态
4. 持续协调Agent 会持续观察并尝试应用期望状态

核心概念速查

Git 作为唯一事实来源
┌─────────────────────────────────────────────────────────────────┐
│                        GIT REPOSITORY                           │
│  (Single Source of Truth for Desired State)                    │
├─────────────────────────────────────────────────────────────────┤
│  manifests/                                                     │
│  ├── base/                    # Base configurations             │
│  │   ├── deployment.yaml                                        │
│  │   ├── service.yaml                                           │
│  │   └── kustomization.yaml                                     │
│  └── overlays/                # Environment-specific            │
│      ├── dev/                                                   │
│      ├── staging/                                               │
│      └── production/                                            │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼ Pull (not Push)
┌─────────────────────────────────────────────────────────────────┐
│                      GITOPS CONTROLLER                          │
│  (ArgoCD / Flux / Kargo)                                       │
│  - Continuously watches Git repository                          │
│  - Compares desired state vs actual state                       │
│  - Reconciles differences automatically                         │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼ Apply
┌─────────────────────────────────────────────────────────────────┐
│                    KUBERNETES CLUSTER                           │
│  (Actual State / Runtime Environment)                          │
└─────────────────────────────────────────────────────────────────┘
推送模式与拉取模式
推送模式(传统 CI/CD)拉取模式(GitOps)
CI 系统将变更推送到集群Agent 从 Git 拉取变更
需要在 CI 中配置集群凭据凭据保留在集群内
单次部署持续协调
漂移无法检测自动纠正漂移
手动回滚流程回滚 = git revert
GitOps 的主要优势
  1. 可审计性:Git 历史记录 = 部署历史记录
  2. 安全性:无需外部访问集群
  3. 可靠性:自动纠正漂移
  4. 速度:通过 PR 合并部署
  5. 回滚:简单的 git revert
  6. 灾难恢复:通过 Git 重新部署整个集群

仓库策略

单体仓库与多仓库

单体仓库(所有环境共用一个仓库):

gitops-repo/
├── apps/
│   ├── app-a/
│   │   ├── base/
│   │   └── overlays/
│   │       ├── dev/
│   │       ├── staging/
│   │       └── prod/
│   └── app-b/
└── infrastructure/
    ├── monitoring/
    └── networking/

多仓库(使用独立仓库):

# Repository per concern
app-a-config/          # App A manifests
app-b-config/          # App B manifests
infrastructure/        # Shared infrastructure
cluster-bootstrap/     # Cluster setup
多仓库模式(本项目)

将 基础设施 与 配置值 分离,以实现安全边界:

infra-team/                    # Base configurations, ApplicationSets
├── applications/              # ArgoCD Application definitions
└── helm-base-values/          # Default Helm values

argo-cd-helm-values/           # Environment-specific overrides
├── dev/                       # Development values
├── stg/                       # Staging values
└── prd/                       # Production values

优势:

  • 为不同仓库设置不同的访问控制
  • 分离关注点
  • 隔离特定环境的密钥

分支策略

环境分支
main ────────────────────────────────────► Production
  │
  └──► staging ──────────────────────────► Staging cluster
         │
         └──► develop ───────────────────► Development cluster
使用 Overlay 的主干开发(推荐)
main ────────────────────────────────────► All environments
  │
  ├── overlays/dev/       → Dev cluster
  ├── overlays/staging/   → Staging cluster
  └── overlays/prod/      → Prod cluster
发布分支
main
  │
  ├── release/v1.0 ──────► Production (v1.0)
  ├── release/v1.1 ──────► Production (v1.1)
  └── release/v2.0 ──────► Production (v2.0)

同步策略和方式

自动同步
syncPolicy:
  automated:
    prune: true       # Delete resources not in Git
    selfHeal: true    # Revert manual changes
手动同步(生产环境推荐)
syncPolicy:
  automated: null     # Require explicit sync
同步选项
选项使用场景
CreateNamespace=true自动创建缺失的命名空间
PruneLast=true同步成功后删除资源
ServerSideApply=true处理大型 CRD
ApplyOutOfSyncOnly=true性能优化
Replace=true强制替换资源

声明式配置模式

Kustomize 模式
# base/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - deployment.yaml
  - service.yaml

# overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - ../../base
patchesStrategicMerge:
  - replica-patch.yaml
images:
  - name: myapp
    newTag: v1.2.3
Helm 模式
# Application pointing to Helm chart
spec:
  source:
    repoURL: https://charts.example.com
    chart: my-app
    targetRevision: 1.2.3
    helm:
      releaseName: my-app
      valueFiles:
        - values.yaml
        - values-prod.yaml
多源模式
spec:
  sources:
    - repoURL: https://charts.bitnami.com/bitnami
      chart: nginx
      targetRevision: 15.0.0
      helm:
        valueFiles:
          - $values/nginx/values-prod.yaml
    - repoURL: https://github.com/org/values.git
      targetRevision: main
      ref: values

渐进式交付集成

GitOps 支持渐进式交付模式:

蓝绿部署
# Two applications, traffic shift via Ingress/Service
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: app-blue
---
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: app-green
使用 Argo Rollouts 进行金丝雀发布
apiVersion: argoproj.io/v1alpha1
kind: Rollout
spec:
  strategy:
    canary:
      steps:
        - setWeight: 10
        - pause: {duration: 5m}
        - setWeight: 50
        - pause: {duration: 10m}
环境晋级(Kargo)
Warehouse → Dev Stage → Staging Stage → Production Stage
    │           │              │               │
    └── Freight promotion through environments ───┘

云服务提供商集成

Azure Arc 启用的 Kubernetes 和 AKS

Azure 通过 Microsoft.ArgoCD 集群扩展提供托管的 ArgoCD 体验:

# Simple installation (single node)
az k8s-extension create \
  --resource-group <rg> --cluster-name <cluster> \
  --cluster-type managedClusters \
  --name argocd \
  --extension-type Microsoft.ArgoCD \
  --release-train preview \
  --config deployWithHighAvailability=false

# Production with workload identity (recommended)
# Use Bicep template - see references/azure-arc-integration.md

主要优势:

功能说明
托管安装Azure 负责部署和升级
工作负载标识无需机密的 Azure AD 身份验证
多集群在混合环境中保持 GitOps 一致性
Azure 集成原生支持 ACR、Key Vault 和 Azure AD

先决条件:

  • 已连接 Azure Arc 的集群,或基于 MSI 的 AKS 集群
  • 已注册 Microsoft.KubernetesConfiguration 提供程序
  • 已安装 k8s-extension CLI 扩展

完整的设置指南请参见 references/azure-arc-integration.md。


安全注意事项

机密管理

切勿将机密存储在 Git 中! 可使用:

方法工具
外部机密External Secrets Operator
密封机密Bitnami Sealed Secrets
SOPSMozilla SOPS 加密
VaultHashiCorp Vault + CSI
云 KMSAWS/Azure/GCP 密钥管理
RBAC 最佳实践
# Limit ArgoCD to specific namespaces
apiVersion: argoproj.io/v1alpha1
kind: AppProject
spec:
  destinations:
    - namespace: 'team-a-*'
      server: https://kubernetes.default.svc
  sourceRepos:
    - 'https://github.com/org/team-a-*'
网络策略
  • GitOps 控制器应是唯一能访问 Git 的组件
  • 限制应用命名空间的出站流量
  • 使用网络策略隔离环境

可观测性与调试

健康状态说明
状态含义操作
Healthy所有资源均在运行无
Progressing正在部署等待
Degraded健康检查失败调查原因
Suspended已手动暂停准备就绪后恢复
Missing未找到资源检查清单
常见问题检查清单
  1. 同步失败:检查 YAML 语法和 RBAC 权限
  2. 不同步:比较差异,检查 ignoreDifferences
  3. 状态降级:检查 Pod 日志和资源限制
  4. 资源缺失:验证命名空间,检查修剪设置
漂移检测
# Check application diff
argocd app diff myapp

# Force refresh from Git
argocd app get myapp --refresh

快速决策指南

何时使用 GitOps
  • Kubernetes 原生工作负载
  • 多个环境(dev/staging/prod)
  • 需要部署审计跟踪
  • 团队协作管理基础设施
  • 灾难恢复需求
GitOps 可能不适用的情况
  • 快速变化的开发环境
  • 没有声明式配置的旧系统
  • 需要实时更改配置
  • 单个开发者、单一环境

参考资料

详细信息请参见:

  • references/core-principles.md - 深入了解四大支柱
  • references/patterns-and-practices.md - 分支和仓库模式
  • references/tooling-ecosystem.md - ArgoCD、Flux 与 Kargo 对比
  • references/anti-patterns.md - 应避免的常见错误
  • references/troubleshooting.md - 调试指南
  • references/azure-arc-integration.md - Azure Arc 和 AKS GitOps 设置

模板

templates/ 中提供可直接使用的模板:

  • application.yaml - ArgoCD Application 示例
  • applicationset.yaml - 多集群部署
  • kustomization.yaml - Kustomize 覆盖层结构

脚本

scripts/ 中提供实用脚本:

  • gitops-health-check.sh - 验证 GitOps 设置

外部资源


注意事项

  • selfHeal: true 会与 kubectl edit 冲突: 事件响应期间修补线上资源的工程师会发现,他们的更改几秒内就被还原。请先暂停自动同步,或将修复提交到 Git。
  • 单体仓库 + ApplicationSet git 生成器会给控制器带来很大负载: 每次目录发生更改,都会重新渲染所有应用。拥有 200 个应用的仓库如果 main 分支变更频繁,可能会让控制器 CPU 持续满载。请拆分仓库,或改用 Webhook 而非轮询。
  • PruneLast=true 会与 Helm 钩子冲突: 钩子在同步期间运行,而清理操作在之后执行。后安装钩子创建的资源会在下次同步时被删除,因为它们不在渲染后的清单中。请为钩子添加 Prune=false 注解。
  • 漂移纠正取决于控制器是否能检测到: ArgoCD 跟踪范围之外的资源(例如由 External Secrets Operator 动态生成的 Secret)不会被协调——其中的漂移不可见。请使用显式的 ignoreDifferences。
  • Sealed Secrets 的作用范围是集群级别: 为集群 A 加密的 SealedSecret 无法在集群 B 上解密。多集群 GitOps 需要为每个集群使用单独的密钥,或共用一个密钥(这会破坏安全模型)。
  • git revert 回滚假设镜像标签不可变: 回退清单会还原标签字符串,但可变标签(例如 :latest)现在可能指向不同的镜像。为确保回滚安全,请固定到摘要。

评论

支持 Markdown