loom-fluxcd

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Flux CD GitOps Toolkit

Flux CD GitOps工具包

Overview

概述

Flux CD is a declarative, GitOps continuous delivery solution for Kubernetes. It automatically ensures that the state of your Kubernetes cluster matches the configuration stored in Git repositories.
When to use this skill:
  • Implementing GitOps workflows for Kubernetes
  • Automating Helm chart deployments and upgrades
  • Managing Kustomize overlays across environments
  • Automating container image updates from registries
  • Setting up multi-tenant Kubernetes with isolated teams
  • Integrating Git-based continuous delivery pipelines
  • Managing infrastructure and application dependencies
  • Implementing progressive delivery with canary deployments
Flux CD是针对Kubernetes的声明式GitOps持续交付解决方案。它会自动确保Kubernetes集群的状态与Git仓库中存储的配置保持一致。
何时使用该工具:
  • 为Kubernetes实现GitOps工作流
  • 自动化Helm Chart的部署与升级
  • 跨环境管理Kustomize覆盖配置
  • 自动化从镜像仓库更新容器镜像
  • 搭建支持团队隔离的多租户Kubernetes集群
  • 集成基于Git的持续交付流水线
  • 管理基础设施与应用依赖
  • 通过金丝雀部署实现渐进式交付

Core Architecture

核心架构

Flux is composed of specialized controllers, each handling specific aspects of GitOps:
Flux由多个专用控制器组成,每个控制器负责GitOps的特定环节:

Source Controller

源控制器

  • GitRepository: Fetches artifacts from Git repositories
  • HelmRepository: Fetches Helm charts from chart repositories
  • HelmChart: Fetches charts from GitRepository or HelmRepository sources
  • Bucket: Fetches artifacts from S3-compatible storage
  • GitRepository:从Git仓库拉取制品
  • HelmRepository:从Chart仓库拉取Helm Chart
  • HelmChart:从GitRepository或HelmRepository源拉取Chart
  • Bucket:从兼容S3的存储拉取制品

Kustomize Controller

Kustomize控制器

  • Kustomization: Applies Kustomize overlays and manages reconciliation
  • Supports dependency ordering and health checks
  • Handles pruning of deleted resources
  • Kustomization:应用Kustomize覆盖配置并管理协调过程
  • 支持依赖排序与健康检查
  • 处理已删除资源的清理

Helm Controller

Helm控制器

  • HelmRelease: Manages Helm chart installations and upgrades
  • Supports automated remediation and testing
  • Handles rollbacks on failure
  • HelmRelease:管理Helm Chart的安装与升级
  • 支持自动修复与测试
  • 处理失败时的回滚

Notification Controller

通知控制器

  • Provider: Defines notification endpoints (Slack, MS Teams, etc.)
  • Alert: Sends alerts based on resource events
  • Receiver: Handles webhook notifications from external systems
  • Provider:定义通知端点(Slack、MS Teams等)
  • Alert:基于资源事件发送告警
  • Receiver:处理来自外部系统的Webhook通知

Image Automation Controllers

镜像自动化控制器

  • ImageRepository: Scans container registries for image metadata
  • ImagePolicy: Defines rules for selecting image tags
  • ImageUpdateAutomation: Updates Git repository with new image tags
  • ImageRepository:扫描容器仓库获取镜像元数据
  • ImagePolicy:定义镜像标签选择规则
  • ImageUpdateAutomation:更新Git仓库中的新镜像标签

Installation and Bootstrap

安装与引导

Prerequisites

前置条件

bash
undefined
bash
undefined

Install Flux CLI

安装Flux CLI

curl -s https://fluxcd.io/install.sh | sudo bash
curl -s https://fluxcd.io/install.sh | sudo bash

Or using Homebrew

或使用Homebrew安装

brew install fluxcd/tap/flux
brew install fluxcd/tap/flux

Verify installation

验证安装

flux --version
undefined
flux --version
undefined

Bootstrap with GitHub

通过GitHub引导

bash
undefined
bash
undefined

Export GitHub personal access token

导出GitHub个人访问令牌

export GITHUB_TOKEN=<your-token>
export GITHUB_TOKEN=<your-token>

Bootstrap Flux

引导Flux

flux bootstrap github
--owner=<github-username>
--repository=<repo-name>
--branch=main
--path=clusters/production
--personal
--components-extra=image-reflector-controller,image-automation-controller
undefined
flux bootstrap github
--owner=<github-username>
--repository=<repo-name>
--branch=main
--path=clusters/production
--personal
--components-extra=image-reflector-controller,image-automation-controller
undefined

Bootstrap with GitLab

通过GitLab引导

bash
export GITLAB_TOKEN=<your-token>

flux bootstrap gitlab \
  --owner=<gitlab-group> \
  --repository=<repo-name> \
  --branch=main \
  --path=clusters/production \
  --personal
bash
export GITLAB_TOKEN=<your-token>

flux bootstrap gitlab \
  --owner=<gitlab-group> \
  --repository=<repo-name> \
  --branch=main \
  --path=clusters/production \
  --personal

Pre-commit Validation

提交前验证

Check your manifests before committing:
bash
undefined
提交前检查清单文件:
bash
undefined

Validate all Flux resources

验证所有Flux资源

flux check
flux check

Check specific resources

检查特定资源

kubectl apply --dry-run=server -f clusters/production/
undefined
kubectl apply --dry-run=server -f clusters/production/
undefined

Repository Structure Best Practices

仓库结构最佳实践

Standard Layout

标准布局

text
├── clusters/
│   ├── production/
│   │   ├── flux-system/           # Flux components (managed by bootstrap)
│   │   ├── infrastructure.yaml    # Infrastructure sources & kustomizations
│   │   └── apps.yaml              # Application sources & kustomizations
│   └── staging/
│       ├── flux-system/
│       ├── infrastructure.yaml
│       └── apps.yaml
├── infrastructure/
│   ├── base/                      # Base infrastructure
│   │   ├── ingress-nginx/
│   │   ├── cert-manager/
│   │   └── sealed-secrets/
│   └── overlays/
│       ├── production/
│       └── staging/
└── apps/
    ├── base/
    │   ├── app1/
    │   └── app2/
    └── overlays/
        ├── production/
        └── staging/
text
├── clusters/
│   ├── production/
│   │   ├── flux-system/           # Flux组件(由引导流程管理)
│   │   ├── infrastructure.yaml    # 基础设施源与Kustomization配置
│   │   └── apps.yaml              # 应用源与Kustomization配置
│   └── staging/
│       ├── flux-system/
│       ├── infrastructure.yaml
│       └── apps.yaml
├── infrastructure/
│   ├── base/                      # 基础基础设施
│   │   ├── ingress-nginx/
│   │   ├── cert-manager/
│   │   └── sealed-secrets/
│   └── overlays/
│       ├── production/
│       └── staging/
└── apps/
    ├── base/
    │   ├── app1/
    │   └── app2/
    └── overlays/
        ├── production/
        └── staging/

Multi-Tenancy Layout

多租户布局

text
├── clusters/
│   └── production/
│       ├── flux-system/
│       ├── tenants/
│       │   ├── team-a.yaml        # Team A namespace and RBAC
│       │   └── team-b.yaml        # Team B namespace and RBAC
│       └── infrastructure.yaml
├── tenants/
│   ├── base/
│   │   ├── team-a/
│   │   │   ├── namespace.yaml
│   │   │   ├── rbac.yaml
│   │   │   └── sync.yaml          # GitRepository + Kustomization for team
│   │   └── team-b/
│   │       ├── namespace.yaml
│   │       ├── rbac.yaml
│   │       └── sync.yaml
│   └── overlays/
│       └── production/
└── teams/                         # Separate repos or paths for each team
    ├── team-a-repo/
    └── team-b-repo/
