Flux CD 2.2 GitOps 工具:基于 Git 分支的 Kubernetes 应用自动更新配置指南

1. 核心概念
  • GitOps 原理:将 Git 仓库作为声明式基础设施的唯一来源,当 Git 分支变更时自动同步到集群。
  • 分支驱动更新:监控特定分支(如 prod/staging),实现环境隔离的自动化部署。
  • Flux 组件
    • Source Controller:监控 Git 仓库变更
    • Kustomize Controller:渲染 Kubernetes 清单
    • Helm Controller:管理 Helm 应用(可选)
2. 前提条件
  • Kubernetes 集群(v1.20+)
  • kubectl 已配置集群访问权限
  • Git 仓库(GitHub/GitLab/Bitbucket)
  • 仓库访问令牌(需 repo 权限)
3. 安装 Flux CLI
curl -s https://fluxcd.io/install.sh | sudo bash
flux check --pre  # 验证环境

4. 引导 Flux 到集群
flux bootstrap git \
  --url=https://github.com/<your-org>/<repo> \
  --branch=main \
  --path=./clusters/production \
  --token-auth

参数说明:

  • --url:Git 仓库地址
  • --branch:监控的主分支
  • --path:集群配置目录(Flux 将在此目录创建配置文件)
5. 配置分支自动更新
场景:监控 staging 分支自动部署
# clusters/production/staging-source.yaml
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: GitRepository
metadata:
  name: staging-source
  namespace: flux-system
spec:
  interval: 1m  # 每分钟检查变更
  url: https://github.com/<your-org>/<repo>
  ref:
    branch: staging  # 目标分支
  secretRef:
    name: git-credentials  # 预创建的密钥

创建同步策略
# clusters/production/staging-sync.yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2
kind: Kustomization
metadata:
  name: staging-apps
  namespace: flux-system
spec:
  interval: 5m
  sourceRef:
    kind: GitRepository
    name: staging-source  # 关联上文的GitRepository
  path: ./apps/staging  # 分支内应用清单路径
  prune: true  # 自动清理已删除资源

6. 验证工作流
  1. 推送变更到分支
    git checkout -b staging
    git add ./apps/staging/deployment.yaml
    git commit -m "Update app version"
    git push origin staging
    

  2. 检查同步状态
    flux get kustomizations --watch
    

  3. 查看事件日志
    flux logs --kind=Kustomization --name=staging-apps
    

7. 高级配置
分支变更通知(Slack)
apiVersion: notification.toolkit.fluxcd.io/v1beta2
kind: Alert
metadata:
  name: branch-update-alert
spec:
  eventSeverity: info
  eventSources:
    - kind: GitRepository
      name: staging-source
  providerRef:
    name: slack-webhook

金丝雀发布(通过分支权重)
spec:
  interval: 1m
  sources:  # 多分支源混合
    - kind: GitRepository
      name: prod-source
      weight: 90  # 90%流量
    - kind: GitRepository
      name: canary-source
      weight: 10  # 10%流量

8. 故障排查
  • 同步失败flux reconcile source git <name> --with-source
  • 凭证问题kubectl -n flux-system get secret git-credentials -o yaml
  • 资源冲突flux suspend kustomization <name> + 手动修复

最佳实践

  • 使用 /.flux.yaml 定义自动 Kustomize 构建
  • 为每个环境隔离分支(dev/staging/prod
  • 启用分支保护规则(防止直接推送)

通过此配置,Flux 将持续监控指定分支的变更,实现 Kubernetes 应用的零接触式部署,确保集群状态始终与 Git 声明一致。

更多推荐