text
├── clusters/
│   └── production/
│       ├── flux-system/
│       ├── tenants/
│       │   ├── team-a.yaml        # Team A的命名空间与RBAC配置
│       │   └── team-b.yaml        # Team B的命名空间与RBAC配置
│       └── infrastructure.yaml
├── tenants/
│   ├── base/
│   │   ├── team-a/
│   │   │   ├── namespace.yaml
│   │   │   ├── rbac.yaml
│   │   │   └── sync.yaml          # 团队的GitRepository + Kustomization配置
│   │   └── team-b/
│   │       ├── namespace.yaml
│   │       ├── rbac.yaml
│   │       └── sync.yaml
│   └── overlays/
│       └── production/
└── teams/                         # 每个团队独立的仓库或路径
    ├── team-a-repo/
    └── team-b-repo/

GitRepository and Kustomization

GitRepository与Kustomization

Basic GitRepository

基础GitRepository

yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
  name: flux-system
  namespace: flux-system
spec:
  interval: 1m0s
  ref:
    branch: main
  url: https://github.com/org/repo
  secretRef:
    name: flux-system
yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
  name: flux-system
  namespace: flux-system
spec:
  interval: 1m0s
  ref:
    branch: main
  url: https://github.com/org/repo
  secretRef:
    name: flux-system

GitRepository with Specific Path

指定路径的GitRepository

yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
  name: apps
  namespace: flux-system
spec:
  interval: 5m0s
  ref:
    branch: main
  url: https://github.com/org/apps-repo
  ignore: |
    # Exclude all
    /*
    # Include specific paths
    !/apps/production/
yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
  name: apps
  namespace: flux-system
spec:
  interval: 5m0s
  ref:
    branch: main
  url: https://github.com/org/apps-repo
  ignore: |
    # 排除所有内容
    /*
    # 包含特定路径
    !/apps/production/

Basic Kustomization

基础Kustomization

yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: infrastructure
  namespace: flux-system
spec:
  interval: 10m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./infrastructure/production
  prune: true
  wait: true
  timeout: 5m0s
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: infrastructure
  namespace: flux-system
spec:
  interval: 10m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./infrastructure/production
  prune: true
  wait: true
  timeout: 5m0s

Kustomization with Dependencies

带依赖的Kustomization

yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: apps
  namespace: flux-system
spec:
  interval: 10m0s
  dependsOn:
    - name: infrastructure
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/production
  prune: true
  wait: true
  timeout: 5m0s
  healthChecks:
    - apiVersion: apps/v1
      kind: Deployment
      name: app-name
      namespace: app-namespace
  postBuild:
    substitute:
      cluster_name: production
      domain: example.com
    substituteFrom:
      - kind: ConfigMap
        name: cluster-vars
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: apps
  namespace: flux-system
spec:
  interval: 10m0s
  dependsOn:
    - name: infrastructure
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/production
  prune: true
  wait: true
  timeout: 5m0s
  healthChecks:
    - apiVersion: apps/v1
      kind: Deployment
      name: app-name
      namespace: app-namespace
  postBuild:
    substitute:
      cluster_name: production
      domain: example.com
    substituteFrom:
      - kind: ConfigMap
        name: cluster-vars

Variable Substitution

变量替换

Create a ConfigMap for cluster-specific variables:
yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: cluster-vars
  namespace: flux-system
data:
  cluster_name: production
  cluster_region: us-east-1
  domain: example.com
Use variables in manifests:
yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  namespace: default
data:
  cluster: ${cluster_name}
  region: ${cluster_region}
  url: https://app.${domain}
创建用于集群特定变量的ConfigMap:
yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: cluster-vars
  namespace: flux-system
data:
  cluster_name: production
  cluster_region: us-east-1
  domain: example.com
在清单中使用变量:
yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  namespace: default
data:
  cluster: ${cluster_name}
  region: ${cluster_region}
  url: https://app.${domain}

Multi-Tenancy Patterns

多租户模式

Namespace Isolation

命名空间隔离

Flux supports multi-tenant clusters where teams have isolated namespaces with their own GitRepository sources and Kustomizations.
Flux支持多租户集群,各团队拥有独立的命名空间,以及自己的GitRepository源和Kustomization配置。

Tenant Bootstrap Pattern

租户引导模式

yaml
undefined
yaml
undefined

clusters/production/tenants/team-a.yaml

clusters/production/tenants/team-a.yaml

apiVersion: v1 kind: Namespace metadata: name: team-a

apiVersion: v1 kind: ServiceAccount metadata: name: team-a-reconciler namespace: team-a

apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: team-a-reconciler namespace: team-a roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects:
  • kind: ServiceAccount name: team-a-reconciler namespace: team-a

apiVersion: source.toolkit.fluxcd.io/v1 kind: GitRepository metadata: name: team-a-repo namespace: team-a spec: interval: 1m url: https://github.com/org/team-a-repo ref: branch: main

apiVersion: kustomize.toolkit.fluxcd.io/v1 kind: Kustomization metadata: name: team-a-apps namespace: team-a spec: interval: 10m serviceAccountName: team-a-reconciler sourceRef: kind: GitRepository name: team-a-repo path: ./apps prune: true validation: client
undefined

apiVersion: v1 kind: Namespace metadata: name: team-a

apiVersion: v1 kind: ServiceAccount metadata: name: team-a-reconciler namespace: team-a

apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: team-a-reconciler namespace: team-a roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects:
  • kind: ServiceAccount name: team-a-reconciler namespace: team-a

apiVersion: source.toolkit.fluxcd.io/v1 kind: GitRepository metadata: name: team-a-repo namespace: team-a spec: interval: 1m url: https://github.com/org/team-a-repo ref: branch: main

apiVersion: kustomize.toolkit.fluxcd.io/v1 kind: Kustomization metadata: name: team-a-apps namespace: team-a spec: interval: 10m serviceAccountName: team-a-reconciler sourceRef: kind: GitRepository name: team-a-repo path: ./apps prune: true validation: client
undefined

Tenant RBAC Restrictions

租户RBAC限制

Restrict tenant reconcilers to their namespace only:
yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: team-a-reconciler
  namespace: team-a
rules:
  - apiGroups: ["*"]
    resources: ["*"]
    verbs: ["*"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: team-a-reconciler
  namespace: team-a
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: team-a-reconciler
subjects:
  - kind: ServiceAccount
    name: team-a-reconciler
    namespace: team-a
限制租户协调器仅能访问自身命名空间:
yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: team-a-reconciler
  namespace: team-a
rules:
  - apiGroups: ["*"]
    resources: ["*"]
    verbs: ["*"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: team-a-reconciler
  namespace: team-a
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: team-a-reconciler
subjects:
  - kind: ServiceAccount
    name: team-a-reconciler
    namespace: team-a

Cross-Tenant Dependencies

跨租户依赖

Teams can depend on shared infrastructure while maintaining isolation:
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: team-a-apps
  namespace: team-a
spec:
  interval: 10m
  dependsOn:
    - name: shared-ingress
      namespace: flux-system
    - name: shared-monitoring
      namespace: flux-system
  sourceRef:
    kind: GitRepository
    name: team-a-repo
  path: ./apps
  prune: true
团队可以依赖共享基础设施,同时保持隔离:
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: team-a-apps
  namespace: team-a
spec:
  interval: 10m
  dependsOn:
    - name: shared-ingress
      namespace: flux-system
    - name: shared-monitoring
      namespace: flux-system
  sourceRef:
    kind: GitRepository
    name: team-a-repo
  path: ./apps
  prune: true

Helm Integration

Helm集成

Flux provides deep integration with Helm for chart-based deployments.
Flux与Helm深度集成,支持基于Chart的部署。

Helm Repository and Helm Release

Helm仓库与Helm发布

HelmRepository

HelmRepository

yaml
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: HelmRepository
metadata:
  name: bitnami
  namespace: flux-system
spec:
  interval: 1h0s
  url: https://charts.bitnami.com/bitnami
yaml
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: HelmRepository
metadata:
  name: bitnami
  namespace: flux-system
spec:
  interval: 1h0s
  url: https://charts.bitnami.com/bitnami

HelmRepository with Authentication

带认证的HelmRepository

yaml
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: HelmRepository
metadata:
  name: private-charts
  namespace: flux-system
spec:
  interval: 1h0s
  url: https://charts.example.com
  secretRef:
    name: helm-charts-auth
---
apiVersion: v1
kind: Secret
metadata:
  name: helm-charts-auth
  namespace: flux-system
type: Opaque
stringData:
  username: user
  password: pass
yaml
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: HelmRepository
metadata:
  name: private-charts
  namespace: flux-system
spec:
  interval: 1h0s
  url: https://charts.example.com
  secretRef:
    name: helm-charts-auth
---
apiVersion: v1
kind: Secret
metadata:
  name: helm-charts-auth
  namespace: flux-system
type: Opaque
stringData:
  username: user
  password: pass

Basic HelmRelease

基础HelmRelease

yaml
apiVersion: helm.toolkit.fluxcd.io/v2beta2
kind: HelmRelease
metadata:
  name: nginx-ingress
  namespace: ingress-nginx
spec:
  interval: 10m0s
  chart:
    spec:
      chart: ingress-nginx
      version: "4.8.x"
      sourceRef:
        kind: HelmRepository
        name: ingress-nginx
        namespace: flux-system
      interval: 1h0s
  values:
    controller:
      service:
        type: LoadBalancer
yaml
apiVersion: helm.toolkit.fluxcd.io/v2beta2
kind: HelmRelease
metadata:
  name: nginx-ingress
  namespace: ingress-nginx
spec:
  interval: 10m0s
  chart:
    spec:
      chart: ingress-nginx
      version: "4.8.x"
      sourceRef:
        kind: HelmRepository
        name: ingress-nginx
        namespace: flux-system
      interval: 1h0s
  values:
    controller:
      service:
        type: LoadBalancer

HelmRelease with ValuesFrom

带ValuesFrom的HelmRelease

yaml
apiVersion: helm.toolkit.fluxcd.io/v2beta2
kind: HelmRelease
metadata:
  name: my-app
  namespace: apps
spec:
  interval: 10m0s
  chart:
    spec:
      chart: my-app
      version: "1.0.x"
      sourceRef:
        kind: HelmRepository
        name: my-charts
        namespace: flux-system
  values:
    replicas: 2
  valuesFrom:
    - kind: ConfigMap
      name: app-config
      valuesKey: values.yaml
    - kind: Secret
      name: app-secrets
      valuesKey: secrets.yaml
yaml
apiVersion: helm.toolkit.fluxcd.io/v2beta2
kind: HelmRelease
metadata:
  name: my-app
  namespace: apps
spec:
  interval: 10m0s
  chart:
    spec:
      chart: my-app
      version: "1.0.x"
      sourceRef:
        kind: HelmRepository
        name: my-charts
        namespace: flux-system
  values:
    replicas: 2
  valuesFrom:
    - kind: ConfigMap
      name: app-config
      valuesKey: values.yaml
    - kind: Secret
      name: app-secrets
      valuesKey: secrets.yaml

HelmRelease with Testing and Rollback

带测试与回滚的HelmRelease

yaml
apiVersion: helm.toolkit.fluxcd.io/v2beta2
kind: HelmRelease
metadata:
  name: my-app
  namespace: apps
spec:
  interval: 10m0s
  chart:
    spec:
      chart: my-app
      version: "1.0.x"
      sourceRef:
        kind: HelmRepository
        name: my-charts
        namespace: flux-system
  install:
    remediation:
      retries: 3
  upgrade:
    remediation:
      retries: 3
      remediateLastFailure: true
    cleanupOnFail: true
  test:
    enable: true
  rollback:
    cleanupOnFail: true
    recreate: true
  values:
    image:
      tag: v1.0.0
yaml
apiVersion: helm.toolkit.fluxcd.io/v2beta2
kind: HelmRelease
metadata:
  name: my-app
  namespace: apps
spec:
  interval: 10m0s
  chart:
    spec:
      chart: my-app
      version: "1.0.x"
      sourceRef:
        kind: HelmRepository
        name: my-charts
        namespace: flux-system
  install:
    remediation:
      retries: 3
  upgrade:
    remediation:
      retries: 3
      remediateLastFailure: true
    cleanupOnFail: true
  test:
    enable: true
  rollback:
    cleanupOnFail: true
    recreate: true
  values:
    image:
      tag: v1.0.0

HelmRelease with Dependencies

带依赖的HelmRelease

yaml
apiVersion: helm.toolkit.fluxcd.io/v2beta2
kind: HelmRelease
metadata:
  name: my-app
  namespace: apps
spec:
  interval: 10m0s
  dependsOn:
    - name: cert-manager
      namespace: cert-manager
    - name: nginx-ingress
      namespace: ingress-nginx
  chart:
    spec:
      chart: my-app
      version: "1.0.x"
      sourceRef:
        kind: HelmRepository
        name: my-charts
        namespace: flux-system
  values:
    ingress:
      enabled: true
      className: nginx
yaml
apiVersion: helm.toolkit.fluxcd.io/v2beta2
kind: HelmRelease
metadata:
  name: my-app
  namespace: apps
spec:
  interval: 10m0s
  dependsOn:
    - name: cert-manager
      namespace: cert-manager
    - name: nginx-ingress
      namespace: ingress-nginx
  chart:
    spec:
      chart: my-app
      version: "1.0.x"
      sourceRef:
        kind: HelmRepository
        name: my-charts
        namespace: flux-system
  values:
    ingress:
      enabled: true
      className: nginx

Secret Management with SOPS

基于SOPS的密钥管理

Install SOPS and Age

安装SOPS与Age

bash
undefined
bash
undefined

Install SOPS

安装SOPS

brew install sops
brew install sops

Install Age

安装Age

brew install age
brew install age

Generate Age key

生成Age密钥

age-keygen -o age.agekey
age-keygen -o age.agekey

Get public key for .sops.yaml

获取公钥用于.sops.yaml

age-keygen -y age.agekey
undefined
age-keygen -y age.agekey
undefined

Configure SOPS

配置SOPS

Create
.sops.yaml
in repository root:
yaml
creation_rules:
  - path_regex: .*/production/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p
  - path_regex: .*/staging/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p
在仓库根目录创建
.sops.yaml
yaml
creation_rules:
  - path_regex: .*/production/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p
  - path_regex: .*/staging/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p

Create Encrypted Secret

创建加密密钥

bash
undefined
bash
undefined

Create secret manifest

创建密钥清单

cat <<EOF > secret.yaml apiVersion: v1 kind: Secret metadata: name: app-secrets namespace: apps stringData: username: admin password: supersecret EOF
cat <<EOF > secret.yaml apiVersion: v1 kind: Secret metadata: name: app-secrets namespace: apps stringData: username: admin password: supersecret EOF

Encrypt with SOPS

使用SOPS加密

sops --encrypt --in-place secret.yaml
sops --encrypt --in-place secret.yaml

Decrypt for viewing

解密查看

sops --decrypt secret.yaml
undefined
sops --decrypt secret.yaml
undefined

Configure Flux for SOPS Decryption

配置Flux支持SOPS解密

Create secret with Age private key:
bash
cat age.agekey | kubectl create secret generic sops-age \
  --namespace=flux-system \
  --from-file=age.agekey=/dev/stdin
Configure Kustomization to decrypt:
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: apps
  namespace: flux-system
spec:
  interval: 10m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/production
  prune: true
  decryption:
    provider: sops
    secretRef:
      name: sops-age
使用Age私钥创建密钥:
bash
cat age.agekey | kubectl create secret generic sops-age \
  --namespace=flux-system \
  --from-file=age.agekey=/dev/stdin
配置Kustomization进行解密:
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: apps
  namespace: flux-system
spec:
  interval: 10m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/production
  prune: true
  decryption:
    provider: sops
    secretRef:
      name: sops-age

SOPS with Multiple Keys

多密钥SOPS配置

For team collaboration, add multiple Age keys:
yaml
creation_rules:
  - path_regex: .*/production/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: >-
      age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p,
      age1zvkyg2lqzraa2lnjvqej32nkuu0ues2s82hzrye869xeexvn73equnujwj,
      age1penhr3v0pklzv6lqrvt3zyqhfvqffkjn5j2qhzc8xr7q8vpfck4q7n8k3f
团队协作时添加多个Age密钥:
yaml
creation_rules:
  - path_regex: .*/production/.*\.yaml
    encrypted_regex: ^(data|stringData)$
    age: >-
      age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p,
      age1zvkyg2lqzraa2lnjvqej32nkuu0ues2s82hzrye869xeexvn73equnujwj,
      age1penhr3v0pklzv6lqrvt3zyqhfvqffkjn5j2qhzc8xr7q8vpfck4q7n8k3f

Image Automation

镜像自动化

Flux can automatically detect new container image versions and update manifests in Git.
Flux可以自动检测新的容器镜像版本并更新Git中的清单。

Image Automation Architecture

镜像自动化架构

The image automation workflow consists of three resources:
  1. ImageRepository - Scans container registry for available tags
  2. ImagePolicy - Defines tag selection rules (semver, regex, alphabetical)
  3. ImageUpdateAutomation - Commits updated image tags back to Git
镜像自动化工作流包含三个资源:
  1. ImageRepository - 扫描容器仓库获取可用标签
  2. ImagePolicy - 定义标签选择规则(语义化版本、正则表达式、字母顺序)
  3. ImageUpdateAutomation - 将更新后的镜像标签提交回Git

Image Automation Workflow

镜像自动化工作流

text
Container Registry
       |
       | (scan for tags)
       v
ImageRepository
       |
       | (filter & select)
       v
  ImagePolicy
       |
       | (update manifests)
       v
ImageUpdateAutomation
       |
       | (commit to Git)
       v
   GitRepository
       |
       | (reconcile)
       v
  Kustomization
       |
       v
   Kubernetes Cluster
text
容器仓库
       |
       | (扫描标签)
       v
ImageRepository
       |
       | (过滤与选择)
       v
  ImagePolicy
       |
       | (更新清单)
       v
ImageUpdateAutomation
       |
       | (提交到Git)
       v
   GitRepository
       |
       | (协调同步)
       v
  Kustomization
       |
       v
   Kubernetes集群

ImageRepository

ImageRepository

yaml
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImageRepository
metadata:
  name: my-app
  namespace: flux-system
spec:
  image: ghcr.io/org/my-app
  interval: 1m0s
yaml
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImageRepository
metadata:
  name: my-app
  namespace: flux-system
spec:
  image: ghcr.io/org/my-app
  interval: 1m0s

ImageRepository with Authentication

带认证的ImageRepository

yaml
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImageRepository
metadata:
  name: my-app
  namespace: flux-system
spec:
  image: registry.example.com/org/my-app
  interval: 1m0s
  secretRef:
    name: registry-credentials
---
apiVersion: v1
kind: Secret
metadata:
  name: registry-credentials
  namespace: flux-system
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: <base64-encoded-docker-config>
yaml
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImageRepository
metadata:
  name: my-app
  namespace: flux-system
spec:
  image: registry.example.com/org/my-app
  interval: 1m0s
  secretRef:
    name: registry-credentials
---
apiVersion: v1
kind: Secret
metadata:
  name: registry-credentials
  namespace: flux-system
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: <base64-encoded-docker-config>

ImagePolicy - Semantic Versioning

ImagePolicy - 语义化版本

yaml
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImagePolicy
metadata:
  name: my-app
  namespace: flux-system
spec:
  imageRepositoryRef:
    name: my-app
  policy:
    semver:
      range: 1.0.x
yaml
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImagePolicy
metadata:
  name: my-app
  namespace: flux-system
spec:
  imageRepositoryRef:
    name: my-app
  policy:
    semver:
      range: 1.0.x

ImagePolicy - Alphabetical

ImagePolicy - 字母顺序

yaml
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImagePolicy
metadata:
  name: my-app-develop
  namespace: flux-system
spec:
  imageRepositoryRef:
    name: my-app
  policy:
    alphabetical:
      order: asc
  filterTags:
    pattern: "^develop-[a-f0-9]+-(?P<ts>[0-9]+)"
    extract: "$ts"
yaml
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImagePolicy
metadata:
  name: my-app-develop
  namespace: flux-system
spec:
  imageRepositoryRef:
    name: my-app
  policy:
    alphabetical:
      order: asc
  filterTags:
    pattern: "^develop-[a-f0-9]+-(?P<ts>[0-9]+)"
    extract: "$ts"

ImagePolicy - Numerical

ImagePolicy - 数字顺序

yaml
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImagePolicy
metadata:
  name: my-app-build
  namespace: flux-system
spec:
  imageRepositoryRef:
    name: my-app
  policy:
    numerical:
      order: asc
  filterTags:
    pattern: "^build-(?P<num>[0-9]+)"
    extract: "$num"
yaml
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImagePolicy
metadata:
  name: my-app-build
  namespace: flux-system
spec:
  imageRepositoryRef:
    name: my-app
  policy:
    numerical:
      order: asc
  filterTags:
    pattern: "^build-(?P<num>[0-9]+)"
    extract: "$num"

ImageUpdateAutomation

ImageUpdateAutomation

yaml
apiVersion: image.toolkit.fluxcd.io/v1beta1
kind: ImageUpdateAutomation
metadata:
  name: my-app
  namespace: flux-system
spec:
  interval: 1m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  git:
    checkout:
      ref:
        branch: main
    commit:
      author:
        email: fluxcdbot@users.noreply.github.com
        name: fluxcdbot
      messageTemplate: |
        Automated image update

        Automation name: {{ .AutomationObject }}

        Files:
        {{ range $filename, $_ := .Updated.Files -}}
        - {{ $filename }}
        {{ end -}}

        Objects:
        {{ range $resource, $_ := .Updated.Objects -}}
        - {{ $resource.Kind }} {{ $resource.Name }}
        {{ end -}}

        Images:
        {{ range .Updated.Images -}}
        - {{.}}
        {{ end -}}
  update:
    path: ./apps/production
    strategy: Setters
yaml
apiVersion: image.toolkit.fluxcd.io/v1beta1
kind: ImageUpdateAutomation
metadata:
  name: my-app
  namespace: flux-system
spec:
  interval: 1m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  git:
    checkout:
      ref:
        branch: main
    commit:
      author:
        email: fluxcdbot@users.noreply.github.com
        name: fluxcdbot
      messageTemplate: |
        Automated image update

        Automation name: {{ .AutomationObject }}

        Files:
        {{ range $filename, $_ := .Updated.Files -}}
        - {{ $filename }}
        {{ end -}}

        Objects:
        {{ range $resource, $_ := .Updated.Objects -}}
        - {{ $resource.Kind }} {{ $resource.Name }}
        {{ end -}}

        Images:
        {{ range .Updated.Images -}}
        - {{.}}
        {{ end -}}
  update:
    path: ./apps/production
    strategy: Setters

Manifest with Image Update Markers

带镜像更新标记的清单

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
  namespace: apps
spec:
  template:
    spec:
      containers:
        - name: app
          image: ghcr.io/org/my-app:1.0.0 # {"$imagepolicy": "flux-system:my-app"}
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
  namespace: apps
spec:
  template:
    spec:
      containers:
        - name: app
          image: ghcr.io/org/my-app:1.0.0 # {"$imagepolicy": "flux-system:my-app"}

Image Automation Best Practices

镜像自动化最佳实践

Environment Strategy:
  • Enable automation in development/staging first
  • Use manual approval for production (PR-based workflow)
  • Test policy rules before deploying
Tag Policies:
  • Use semver for releases (e.g.,
    1.0.x
    ,
    >=1.0.0
    )
  • Use regex for branch-based tags (e.g.,
    ^develop-.*
    )
  • Use numerical for build numbers
Security:
  • Scan images before deployment (integrate with CI)
  • Use private registries with authentication
  • Enable image signing verification
环境策略:
  • 先在开发/预发布环境启用自动化
  • 生产环境使用手动审批(基于PR的工作流)
  • 部署前测试规则
标签策略:
  • 发布版本使用语义化版本(如
    1.0.x
    ,
    >=1.0.0
  • 分支标签使用正则表达式(如
    ^develop-.*
  • 构建编号使用数字顺序
安全:
  • 部署前扫描镜像(与CI集成)
  • 使用带认证的私有仓库
  • 启用镜像签名验证

ImageUpdateAutomation with Push Branch

带推送分支的ImageUpdateAutomation

For PR-based workflows:
yaml
apiVersion: image.toolkit.fluxcd.io/v1beta1
kind: ImageUpdateAutomation
metadata:
  name: my-app
  namespace: flux-system
spec:
  interval: 1m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  git:
    checkout:
      ref:
        branch: main
    push:
      branch: image-updates
    commit:
      author:
        email: fluxcdbot@users.noreply.github.com
        name: fluxcdbot
      messageTemplate: |
        Automated image update by Flux

        [ci skip]
  update:
    path: ./apps/production
    strategy: Setters
基于PR的工作流:
yaml
apiVersion: image.toolkit.fluxcd.io/v1beta1
kind: ImageUpdateAutomation
metadata:
  name: my-app
  namespace: flux-system
spec:
  interval: 1m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  git:
    checkout:
      ref:
        branch: main
    push:
      branch: image-updates
    commit:
      author:
        email: fluxcdbot@users.noreply.github.com
        name: fluxcdbot
      messageTemplate: |
        Automated image update by Flux

        [ci skip]
  update:
    path: ./apps/production
    strategy: Setters

Notifications

通知

Slack Provider

Slack Provider

yaml
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Provider
metadata:
  name: slack
  namespace: flux-system
spec:
  type: slack
  channel: flux-notifications
  secretRef:
    name: slack-webhook-url
---
apiVersion: v1
kind: Secret
metadata:
  name: slack-webhook-url
  namespace: flux-system
stringData:
  address: https://hooks.slack.com/services/YOUR/WEBHOOK/URL
yaml
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Provider
metadata:
  name: slack
  namespace: flux-system
spec:
  type: slack
  channel: flux-notifications
  secretRef:
    name: slack-webhook-url
---
apiVersion: v1
kind: Secret
metadata:
  name: slack-webhook-url
  namespace: flux-system
stringData:
  address: https://hooks.slack.com/services/YOUR/WEBHOOK/URL

Alert for Kustomization Failures

Kustomization失败告警

yaml
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Alert
metadata:
  name: kustomization-failures
  namespace: flux-system
spec:
  providerRef:
    name: slack
  eventSeverity: error
  eventSources:
    - kind: Kustomization
      name: "*"
  exclusionList:
    - ".*health check failed.*"
yaml
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Alert
metadata:
  name: kustomization-failures
  namespace: flux-system
spec:
  providerRef:
    name: slack
  eventSeverity: error
  eventSources:
    - kind: Kustomization
      name: "*"
  exclusionList:
    - ".*health check failed.*"

Alert for HelmRelease Events

HelmRelease事件告警

yaml
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Alert
metadata:
  name: helm-releases
  namespace: flux-system
spec:
  providerRef:
    name: slack
  eventSeverity: info
  eventSources:
    - kind: HelmRelease
      name: "*"
      namespace: "*"
  summary: "Helm Release {{ .InvolvedObject.name }} in {{ .InvolvedObject.namespace }}"
yaml
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Alert
metadata:
  name: helm-releases
  namespace: flux-system
spec:
  providerRef:
    name: slack
  eventSeverity: info
  eventSources:
    - kind: HelmRelease
      name: "*"
      namespace: "*"
  summary: "Helm Release {{ .InvolvedObject.name }} in {{ .InvolvedObject.namespace }}"

Microsoft Teams Provider

Microsoft Teams Provider

yaml
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Provider
metadata:
  name: msteams
  namespace: flux-system
spec:
  type: msteams
  secretRef:
    name: msteams-webhook-url
---
apiVersion: v1
kind: Secret
metadata:
  name: msteams-webhook-url
  namespace: flux-system
stringData:
  address: https://outlook.office.com/webhook/YOUR/WEBHOOK/URL
yaml
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Provider
metadata:
  name: msteams
  namespace: flux-system
spec:
  type: msteams
  secretRef:
    name: msteams-webhook-url
---
apiVersion: v1
kind: Secret
metadata:
  name: msteams-webhook-url
  namespace: flux-system
stringData:
  address: https://outlook.office.com/webhook/YOUR/WEBHOOK/URL

Receiver for GitHub Webhooks

GitHub Webhook接收器

yaml
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Receiver
metadata:
  name: github-receiver
  namespace: flux-system
spec:
  type: github
  events:
    - "ping"
    - "push"
  secretRef:
    name: github-webhook-token
  resources:
    - kind: GitRepository
      name: flux-system
---
apiVersion: v1
kind: Secret
metadata:
  name: github-webhook-token
  namespace: flux-system
type: Opaque
stringData:
  token: <webhook-secret>
yaml
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Receiver
metadata:
  name: github-receiver
  namespace: flux-system
spec:
  type: github
  events:
    - "ping"
    - "push"
  secretRef:
    name: github-webhook-token
  resources:
    - kind: GitRepository
      name: flux-system
---
apiVersion: v1
kind: Secret
metadata:
  name: github-webhook-token
  namespace: flux-system
type: Opaque
stringData:
  token: <webhook-secret>

Multi-Cluster Setup

多集群配置

Fleet Repository Structure

集群舰队仓库结构

text
fleet-infra/
├── clusters/
│   ├── production/
│   │   ├── flux-system/
│   │   └── cluster-config.yaml
│   ├── staging/
│   │   ├── flux-system/
│   │   └── cluster-config.yaml
│   └── development/
│       ├── flux-system/
│       └── cluster-config.yaml
├── infrastructure/
│   ├── base/
│   └── overlays/
│       ├── production/
│       ├── staging/
│       └── development/
└── apps/
    ├── base/
    └── overlays/
        ├── production/
        ├── staging/
        └── development/
text
fleet-infra/
├── clusters/
│   ├── production/
│   │   ├── flux-system/
│   │   └── cluster-config.yaml
│   ├── staging/
│   │   ├── flux-system/
│   │   └── cluster-config.yaml
│   └── development/
│       ├── flux-system/
│       └── cluster-config.yaml
├── infrastructure/
│   ├── base/
│   └── overlays/
│       ├── production/
│       ├── staging/
│       └── development/
└── apps/
    ├── base/
    └── overlays/
        ├── production/
        ├── staging/
        └── development/

Cluster-Specific Configuration

集群特定配置

Production cluster (
clusters/production/cluster-config.yaml
):
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: infrastructure
  namespace: flux-system
spec:
  interval: 10m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./infrastructure/overlays/production
  prune: true
  wait: true
  postBuild:
    substitute:
      cluster_name: production
      cluster_region: us-east-1
      replicas: "3"
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: apps
  namespace: flux-system
spec:
  interval: 10m0s
  dependsOn:
    - name: infrastructure
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/overlays/production
  prune: true
  postBuild:
    substitute:
      cluster_name: production
      domain: prod.example.com
生产集群(
clusters/production/cluster-config.yaml
):
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: infrastructure
  namespace: flux-system
spec:
  interval: 10m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./infrastructure/overlays/production
  prune: true
  wait: true
  postBuild:
    substitute:
      cluster_name: production
      cluster_region: us-east-1
      replicas: "3"
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: apps
  namespace: flux-system
spec:
  interval: 10m0s
  dependsOn:
    - name: infrastructure
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/overlays/production
  prune: true
  postBuild:
    substitute:
      cluster_name: production
      domain: prod.example.com

Multi-Cluster with Cluster API

基于Cluster API的多集群管理

Manage multiple clusters using Cluster API:
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: cluster-staging
  namespace: flux-system
spec:
  interval: 10m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./clusters/staging
  prune: true
  kubeConfig:
    secretRef:
      name: staging-kubeconfig
---
apiVersion: v1
kind: Secret
metadata:
  name: staging-kubeconfig
  namespace: flux-system
type: Opaque
data:
  value: <base64-encoded-kubeconfig>
使用Cluster API管理多个集群:
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: cluster-staging
  namespace: flux-system
spec:
  interval: 10m0s
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./clusters/staging
  prune: true
  kubeConfig:
    secretRef:
      name: staging-kubeconfig
---
apiVersion: v1
kind: Secret
metadata:
  name: staging-kubeconfig
  namespace: flux-system
type: Opaque
data:
  value: <base64-encoded-kubeconfig>

Dependency Management

依赖管理

Infrastructure Layer Dependencies

基础设施层依赖

yaml
undefined
yaml
undefined

Base infrastructure

基础基础设施

apiVersion: kustomize.toolkit.fluxcd.io/v1 kind: Kustomization metadata: name: crds namespace: flux-system spec: interval: 1h sourceRef: kind: GitRepository name: flux-system path: ./infrastructure/crds prune: false # Never prune CRDs automatically

apiVersion: kustomize.toolkit.fluxcd.io/v1 kind: Kustomization metadata: name: crds namespace: flux-system spec: interval: 1h sourceRef: kind: GitRepository name: flux-system path: ./infrastructure/crds prune: false # 绝不自动清理CRD

Depends on CRDs

依赖CRD

apiVersion: kustomize.toolkit.fluxcd.io/v1 kind: Kustomization metadata: name: cert-manager namespace: flux-system spec: interval: 10m dependsOn: - name: crds sourceRef: kind: GitRepository name: flux-system path: ./infrastructure/cert-manager healthChecks: - apiVersion: apps/v1 kind: Deployment name: cert-manager namespace: cert-manager

apiVersion: kustomize.toolkit.fluxcd.io/v1 kind: Kustomization metadata: name: cert-manager namespace: flux-system spec: interval: 10m dependsOn: - name: crds sourceRef: kind: GitRepository name: flux-system path: ./infrastructure/cert-manager healthChecks: - apiVersion: apps/v1 kind: Deployment name: cert-manager namespace: cert-manager

Depends on cert-manager

依赖cert-manager

apiVersion: kustomize.toolkit.fluxcd.io/v1 kind: Kustomization metadata: name: ingress-nginx namespace: flux-system spec: interval: 10m dependsOn: - name: cert-manager sourceRef: kind: GitRepository name: flux-system path: ./infrastructure/ingress-nginx
undefined
apiVersion: kustomize.toolkit.fluxcd.io/v1 kind: Kustomization metadata: name: ingress-nginx namespace: flux-system spec: interval: 10m dependsOn: - name: cert-manager sourceRef: kind: GitRepository name: flux-system path: ./infrastructure/ingress-nginx
undefined

Application Dependencies

应用层依赖

yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: database
  namespace: flux-system
spec:
  interval: 10m
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/database
  healthChecks:
    - apiVersion: apps/v1
      kind: StatefulSet
      name: postgresql
      namespace: database
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: backend
  namespace: flux-system
spec:
  interval: 5m
  dependsOn:
    - name: database
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/backend
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: frontend
  namespace: flux-system
spec:
  interval: 5m
  dependsOn:
    - name: backend
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/frontend
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: database
  namespace: flux-system
spec:
  interval: 10m
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/database
  healthChecks:
    - apiVersion: apps/v1
      kind: StatefulSet
      name: postgresql
      namespace: database
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: backend
  namespace: flux-system
spec:
  interval: 5m
  dependsOn:
    - name: database
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/backend
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: frontend
  namespace: flux-system
spec:
  interval: 5m
  dependsOn:
    - name: backend
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./apps/frontend

Best Practices

最佳实践

1. Resource Organization

1. 资源组织

  • Separate concerns: Keep infrastructure, apps, and cluster configs in separate directories
  • Use overlays: Leverage Kustomize overlays for environment-specific configurations
  • Namespace isolation: Use separate namespaces for different teams or applications
  • 分离关注点:将基础设施、应用和集群配置放在不同目录
  • 使用覆盖配置:利用Kustomize覆盖配置处理环境特定设置
  • 命名空间隔离:为不同团队或应用使用独立命名空间

2. Reconciliation Intervals

2. 协调间隔

  • Infrastructure: 1h (stable resources that change infrequently)
  • Applications: 10m (balance between responsiveness and API load)
  • Development: 1m-5m (faster feedback during active development)
  • Source repos: 1m-5m (detect changes quickly)
  • 基础设施:1小时(稳定资源,变更频率低)
  • 应用:10分钟(平衡响应速度与API负载)
  • 开发环境:1-5分钟(开发阶段快速反馈)
  • 源仓库:1-5分钟(快速检测变更)

3. Pruning Strategy

3. 清理策略

  • Enable pruning: Set
    prune: true
    for Kustomizations to clean up deleted resources
  • CRDs exception: Set
    prune: false
    for CRD Kustomizations to prevent accidental deletion
  • Test before production: Test pruning in non-production environments first
  • 启用清理:为Kustomization设置
    prune: true
    以清理已删除资源
  • CRD例外:为CRD的Kustomization设置
    prune: false
    防止意外删除
  • 生产前测试:先在非生产环境测试清理功能

4. Health Checks

4. 健康检查

Always define health checks for critical resources:
yaml
spec:
  healthChecks:
    - apiVersion: apps/v1
      kind: Deployment
      name: critical-app
      namespace: apps
    - apiVersion: v1
      kind: Service
      name: critical-service
      namespace: apps
始终为关键资源定义健康检查:
yaml
spec:
  healthChecks:
    - apiVersion: apps/v1
      kind: Deployment
      name: critical-app
      namespace: apps
    - apiVersion: v1
      kind: Service
      name: critical-service
      namespace: apps

5. Suspend Reconciliation

5. 暂停协调

Temporarily suspend reconciliation when needed:
bash
undefined
必要时临时暂停协调:
bash
undefined

Suspend a Kustomization

暂停Kustomization

flux suspend kustomization apps
flux suspend kustomization apps

Resume reconciliation

恢复协调

flux resume kustomization apps
undefined
flux resume kustomization apps
undefined

6. Force Reconciliation

6. 强制协调

Trigger immediate reconciliation:
bash
undefined
触发立即协调:
bash
undefined

Reconcile a specific Kustomization

协调特定Kustomization

flux reconcile kustomization apps --with-source
flux reconcile kustomization apps --with-source

Reconcile a HelmRelease

协调HelmRelease

flux reconcile helmrelease my-app -n apps
undefined
flux reconcile helmrelease my-app -n apps
undefined

7. Monitoring and Debugging

7. 监控与调试

bash
undefined
bash
undefined

Check Flux components status

检查Flux组件状态

flux check
flux check

Get all Flux resources

获取所有Flux资源

flux get all
flux get all

Get specific resource with detailed info

获取特定资源的详细信息

flux get kustomization infrastructure
flux get kustomization infrastructure

View logs

查看日志

flux logs --level=error --all-namespaces
flux logs --level=error --all-namespaces

Export current cluster state

导出当前集群状态

flux export source git flux-system flux export kustomization --all
undefined
flux export source git flux-system flux export kustomization --all
undefined

8. Version Control

8. 版本控制

  • Commit frequently: Small, atomic commits are easier to debug
  • Meaningful messages: Describe what and why, not just what
  • Branch protection: Require reviews for main/production branches
  • Tag releases: Use Git tags for application version tracking
  • 频繁提交:小而原子化的提交更易于调试
  • 有意义的提交信息:描述变更内容与原因
  • 分支保护:主/生产分支需要评审
  • 标记版本:使用Git标签跟踪应用版本

9. Security

9. 安全

  • Encrypt secrets: Always use SOPS or external secret managers
  • RBAC: Implement strict RBAC policies for multi-tenancy
  • Network policies: Define network policies for namespace isolation
  • Image scanning: Integrate container image scanning in CI/CD
  • Policy enforcement: Use tools like OPA Gatekeeper or Kyverno
  • 加密密钥:始终使用SOPS或外部密钥管理器
  • RBAC:为多租户实现严格的RBAC策略
  • 网络策略:定义命名空间隔离的网络策略
  • 镜像扫描:在CI/CD中集成容器镜像扫描
  • 策略强制执行:使用OPA Gatekeeper或Kyverno等工具

10. Disaster Recovery

10. 灾难恢复

bash
undefined
bash
undefined

Backup Flux configuration

备份Flux配置

flux export source git --all > sources.yaml flux export kustomization --all > kustomizations.yaml flux export helmrelease --all > helmreleases.yaml
flux export source git --all > sources.yaml flux export kustomization --all > kustomizations.yaml flux export helmrelease --all > helmreleases.yaml

Restore from backup

从备份恢复

kubectl apply -f sources.yaml kubectl apply -f kustomizations.yaml kubectl apply -f helmreleases.yaml
undefined
kubectl apply -f sources.yaml kubectl apply -f kustomizations.yaml kubectl apply -f helmreleases.yaml
undefined

Common Patterns

常见模式

Progressive Delivery with Flagger

基于Flagger的渐进式交付

yaml
apiVersion: helm.toolkit.fluxcd.io/v2beta2
kind: HelmRelease
metadata:
  name: flagger
  namespace: flagger-system
spec:
  interval: 10m
  chart:
    spec:
      chart: flagger
      version: "1.x"
      sourceRef:
        kind: HelmRepository
        name: flagger
        namespace: flux-system
---
apiVersion: flagger.app/v1beta1
kind: Canary
metadata:
  name: my-app
  namespace: apps
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: my-app
  service:
    port: 80
  analysis:
    interval: 1m
    threshold: 5
    maxWeight: 50
    stepWeight: 10
    metrics:
      - name: request-success-rate
        thresholdRange:
          min: 99
        interval: 1m
yaml
apiVersion: helm.toolkit.fluxcd.io/v2beta2
kind: HelmRelease
metadata:
  name: flagger
  namespace: flagger-system
spec:
  interval: 10m
  chart:
    spec:
      chart: flagger
      version: "1.x"
      sourceRef:
        kind: HelmRepository
        name: flagger
        namespace: flux-system
---
apiVersion: flagger.app/v1beta1
kind: Canary
metadata:
  name: my-app
  namespace: apps
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: my-app
  service:
    port: 80
  analysis:
    interval: 1m
    threshold: 5
    maxWeight: 50
    stepWeight: 10
    metrics:
      - name: request-success-rate
        thresholdRange:
          min: 99
        interval: 1m

External Secrets Operator Integration

与External Secrets Operator集成

yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: external-secrets
  namespace: flux-system
spec:
  interval: 10m
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./infrastructure/external-secrets
  prune: true
---
apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
  name: aws-secretsmanager
  namespace: apps
spec:
  provider:
    aws:
      service: SecretsManager
      region: us-east-1
      auth:
        jwt:
          serviceAccountRef:
            name: external-secrets-sa
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: app-secrets
  namespace: apps
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: aws-secretsmanager
    kind: SecretStore
  target:
    name: app-secrets
    creationPolicy: Owner
  data:
    - secretKey: db-password
      remoteRef:
        key: prod/app/database
        property: password
yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: external-secrets
  namespace: flux-system
spec:
  interval: 10m
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./infrastructure/external-secrets
  prune: true
---
apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
  name: aws-secretsmanager
  namespace: apps
spec:
  provider:
    aws:
      service: SecretsManager
      region: us-east-1
      auth:
        jwt:
          serviceAccountRef:
            name: external-secrets-sa
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: app-secrets
  namespace: apps
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: aws-secretsmanager
    kind: SecretStore
  target:
    name: app-secrets
    creationPolicy: Owner
  data:
    - secretKey: db-password
      remoteRef:
        key: prod/app/database
        property: password

Troubleshooting

故障排除

Common Issues

常见问题

Issue: Kustomization stuck in "Progressing" state
bash
undefined
问题:Kustomization卡在"Progressing"状态
bash
undefined

Check Kustomization status

检查Kustomization状态

flux get kustomization infrastructure
flux get kustomization infrastructure

View detailed events

查看详细事件

kubectl describe kustomization infrastructure -n flux-system
kubectl describe kustomization infrastructure -n flux-system

Check logs

检查日志

kubectl logs -n flux-system deploy/kustomize-controller

**Issue**: HelmRelease installation failed

```bash
kubectl logs -n flux-system deploy/kustomize-controller

**问题**:HelmRelease安装失败

```bash

Get HelmRelease status

获取HelmRelease状态

flux get helmrelease my-app -n apps
flux get helmrelease my-app -n apps

View Helm release history

查看Helm发布历史

helm history my-app -n apps
helm history my-app -n apps

Check Helm controller logs

检查Helm控制器日志

kubectl logs -n flux-system deploy/helm-controller

**Issue**: Image automation not updating manifests

```bash
kubectl logs -n flux-system deploy/helm-controller

**问题**:镜像自动化未更新清单

```bash

Check ImageRepository status

检查ImageRepository状态

flux get image repository my-app
flux get image repository my-app

Check ImagePolicy status

检查ImagePolicy状态

flux get image policy my-app
flux get image policy my-app

View image automation logs

查看镜像自动化日志

kubectl logs -n flux-system deploy/image-reflector-controller kubectl logs -n flux-system deploy/image-automation-controller

**Issue**: Source reconciliation failures

```bash
kubectl logs -n flux-system deploy/image-reflector-controller kubectl logs -n flux-system deploy/image-automation-controller

**问题**:源协调失败

```bash

Check GitRepository status

检查GitRepository状态

flux get source git flux-system
flux get source git flux-system

View source controller logs

查看源控制器日志

kubectl logs -n flux-system deploy/source-controller
kubectl logs -n flux-system deploy/source-controller

Reconcile manually

手动协调

flux reconcile source git flux-system
undefined
flux reconcile source git flux-system
undefined

Debug Mode

调试模式

Enable debug logging:
bash
undefined
启用调试日志:
bash
undefined

Patch controller for debug logging

补丁控制器启用调试日志

kubectl patch deployment kustomize-controller
-n flux-system
--type='json'
-p='[{"op": "add", "path": "/spec/template/spec/containers/0/args/-", "value": "--log-level=debug"}]'
undefined
kubectl patch deployment kustomize-controller
-n flux-system
--type='json'
-p='[{"op": "add", "path": "/spec/template/spec/containers/0/args/-", "value": "--log-level=debug"}]'
undefined

Performance Optimization

性能优化

Reduce API Server Load

降低API服务器负载

yaml
spec:
  interval: 1h # Increase for stable resources
  retryInterval: 5m # Retry less frequently on errors
yaml
spec:
  interval: 1h # 针对稳定资源增加间隔
  retryInterval: 5m # 错误时减少重试频率

Optimize Git Operations

优化Git操作

yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
  name: flux-system
  namespace: flux-system
spec:
  interval: 5m
  ref:
    branch: main
  url: https://github.com/org/repo
  ignore: |
    # Reduce clone size
    *.md
    docs/
    examples/
yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
  name: flux-system
  namespace: flux-system
spec:
  interval: 5m
  ref:
    branch: main
  url: https://github.com/org/repo
  ignore: |
    # 减少克隆大小
    *.md
    docs/
    examples/

Parallel Reconciliation

并行协调

Enable parallel reconciliation in controllers:
bash
flux install \
  --components-extra=image-reflector-controller,image-automation-controller \
  --reconcile-interval=1h \
  --kustomize-concurrency=10 \
  --helm-concurrency=10
在控制器中启用并行协调:
bash
flux install \
  --components-extra=image-reflector-controller,image-automation-controller \
  --reconcile-interval=1h \
  --kustomize-concurrency=10 \
  --helm-concurrency=10

Summary

总结

Flux CD provides a powerful, declarative approach to managing Kubernetes deployments through GitOps. Key takeaways:
  1. Bootstrap once: Use
    flux bootstrap
    to set up Flux in your cluster
  2. Organize thoughtfully: Structure your repository for clarity and maintainability
  3. Layer dependencies: Build infrastructure before applications
  4. Secure secrets: Use SOPS or external secret managers
  5. Monitor actively: Set up alerts and regularly check Flux status
  6. Automate carefully: Use image automation for non-production environments first
  7. Multi-tenancy: Leverage namespaces and RBAC for team isolation
  8. Test changes: Validate in lower environments before production
Flux CD提供了强大的声明式方法,通过GitOps管理Kubernetes部署。核心要点:
  1. 一次引导:使用
    flux bootstrap
    在集群中设置Flux
  2. 合理组织:清晰结构化仓库以提升可维护性
  3. 分层依赖:先构建基础设施再部署应用
  4. 安全密钥:使用SOPS或外部密钥管理器
  5. 主动监控:设置告警并定期检查Flux状态
  6. 谨慎自动化:先在非生产环境启用镜像自动化
  7. 多租户:利用命名空间与RBAC实现团队隔离
  8. 测试变更:在低环境验证后再部署到生产

Key Decision Points

关键决策点

Choose GitRepository vs HelmRepository:
  • GitRepository: For custom manifests, Kustomize overlays, or Helm charts in Git
  • HelmRepository: For public/private Helm chart repositories
Choose Kustomization vs HelmRelease:
  • Kustomization: For raw manifests, ConfigMaps, Secrets, Kustomize overlays
  • HelmRelease: For packaged Helm charts with values customization
Image Automation Strategy:
  • Direct commit: Development/staging environments with rapid iteration
  • PR workflow: Production environments requiring review and approval
  • Disabled: Mission-critical production with manual deployment gates
Multi-Tenancy Approach:
  • Namespace isolation: Teams share cluster, separate by namespace
  • Cluster isolation: Each team gets dedicated cluster(s)
  • Hybrid: Core teams share, external teams isolated
Secret Management:
  • SOPS: Git-native, age/pgp encryption, good for small teams
  • External Secrets Operator: Integrate AWS Secrets Manager, Vault, GCP Secret Manager
  • Sealed Secrets: Kubernetes-native, one-way encryption
By following these patterns and practices, you can build reliable, automated deployment pipelines that scale with your organization.
选择GitRepository还是HelmRepository:
  • GitRepository:用于自定义清单、Kustomize覆盖配置或Git中的Helm Chart
  • HelmRepository:用于公共/私有Helm Chart仓库
选择Kustomization还是HelmRelease:
  • Kustomization:用于原始清单、ConfigMap、Secret、Kustomize覆盖配置
  • HelmRelease:用于带值自定义的打包Helm Chart
镜像自动化策略:
  • 直接提交:开发/预发布环境,快速迭代
  • PR工作流:生产环境,需要评审与审批
  • 禁用:关键生产环境,手动部署
多租户方案:
  • 命名空间隔离:团队共享集群,按命名空间分离
  • 集群隔离:每个团队拥有专用集群
  • 混合模式:核心团队共享,外部团队隔离
密钥管理:
  • SOPS:原生Git支持,age/pgp加密,适合小型团队
  • External Secrets Operator:集成AWS Secrets Manager、Vault、GCP Secret Manager
  • Sealed Secrets:Kubernetes原生,单向加密
遵循这些模式与实践,你可以构建可靠、自动化的部署流水线,随组织规模扩展。