FluxCD
FluxCD 完全技術ガイド — GitOps ツールキットの全容
1. はじめに
1.1 GitOps とは何か
GitOps は、Kubernetes をはじめとするクラウドネイティブインフラストラクチャの運用を、Git リポジトリを「Single Source of Truth(唯一の信頼できる情報源)」として管理する運用モデルである。2017 年に Weaveworks 社が提唱したこの概念は、以下の 4 つの原則に基づいている。
- 宣言的記述(Declarative): システムの望ましい状態を宣言的に記述する
- バージョン管理と不変性(Versioned and Immutable): 望ましい状態は Git に保存され、バージョン管理される
- 自動プル(Pulled Automatically): 承認された変更は自動的にシステムに適用される
- 継続的リコンシリエーション(Continuously Reconciled): エージェントが望ましい状態と実際の状態を継続的に比較し、差分を修正する
従来の CI/CD パイプラインが「プッシュ型」でデプロイを行うのに対し、GitOps は「プル型」のアプローチを採用する。これにより、クラスター側から Git リポジトリの状態を監視し、差分があれば自動的に収束させるという、より安全で監査可能な運用が実現される。
1.2 FluxCD の概要
FluxCD(以下 Flux)は、CNCF(Cloud Native Computing Foundation)の Graduated プロジェクトであり、Kubernetes 上で GitOps を実現するためのオープンソースツールキットである。Weaveworks 社によって開発が開始され、現在はコミュニティ主導で活発に開発が続けられている。
Flux は単一のモノリシックなツールではなく、複数の専門的なコントローラーから構成されるモジュラーアーキテクチャを採用している。各コントローラーは Kubernetes のカスタムリソース定義(CRD)を通じて宣言的に設定され、それぞれが独立して動作しながらも協調してGitOpsワークフローを実現する。
1.3 Flux の主な特徴
| 特徴 | 説明 |
|---|---|
| マルチテナンシー | 名前空間レベルでの分離により、複数チームが安全に共存可能 |
| マルチクラスター | 単一の管理クラスターから複数クラスターを GitOps で管理 |
| Helm サポート | Helm チャートのライフサイクルを宣言的に管理 |
| Kustomize サポート | Kustomize によるマニフェストのカスタマイズをネイティブサポート |
| 通知とアラート | Slack、Teams、PagerDuty 等への通知統合 |
| イメージ自動更新 | コンテナレジストリの新しいイメージタグを検知して Git を自動更新 |
| OCI サポート | OCI アーティファクトとしてのマニフェスト配布に対応 |
| SOPS / Age 暗号化 | シークレットの暗号化管理をネイティブサポート |
1.4 Flux v1 から Flux v2 への進化
Flux v1 は単一のデーモンとして動作していたが、Flux v2(現在の Flux)では GitOps Toolkit と呼ばれるモジュラーアーキテクチャに完全に再設計された。この進化により以下の改善が実現された。
- 拡張性: 各コントローラーが独立した CRD を持ち、個別に拡張可能
- 組み合わせ自由度: 必要なコントローラーだけを選択してデプロイ可能
- Kubernetes ネイティブ: すべてが Kubernetes API を通じて操作される
- テスト容易性: 各コンポーネントを個別にテスト可能
2. アーキテクチャ全体像
2.1 コンポーネント構成
Flux は以下の主要コントローラーで構成される。
┌─────────────────────────────────────────────────────────────────┐
│ Flux System Namespace │
│ (通常: flux-system) │
│ │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ Source │ │ Kustomize │ │
│ │ Controller │ │ Controller │ │
│ │ │ │ │ │
│ │ - GitRepository │ │ - Kustomization │ │
│ │ - OCIRepository │ │ │ │
│ │ - Bucket │ └──────────────────┘ │
│ │ - HelmRepository │ │
│ │ - HelmChart │ ┌──────────────────┐ │
│ └──────────────────┘ │ Helm │ │
│ │ Controller │ │
│ ┌──────────────────┐ │ │ │
│ │ Notification │ │ - HelmRelease │ │
│ │ Controller │ └──────────────────┘ │
│ │ │ │
│ │ - Provider │ ┌──────────────────┐ │
│ │ - Alert │ │ Image │ │
│ │ - Receiver │ │ Automation │ │
│ └──────────────────┘ │ Controllers │ │
│ │ │ │
│ │ - ImageRepository│ │
│ │ - ImagePolicy │ │
│ │ - ImageUpdate │ │
│ │ Automation │ │
│ └──────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
2.2 各コントローラーの役割
Source Controller
ソースコントローラーは、外部ソース(Git リポジトリ、Helm リポジトリ、S3 互換バケット、OCI レジストリ)からアーティファクトを取得し、クラスター内部で利用可能にする役割を担う。取得されたアーティファクトは tar.gz 形式でクラスター内のストレージサーバーにキャッシュされ、他のコントローラーに提供される。
Kustomize Controller
Kustomize コントローラーは、Source Controller が取得したアーティファクトに含まれる Kubernetes マニフェストを、Kustomize を用いてビルドし、クラスターに適用する。変数の置換、パッチの適用、リソースの生成を宣言的に行う。
Helm Controller
Helm コントローラーは、Helm チャートのインストール、アップグレード、ロールバックを宣言的に管理する。HelmRelease カスタムリソースを通じて、Helm のリリースライフサイクル全体を制御する。
Notification Controller
通知コントローラーは、Flux の各種イベントを外部サービス(Slack、Microsoft Teams、PagerDuty、GitHub など)に通知する。また、外部からの Webhook を受信してリコンシリエーションをトリガーする機能も提供する。
Image Reflector Controller / Image Automation Controller
これらのコントローラーは連携して、コンテナレジストリの新しいイメージタグを検知し、Git リポジトリ内のマニフェストを自動的に更新する。CI/CD パイプラインの一部として、イメージのビルド後に自動的にデプロイメントを更新するワークフローを実現する。
2.3 リコンシリエーションループ
Flux の中核となるのは、リコンシリエーション(調停)ループである。これは Kubernetes のコントローラーパターンに基づいており、以下のサイクルを繰り返す。
┌──────────────┐
│ Desired State│
│ (Git Repo) │
└──────┬───────┘
│
▼
┌──────────────┐
│ Observe │ ← Source Controller がソースを取得
│ (Fetch) │
└──────┬───────┘
│
▼
┌──────────────┐
│ Diff │ ← 望ましい状態と実際の状態を比較
│ (Compare) │
└──────┬───────┘
│
▼
┌──────────────┐
│ Act │ ← 差分があれば修正を適用
│ (Apply) │
└──────┬───────┘
│
▼
┌──────────────┐
│ Actual State │
│ (Cluster) │
└──────────────┘
各リコンシリエーションの間隔は、カスタムリソースの spec.interval フィールドで設定する。例えば interval: 5m と設定すれば、5 分ごとにソースの変更を確認し、必要に応じてクラスターの状態を修正する。
2.4 CRD ベースの設計思想
Flux のすべての設定は Kubernetes CRD として表現される。これにより以下の利点が得られる。
- kubectl との統合:
kubectl get gitrepositoriesのように標準ツールで管理可能 - RBAC との統合: Kubernetes の RBAC でアクセス制御が可能
- 監査ログ: Kubernetes の監査ログにすべての操作が記録される
- GitOps の自己参照: Flux 自身の設定も GitOps で管理可能(ブートストラップ)
3. インストールとブートストラップ
3.1 前提条件
Flux をインストールするには以下が必要である。
- Kubernetes クラスター(v1.28 以上推奨)
- kubectl(クラスターに接続済み)
- Flux CLI(
fluxコマンド)
3.2 Flux CLI のインストール
# macOS (Homebrew)
brew install fluxcd/tap/flux
# Linux
curl -s https://fluxcd.io/install.sh | sudo bash
# バージョン確認
flux --version
# flux version 2.4.x
# クラスターの前提条件チェック
flux check --pre
# ► checking prerequisites
# ✔ Kubernetes 1.30.2 >=1.28.0-0
# ✔ prerequisites checks passed
3.3 ブートストラップ
ブートストラップは Flux をクラスターにインストールすると同時に、Flux 自身の設定を Git リポジトリで管理するための初期設定を行うプロセスである。これにより Flux は自分自身を GitOps で管理できるようになる。
GitHub を使用したブートストラップ
# GitHub Personal Access Token を環境変数に設定
export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# ブートストラップの実行
flux bootstrap github \
--owner=my-org \
--repository=fleet-infra \
--branch=main \
--path=clusters/production \
--personal=false \
--token-auth
このコマンドは以下の処理を自動的に行う。
- 指定された GitHub リポジトリが存在しない場合は作成
- Flux のコンポーネントマニフェストを
clusters/production/flux-system/に生成 - マニフェストをリポジトリにコミット・プッシュ
- クラスターに Flux コンポーネントをデプロイ
- Flux がリポジトリを監視するための GitRepository と Kustomization リソースを作成
GitLab を使用したブートストラップ
export GITLAB_TOKEN=glpat-xxxxxxxxxxxxxxxxxxxx
flux bootstrap gitlab \
--owner=my-group \
--repository=fleet-infra \
--branch=main \
--path=clusters/production \
--token-auth
汎用 Git リポジトリを使用したブートストラップ
flux bootstrap git \
--url=ssh://git@git.example.com/fleet-infra.git \
--branch=main \
--path=clusters/production \
--private-key-file=/path/to/private-key
3.4 ブートストラップ後のリポジトリ構造
fleet-infra/
├── clusters/
│ └── production/
│ └── flux-system/
│ ├── gotk-components.yaml # Flux コンポーネントのマニフェスト
│ ├── gotk-sync.yaml # 自己参照用の GitRepository + Kustomization
│ └── kustomization.yaml # Kustomize のエントリポイント
gotk-sync.yaml の内容は以下のようになる。
# GitRepository: Flux がこのリポジトリを監視する設定
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
name: flux-system
namespace: flux-system
spec:
interval: 1m0s
ref:
branch: main
secretRef:
name: flux-system # Git 認証情報
url: ssh://git@github.com/my-org/fleet-infra.git
---
# Kustomization: リポジトリ内のマニフェストをクラスターに適用する設定
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: flux-system
namespace: flux-system
spec:
interval: 10m0s
path: ./clusters/production
prune: true
sourceRef:
kind: GitRepository
name: flux-system
3.5 Flux のカスタムインストール
ブートストラップ時にコンポーネントを選択してインストールすることも可能である。
# Image Automation を含めたインストール
flux bootstrap github \
--components-extra=image-reflector-controller,image-automation-controller \
--owner=my-org \
--repository=fleet-infra \
--branch=main \
--path=clusters/production
# 特定のコンポーネントのみをインストール(マニフェスト生成)
flux install \
--components=source-controller,kustomize-controller \
--export > gotk-components.yaml
3.6 インストールの検証
# Flux コンポーネントの状態確認
flux check
# 出力例:
# ► checking prerequisites
# ✔ Kubernetes 1.30.2 >=1.28.0-0
# ► checking controllers
# ✔ helm-controller: deployment ready
# ✔ kustomize-controller: deployment ready
# ✔ notification-controller: deployment ready
# ✔ source-controller: deployment ready
# ✔ all checks passed
# 全リソースの状態確認
flux get all
4. Source Controller 詳解
4.1 GitRepository
GitRepository は最も基本的なソースリソースであり、Git リポジトリからマニフェストを取得するために使用する。
基本設定
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
name: webapp
namespace: flux-system
spec:
interval: 5m
url: https://github.com/my-org/webapp-deploy.git
ref:
branch: main
secretRef:
name: webapp-git-auth
ブランチ、タグ、コミットの指定
# 特定のブランチ
spec:
ref:
branch: production
# 特定のタグ
spec:
ref:
tag: v1.2.3
# セマンティックバージョニング範囲
spec:
ref:
semver: ">=1.0.0 <2.0.0"
# 特定のコミット
spec:
ref:
commit: 3f8a0b12e5d6c7a8b9e0f1a2b3c4d5e6f7a8b9c0
パスフィルタリング
大規模なモノレポでは、特定のディレクトリのみを監視することで不要なリコンシリエーションを回避できる。
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
name: monorepo
namespace: flux-system
spec:
interval: 5m
url: https://github.com/my-org/monorepo.git
ref:
branch: main
include:
- fromPath: deploy/production
toPath: .
Git 認証設定
SSH 鍵による認証:
# SSH 鍵の Secret を作成
flux create secret git webapp-git-auth \
--url=ssh://git@github.com/my-org/webapp-deploy.git \
--private-key-file=./identity
これにより以下の Secret が作成される:
apiVersion: v1
kind: Secret
metadata:
name: webapp-git-auth
namespace: flux-system
type: Opaque
data:
identity: <base64-encoded-private-key>
identity.pub: <base64-encoded-public-key>
known_hosts: <base64-encoded-known-hosts>
HTTPS トークンによる認証:
apiVersion: v1
kind: Secret
metadata:
name: webapp-git-auth
namespace: flux-system
type: Opaque
stringData:
username: git
password: ghp_xxxxxxxxxxxxxxxxxxxx
GitRepository のステータス確認
# CLI でのステータス確認
flux get sources git
# 出力例:
# NAME REVISION SUSPENDED READY MESSAGE
# webapp main@sha1:a1b2c3d False True stored artifact for revision 'main@sha1:a1b2c3d'
# kubectl での詳細確認
kubectl -n flux-system get gitrepository webapp -o yaml
4.2 HelmRepository
HelmRepository は Helm チャートリポジトリを定義する。HTTP/HTTPS ベースの従来型リポジトリと OCI ベースのリポジトリの両方をサポートする。
HTTP/HTTPS リポジトリ
apiVersion: source.toolkit.fluxcd.io/v1
kind: HelmRepository
metadata:
name: bitnami
namespace: flux-system
spec:
interval: 30m
url: https://charts.bitnami.com/bitnami
OCI リポジトリ
apiVersion: source.toolkit.fluxcd.io/v1
kind: HelmRepository
metadata:
name: podinfo
namespace: flux-system
spec:
type: oci
interval: 5m
url: oci://ghcr.io/stefanprodan/charts
認証付きリポジトリ
apiVersion: source.toolkit.fluxcd.io/v1
kind: HelmRepository
metadata:
name: private-charts
namespace: flux-system
spec:
interval: 10m
url: https://charts.example.com
secretRef:
name: helm-repo-creds
---
apiVersion: v1
kind: Secret
metadata:
name: helm-repo-creds
namespace: flux-system
type: Opaque
stringData:
username: admin
password: s3cur3p@ss
4.3 HelmChart
HelmChart は HelmRepository からの特定チャートの取得を定義する。通常は HelmRelease から暗黙的に作成されるが、明示的に定義することも可能である。
apiVersion: source.toolkit.fluxcd.io/v1
kind: HelmChart
metadata:
name: nginx
namespace: flux-system
spec:
chart: nginx
version: ">=15.0.0 <16.0.0"
sourceRef:
kind: HelmRepository
name: bitnami
interval: 10m
reconcileStrategy: ChartVersion # Revision or ChartVersion
4.4 OCIRepository
OCIRepository は OCI コンテナレジストリからアーティファクトを取得する。Helm チャートだけでなく、Kustomize オーバーレイや平文マニフェストも OCI アーティファクトとして配布できる。
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: OCIRepository
metadata:
name: app-manifests
namespace: flux-system
spec:
interval: 5m
url: oci://ghcr.io/my-org/app-manifests
ref:
tag: latest
provider: generic # generic, aws, azure, gcp
OCI アーティファクトのプッシュ:
# Flux CLI を使って OCI アーティファクトをプッシュ
flux push artifact oci://ghcr.io/my-org/app-manifests:v1.0.0 \
--path=./manifests \
--source="$(git config --get remote.origin.url)" \
--revision="$(git branch --show-current)@sha1:$(git rev-parse HEAD)"
4.5 Bucket
Bucket は S3 互換のオブジェクトストレージからアーティファクトを取得する。AWS S3、Google Cloud Storage、Azure Blob Storage、MinIO などに対応する。
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: Bucket
metadata:
name: config-bucket
namespace: flux-system
spec:
interval: 5m
provider: aws # generic, aws, azure, gcp
bucketName: my-config-bucket
endpoint: s3.amazonaws.com
region: us-east-1
secretRef:
name: bucket-creds
5. Kustomize Controller 詳解
5.1 Kustomization リソース
Kustomization リソースは、Source Controller が取得したアーティファクトから Kubernetes マニフェストをビルドし、クラスターに適用する方法を定義する。Flux の Kustomization は Kubernetes ネイティブの Kustomize(kustomize.config.k8s.io)とは異なる CRD であることに注意が必要である。
基本設定
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: webapp
namespace: flux-system
spec:
interval: 10m
targetNamespace: webapp-production
sourceRef:
kind: GitRepository
name: webapp
path: ./deploy/production
prune: true
timeout: 3m
各フィールドの意味:
| フィールド | 説明 |
|---|---|
interval | リコンシリエーションの間隔 |
targetNamespace | リソースが適用されるデフォルトの名前空間 |
sourceRef | 参照するソースリソース |
path | ソース内のマニフェストのパス |
prune | Git から削除されたリソースをクラスターからも削除するか |
timeout | 適用のタイムアウト |
5.2 依存関係の定義
Kustomization リソース間に依存関係を定義して、適用順序を制御できる。
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: infrastructure
namespace: flux-system
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: fleet-infra
path: ./infrastructure
prune: true
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: apps
namespace: flux-system
spec:
interval: 10m
dependsOn:
- name: infrastructure # infrastructure が Ready になるまで待機
sourceRef:
kind: GitRepository
name: fleet-infra
path: ./apps/production
prune: true
この設定により、インフラストラクチャコンポーネント(Ingress Controller、Cert-Manager など)が先にデプロイされ、その後にアプリケーションがデプロイされる。
5.3 ヘルスチェック
Kustomization は、適用したリソースのヘルスチェックを行い、すべてが正常にデプロイされたことを確認できる。
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: webapp
namespace: flux-system
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: webapp
path: ./deploy
prune: true
wait: true # すべてのリソースが Ready になるまで待機
timeout: 5m # ヘルスチェックのタイムアウト
healthChecks: # 明示的にヘルスチェック対象を指定する場合
- apiVersion: apps/v1
kind: Deployment
name: webapp
namespace: webapp-production
- apiVersion: v1
kind: Service
name: webapp
namespace: webapp-production
5.4 変数の置換(Post Build Variable Substitution)
Kustomize Controller は、マニフェストのビルド後に変数の置換を行う機能を提供する。これにより、環境固有の値を動的に注入できる。
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: webapp
namespace: flux-system
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: webapp
path: ./deploy
prune: true
postBuild:
substitute:
CLUSTER_NAME: production
DOMAIN: app.example.com
REPLICAS: "3"
substituteFrom:
- kind: ConfigMap
name: cluster-settings
- kind: Secret
name: cluster-secrets
マニフェスト内では ${VARIABLE_NAME} の形式で変数を参照する:
# deploy/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp
spec:
replicas: ${REPLICAS}
template:
spec:
containers:
- name: webapp
env:
- name: CLUSTER_NAME
value: ${CLUSTER_NAME}
- name: APP_DOMAIN
value: ${DOMAIN}
5.5 パッチの適用
Kustomization リソース自体にインラインでパッチを定義できる。
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: webapp
namespace: flux-system
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: webapp
path: ./deploy
prune: true
patches:
# Strategic Merge Patch
- patch: |
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp
spec:
replicas: 5
target:
kind: Deployment
name: webapp
# JSON Patch
- patch: |
- op: add
path: /metadata/labels/environment
value: production
target:
kind: Deployment
labelSelector: "app.kubernetes.io/part-of=webapp"
5.6 デクリプション(暗号化シークレットの復号)
Flux は Mozilla SOPS および Age による暗号化シークレットの復号をネイティブサポートする。
SOPS + Age の設定
# Age の鍵ペアを生成
age-keygen -o age.agekey
# Public key: age1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# Age の秘密鍵を Kubernetes Secret として保存
cat age.agekey |
kubectl create secret generic sops-age \
--namespace=flux-system \
--from-file=age.agekey=/dev/stdin
SOPS の設定ファイル(.sops.yaml):
creation_rules:
- path_regex: .*.yaml
encrypted_regex: ^(data|stringData)$
age: age1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
シークレットの暗号化:
sops --encrypt --in-place secret.yaml
暗号化されたシークレットの例:
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque
stringData:
username: ENC[AES256_GCM,data:xxxxx,iv:xxxxx,tag:xxxxx,type:str]
password: ENC[AES256_GCM,data:yyyyy,iv:yyyyy,tag:yyyyy,type:str]
sops:
age:
- recipient: age1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
enc: |
-----BEGIN AGE ENCRYPTED FILE-----
...
-----END AGE ENCRYPTED FILE-----
lastmodified: "2025-01-15T10:30:00Z"
version: 3.8.1
Kustomization での復号設定:
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: webapp
namespace: flux-system
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: webapp
path: ./deploy
prune: true
decryption:
provider: sops
secretRef:
name: sops-age # Age 秘密鍵を含む Secret
5.7 サービスアカウントの偽装(Impersonation)
マルチテナント環境では、Kustomization がリソースを適用する際に使用するサービスアカウントを制限できる。
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: tenant-app
namespace: flux-system
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: tenant-repo
path: ./deploy
prune: true
serviceAccountName: tenant-deployer
targetNamespace: tenant-namespace
対応するサービスアカウントと RBAC:
apiVersion: v1
kind: ServiceAccount
metadata:
name: tenant-deployer
namespace: tenant-namespace
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: tenant-deployer
namespace: tenant-namespace
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin # テナントの名前空間内のみ
subjects:
- kind: ServiceAccount
name: tenant-deployer
namespace: tenant-namespace
6. Helm Controller 詳解
6.1 HelmRelease リソース
HelmRelease は Helm チャートのインストールとライフサイクル管理を宣言的に行うためのリソースである。
基本設定
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: nginx
namespace: flux-system
spec:
interval: 30m
chart:
spec:
chart: nginx
version: ">=15.0.0 <16.0.0"
sourceRef:
kind: HelmRepository
name: bitnami
interval: 10m
targetNamespace: web
install:
createNamespace: true
remediation:
retries: 3
upgrade:
remediation:
retries: 3
remediateLastFailure: true
values:
replicaCount: 3
service:
type: ClusterIP
ingress:
enabled: true
hostname: nginx.example.com
tls: true
6.2 Values のソース
HelmRelease の values は複数のソースから取得して統合できる。
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: webapp
namespace: flux-system
spec:
interval: 30m
chart:
spec:
chart: webapp
version: "1.x"
sourceRef:
kind: HelmRepository
name: internal
# values ファイルから読み込み(GitRepository 内のファイル)
valuesFrom:
- kind: ConfigMap
name: webapp-default-values
valuesKey: values.yaml
- kind: Secret
name: webapp-secret-values
valuesKey: secret-values.yaml
- kind: ConfigMap
name: webapp-env-values
valuesKey: production.yaml
optional: true # 存在しなくてもエラーにならない
# インライン values(valuesFrom より優先される)
values:
replicaCount: 5
image:
tag: v2.1.0
values の優先順位(後のものが優先):
- チャートのデフォルト values
valuesFromのリスト順values(インライン)
6.3 リリースのリメディエーション(修復)
HelmRelease はインストールやアップグレードの失敗時の自動修復機能を提供する。
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: webapp
namespace: flux-system
spec:
interval: 30m
chart:
spec:
chart: webapp
version: "1.x"
sourceRef:
kind: HelmRepository
name: internal
# インストール時のリメディエーション
install:
crds: CreateReplace # CRD の処理方法
remediation:
retries: 3 # リトライ回数
# アップグレード時のリメディエーション
upgrade:
crds: CreateReplace
cleanupOnFail: true # 失敗時にリソースをクリーンアップ
remediation:
retries: 3
remediateLastFailure: true # 最後のリトライ失敗時にロールバック
strategy: rollback # rollback or uninstall
# アンインストール時の設定
uninstall:
keepHistory: false
timeout: 5m
# テスト設定
test:
enable: true
ignoreFailures: false
6.4 依存関係
HelmRelease 間の依存関係も定義可能である。
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: database
namespace: flux-system
spec:
interval: 30m
chart:
spec:
chart: postgresql
sourceRef:
kind: HelmRepository
name: bitnami
---
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: webapp
namespace: flux-system
spec:
interval: 30m
dependsOn:
- name: database # database の HelmRelease が Ready になるまで待機
chart:
spec:
chart: webapp
sourceRef:
kind: HelmRepository
name: internal
6.5 Git リポジトリからの Helm チャート
HelmRepository を使わずに、Git リポジトリから直接 Helm チャートを取得することも可能である。
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
name: app-charts
namespace: flux-system
spec:
interval: 5m
url: https://github.com/my-org/helm-charts.git
ref:
branch: main
---
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: webapp
namespace: flux-system
spec:
interval: 30m
chart:
spec:
chart: ./charts/webapp # Git リポジトリ内のパス
sourceRef:
kind: GitRepository
name: app-charts
values:
replicaCount: 3
6.6 Drift Detection(ドリフト検出)
Helm Controller は、クラスター上のリソースが手動で変更された場合(ドリフト)を検出し、自動的に修正する機能を持つ。
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: webapp
namespace: flux-system
spec:
interval: 30m
chart:
spec:
chart: webapp
sourceRef:
kind: HelmRepository
name: internal
# ドリフト検出を有効化
driftDetection:
mode: enabled # enabled, warn, or disabled
ignore:
# 特定のフィールドの変更を無視
- paths: ["/spec/replicas"]
target:
kind: Deployment
mode の設定値:
disabled: ドリフト検出を無効化(デフォルト)warn: ドリフトを検出してイベントを発行するが修正しないenabled: ドリフトを検出して自動的に修正する
7. Notification Controller 詳解
7.1 アーキテクチャ
Notification Controller は双方向の通知機能を提供する。
- アウトバウンド(Alert + Provider): Flux のイベントを外部サービスに送信
- インバウンド(Receiver): 外部からの Webhook を受信してリコンシリエーションをトリガー
┌─────────────┐
Git Push ────→ │ Receiver │ ────→ リコンシリエーション
CI Webhook │ │ トリガー
└─────────────┘
┌─────────────┐ ┌─────────────┐
Flux Events ──→│ Alert │ ───→ │ Provider │ ──→ Slack/Teams/etc.
└─────────────┘ └─────────────┘
7.2 Provider(通知プロバイダー)
Provider は通知の送信先サービスを定義する。
Slack
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Provider
metadata:
name: slack
namespace: flux-system
spec:
type: slack
channel: flux-notifications
address: https://hooks.slack.com/services/T00/B00/XXXXXXX
secretRef:
name: slack-webhook-url
---
apiVersion: v1
kind: Secret
metadata:
name: slack-webhook-url
namespace: flux-system
type: Opaque
stringData:
address: https://hooks.slack.com/services/T00/B00/XXXXXXX
Microsoft Teams
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Provider
metadata:
name: teams
namespace: flux-system
spec:
type: msteams
address: https://outlook.office.com/webhook/xxxxx
PagerDuty
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Provider
metadata:
name: pagerduty
namespace: flux-system
spec:
type: pagerduty
channel: flux-critical
secretRef:
name: pagerduty-routing-key
---
apiVersion: v1
kind: Secret
metadata:
name: pagerduty-routing-key
namespace: flux-system
type: Opaque
stringData:
token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
GitHub(コミットステータスの更新)
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Provider
metadata:
name: github-status
namespace: flux-system
spec:
type: github
address: https://github.com/my-org/webapp-deploy
secretRef:
name: github-token
サポートされるプロバイダー一覧
| プロバイダー | type 値 |
|---|---|
| Slack | slack |
| Microsoft Teams | msteams |
| Discord | discord |
| PagerDuty | pagerduty |
| GitHub | github |
| GitLab | gitlab |
| Bitbucket | bitbucket |
| Azure DevOps | azuredevops |
| Google Chat | googlechat |
| Grafana | grafana |
| Matrix | matrix |
| Opsgenie | opsgenie |
| Telegram | telegram |
| DataDog | datadog |
| Generic Webhook | generic |
| Generic HMAC | generic-hmac |
7.3 Alert(アラートルール)
Alert はどのイベントをどのプロバイダーに送信するかを定義する。
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Alert
metadata:
name: webapp-alerts
namespace: flux-system
spec:
providerRef:
name: slack
eventSeverity: info # info or error
eventSources:
- kind: GitRepository
name: webapp
- kind: Kustomization
name: webapp
- kind: HelmRelease
name: webapp
namespace: flux-system
exclusionList:
- ".*upgrade.*has.*started" # 正規表現で特定のイベントを除外
summary: "Production cluster alert"
重大なエラーのみを PagerDuty に送信する設定:
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Alert
metadata:
name: critical-alerts
namespace: flux-system
spec:
providerRef:
name: pagerduty
eventSeverity: error # エラーイベントのみ
eventSources:
- kind: Kustomization
name: "*" # すべての Kustomization
- kind: HelmRelease
name: "*" # すべての HelmRelease
7.4 Receiver(Webhook 受信)
Receiver は外部システムからの Webhook を受信して、リコンシリエーションをトリガーする。これにより、Git プッシュ直後に即座に同期を開始することが可能になる。
GitHub Webhook Receiver
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Receiver
metadata:
name: github-receiver
namespace: flux-system
spec:
type: github
events:
- "ping"
- "push"
secretRef:
name: receiver-token
resources:
- kind: GitRepository
name: webapp
---
apiVersion: v1
kind: Secret
metadata:
name: receiver-token
namespace: flux-system
type: Opaque
stringData:
token: my-webhook-secret-token
Receiver のエンドポイントは以下のコマンドで確認できる:
flux get receivers
# 出力例:
# NAME SUSPENDED READY MESSAGE
# github-receiver False True Receiver initialized for path
# /hook/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
このパスに対して GitHub の Webhook を設定する:
- URL:
https://flux-webhook.example.com/hook/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - Content type:
application/json - Secret:
my-webhook-secret-token
サポートされる Receiver タイプ
| タイプ | 説明 |
|---|---|
github | GitHub Webhook |
gitlab | GitLab Webhook |
bitbucket | Bitbucket Webhook |
harbor | Harbor Webhook(イメージプッシュ) |
quay | Quay Webhook |
dockerhub | Docker Hub Webhook |
nexus | Nexus Repository Webhook |
acr | Azure Container Registry |
gcr | Google Container Registry |
generic | カスタム Webhook |
generic-hmac | HMAC 署名付きカスタム Webhook |
cdevents | CDEvents 準拠 Webhook |
8. Image Automation 詳解
8.1 概要
Image Automation は、コンテナレジストリの新しいイメージを検知して、Git リポジトリ内のマニフェストを自動更新する機能である。これにより CI パイプラインでイメージをビルドした後、自動的にデプロイメントが更新される。
CI Pipeline Flux Image Automation Kubernetes
───────── ───────────────────── ──────────
1. コードプッシュ
2. イメージビルド
3. レジストリにプッシュ
4. 新イメージを検知
(ImageRepository)
5. ポリシー評価
(ImagePolicy)
6. Git リポジトリを更新
(ImageUpdateAutomation)
7. Flux が変更を検知
8. マニフェスト適用
9. 新イメージでデプロイ
8.2 ImageRepository
ImageRepository はコンテナレジストリのイメージタグを定期的にスキャンする。
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImageRepository
metadata:
name: webapp
namespace: flux-system
spec:
image: ghcr.io/my-org/webapp
interval: 5m
# 特定のタグパターンのみをスキャン
exclusionList:
- "^latest$"
- ".*-rc.*"
# 認証が必要な場合
secretRef:
name: registry-creds
プライベートレジストリの認証:
apiVersion: v1
kind: Secret
metadata:
name: registry-creds
namespace: flux-system
type: kubernetes.io/dockerconfigjson
data:
.dockerconfigjson: <base64-encoded-docker-config>
8.3 ImagePolicy
ImagePolicy は、ImageRepository が検出したタグの中からどのタグを使用するかのルールを定義する。
セマンティックバージョニング
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImagePolicy
metadata:
name: webapp
namespace: flux-system
spec:
imageRepositoryRef:
name: webapp
policy:
semver:
range: ">=1.0.0 <2.0.0"
タイムスタンプベース(最新のイメージ)
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImagePolicy
metadata:
name: webapp
namespace: flux-system
spec:
imageRepositoryRef:
name: webapp
filterTags:
pattern: "^main-[a-f0-9]+-(?P<ts>[0-9]+)"
extract: "$ts"
policy:
numerical:
order: asc
アルファベット順(最新のタグ)
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImagePolicy
metadata:
name: webapp
namespace: flux-system
spec:
imageRepositoryRef:
name: webapp
filterTags:
pattern: "^v(?P<version>.*)"
extract: "$version"
policy:
alphabetical:
order: asc
8.4 ImageUpdateAutomation
ImageUpdateAutomation は、ImagePolicy が選択したイメージタグで Git リポジトリ内のマニフェストを自動的に更新する。
apiVersion: image.toolkit.fluxcd.io/v1beta2
kind: ImageUpdateAutomation
metadata:
name: webapp-automation
namespace: flux-system
spec:
interval: 30m
sourceRef:
kind: GitRepository
name: webapp
git:
checkout:
ref:
branch: main
commit:
author:
name: fluxcdbot
email: fluxcdbot@example.com
messageTemplate: |
Automated image update
Automation name: {{ .AutomationObject }}
Files:
{{ range $filename, $_ := .Changed.FileChanges -}}
- {{ $filename }}
{{ end -}}
Objects:
{{ range $resource, $changes := .Changed.Objects -}}
- {{ $resource.Kind }}/{{ $resource.Name }} ({{ $resource.Namespace }})
{{- range $_, $change := $changes }}
- {{ $change.OldValue }} -> {{ $change.NewValue }}
{{- end }}
{{ end -}}
push:
branch: main
update:
path: ./deploy
strategy: Setters
マニフェストでのマーカー設定
ImageUpdateAutomation はマニフェスト内の特殊なコメントマーカーを使ってイメージタグの更新位置を識別する。
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp
spec:
template:
spec:
containers:
- name: webapp
image: ghcr.io/my-org/webapp:v1.0.0 # {"$imagepolicy": "flux-system:webapp"}
マーカーの種類:
# 完全なイメージ参照(リポジトリ + タグ)
image: ghcr.io/my-org/webapp:v1.0.0 # {"$imagepolicy": "flux-system:webapp"}
# タグのみ
image: ghcr.io/my-org/webapp:v1.0.0 # {"$imagepolicy": "flux-system:webapp:tag"}
# イメージ名のみ
image: ghcr.io/my-org/webapp:v1.0.0 # {"$imagepolicy": "flux-system:webapp:name"}
9. マルチテナンシー
9.1 テナント分離モデル
Flux のマルチテナンシーは、Kubernetes の名前空間を基盤として実装される。各テナントは専用の名前空間を持ち、RBAC によりアクセスが制限される。
┌─────────────────────────────────────────────────┐
│ Management Cluster │
│ │
│ ┌──────────────────┐ │
│ │ flux-system │ ← Flux コントローラー │
│ │ (Platform Team) │ │
│ └──────────────────┘ │
│ │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ team-a │ │ team-b │ │
│ │ (Tenant A) │ │ (Tenant B) │ │
│ │ │ │ │ │
│ │ - GitRepository │ │ - GitRepository │ │
│ │ - Kustomization │ │ - HelmRelease │ │
│ │ - HelmRelease │ │ - Alert │ │
│ └──────────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────┘
9.2 テナントのオンボーディング
プラットフォームチームがテナントをセットアップする例:
# tenant-a/namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
name: team-a
labels:
toolkit.fluxcd.io/tenant: team-a
---
# tenant-a/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: team-a-deployer
namespace: team-a
---
# tenant-a/rolebinding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: team-a-deployer
namespace: team-a
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: ServiceAccount
name: team-a-deployer
namespace: team-a
---
# tenant-a/gitrepository.yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
name: team-a-repo
namespace: team-a
spec:
interval: 5m
url: https://github.com/team-a/k8s-manifests.git
ref:
branch: main
secretRef:
name: team-a-git-auth
---
# tenant-a/kustomization.yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: team-a-apps
namespace: team-a
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: team-a-repo
namespace: team-a
path: ./apps
prune: true
serviceAccountName: team-a-deployer # テナント用サービスアカウント
targetNamespace: team-a # リソースはこの名前空間に制限
9.3 クロスネームスペース参照の制御
デフォルトでは、Flux リソースは他の名前空間のリソースを参照できる。マルチテナント環境ではこれを制限する必要がある。
# Kustomize Controller の起動引数で制御
# --no-cross-namespace-refs=true
apiVersion: apps/v1
kind: Deployment
metadata:
name: kustomize-controller
namespace: flux-system
spec:
template:
spec:
containers:
- name: manager
args:
- --no-cross-namespace-refs=true
10. マルチクラスター管理
10.1 管理モデル
Flux によるマルチクラスター管理は、単一の管理クラスター(Management Cluster)から複数のワークロードクラスターを GitOps で管理するモデルを採用する。
┌───────────────────────┐
│ Git Repository │
│ (fleet-infra) │
│ │
│ clusters/ │
│ ├── management/ │
│ ├── staging/ │
│ └── production/ │
└──────────┬────────────┘
│
┌──────────▼────────────┐
│ Management Cluster │
│ (Flux installed) │
│ │
│ ┌─────────────────┐ │
│ │ Kustomization │ │
│ │ (staging) │───│──→ Staging Cluster
│ └─────────────────┘ │
│ │
│ ┌─────────────────┐ │
│ │ Kustomization │ │
│ │ (production) │───│──→ Production Cluster
│ └─────────────────┘ │
└────────────────────────┘
10.2 リポジトリ構造
fleet-infra/
├── clusters/
│ ├── management/
│ │ └── flux-system/
│ │ ├── gotk-components.yaml
│ │ └── gotk-sync.yaml
│ ├── staging/
│ │ ├── infrastructure.yaml # Kustomization
│ │ └── apps.yaml # Kustomization
│ └── production/
│ ├── infrastructure.yaml
│ └── apps.yaml
├── infrastructure/
│ ├── base/
│ │ ├── cert-manager/
│ │ ├── ingress-nginx/
│ │ └── monitoring/
│ ├── staging/
│ │ └── kustomization.yaml
│ └── production/
│ └── kustomization.yaml
└── apps/
├── base/
│ └── webapp/
├── staging/
│ └── kustomization.yaml
└── production/
└── kustomization.yaml
10.3 リモートクラスターの設定
管理クラスターからリモートクラスターにマニフェストを適用するには、kubeConfig フィールドを使用する。
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: staging-apps
namespace: flux-system
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: fleet-infra
path: ./apps/staging
prune: true
kubeConfig:
secretRef:
name: staging-kubeconfig
---
apiVersion: v1
kind: Secret
metadata:
name: staging-kubeconfig
namespace: flux-system
type: Opaque
stringData:
value: |
apiVersion: v1
kind: Config
clusters:
- cluster:
server: https://staging-k8s.example.com
certificate-authority-data: LS0tLS1...
name: staging
contexts:
- context:
cluster: staging
user: flux-deployer
name: staging
current-context: staging
users:
- name: flux-deployer
user:
token: eyJhbGci...
10.4 環境ごとのカスタマイズ
Kustomize のオーバーレイを使って、環境ごとに設定を変更する。
# apps/base/webapp/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp
spec:
replicas: 1
template:
spec:
containers:
- name: webapp
image: ghcr.io/my-org/webapp:v1.0.0
resources:
requests:
cpu: 100m
memory: 128Mi
---
# apps/base/webapp/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml
- service.yaml
- ingress.yaml
Staging オーバーレイ:
# apps/staging/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../base/webapp
patches:
- patch: |
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp
spec:
replicas: 2
template:
spec:
containers:
- name: webapp
resources:
requests:
cpu: 200m
memory: 256Mi
Production オーバーレイ:
# apps/production/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../base/webapp
patches:
- patch: |
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp
spec:
replicas: 5
template:
spec:
containers:
- name: webapp
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
cpu: "1"
memory: 1Gi
11. 監視とオブザーバビリティ
11.1 Prometheus メトリクス
Flux の各コントローラーは Prometheus メトリクスを公開する。
主要なメトリクス:
| メトリクス | 説明 |
|---|---|
gotk_reconcile_duration_seconds | リコンシリエーションの所要時間 |
gotk_reconcile_condition | リソースの状態(Ready/Stalled/Suspended) |
controller_runtime_reconcile_total | リコンシリエーションの合計回数 |
controller_runtime_reconcile_errors_total | エラー回数 |
source_controller_artifact_in_storage | ストレージ内のアーティファクト数 |
Prometheus ServiceMonitor
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: flux-system
namespace: monitoring
spec:
namespaceSelector:
matchNames:
- flux-system
selector:
matchLabels:
app.kubernetes.io/part-of: flux
endpoints:
- port: http-prom
path: /metrics
interval: 30s
11.2 Grafana ダッシュボード
Flux プロジェクトは公式の Grafana ダッシュボードを提供している。
# Grafana ダッシュボードの ConfigMap(kube-prometheus-stack 用)
apiVersion: v1
kind: ConfigMap
metadata:
name: flux-grafana-dashboards
namespace: monitoring
labels:
grafana_dashboard: "1"
data:
flux-cluster.json: |
{
"annotations": { ... },
"panels": [
{
"title": "Reconciliation Duration",
"targets": [
{
"expr": "histogram_quantile(0.99, sum(rate(gotk_reconcile_duration_seconds_bucket[5m])) by (le, kind))"
}
]
}
]
}
11.3 Flux のイベント
Flux は Kubernetes イベントを通じて詳細な情報を提供する。
# Flux 関連のイベントを確認
kubectl -n flux-system get events --sort-by='.lastTimestamp'
# 特定のリソースのイベント
kubectl -n flux-system describe kustomization webapp
# Flux CLI でのイベント確認
flux events --for Kustomization/webapp
11.4 ログの確認
# Source Controller のログ
kubectl -n flux-system logs deployment/source-controller
# Kustomize Controller のログ
kubectl -n flux-system logs deployment/kustomize-controller
# 特定のリソースに関するログのフィルタリング
kubectl -n flux-system logs deployment/kustomize-controller | \
grep "webapp"
# JSON ログのパース
kubectl -n flux-system logs deployment/source-controller \
-f --since=5m | jq 'select(.name == "webapp")'
12. 運用ガイド
12.1 リコンシリエーションの手動トリガー
# GitRepository のリコンシリエーション
flux reconcile source git webapp
# Kustomization のリコンシリエーション
flux reconcile kustomization webapp
# HelmRelease のリコンシリエーション
flux reconcile helmrelease nginx
# すべてのソースを強制的に再取得
flux reconcile source git flux-system
12.2 リコンシリエーションの一時停止と再開
メンテナンス時やトラブルシューティング時に、リコンシリエーションを一時停止できる。
# 一時停止
flux suspend kustomization webapp
flux suspend helmrelease nginx
flux suspend source git webapp
# 再開
flux resume kustomization webapp
flux resume helmrelease nginx
flux resume source git webapp
YAML での設定:
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: webapp
namespace: flux-system
spec:
suspend: true # リコンシリエーションを一時停止
interval: 10m
# ...
12.3 ロールバック
Git ベースのロールバック(推奨)
GitOps では、Git リポジトリの状態を戻すことがロールバックとなる。
# Git で前のバージョンに戻す
git revert HEAD
git push origin main
# Flux が自動的に変更を検知して適用する
# 即時反映が必要な場合は手動リコンシリエーション
flux reconcile source git webapp
flux reconcile kustomization webapp
HelmRelease のロールバック
HelmRelease は自動ロールバック機能を持つ。
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: webapp
spec:
upgrade:
remediation:
retries: 3
strategy: rollback # アップグレード失敗時にロールバック
12.4 Garbage Collection(プルーニング)
prune: true を設定した Kustomization は、Git リポジトリから削除されたリソースをクラスターからも自動的に削除する。
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: webapp
namespace: flux-system
spec:
prune: true # Git から削除されたリソースを自動削除
特定のリソースをプルーニングから除外:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: webapp-data
annotations:
kustomize.toolkit.fluxcd.io/prune: disabled # プルーニングから除外
12.5 Flux のアップグレード
# Flux CLI のアップグレード
brew upgrade fluxcd/tap/flux
# クラスター上の Flux のアップグレード
flux install
# または、ブートストラップの再実行
flux bootstrap github \
--owner=my-org \
--repository=fleet-infra \
--branch=main \
--path=clusters/production
12.6 トラブルシューティング
# 全体の状態確認
flux get all
# 問題のあるリソースの特定
flux get all --status-selector ready=false
# 詳細なステータスの確認
flux get kustomizations --verbose
# コントローラーのログ確認
flux logs --all-namespaces --since=1h
# 特定レベルのログ
flux logs --level=error --since=30m
# リソースの詳細情報
kubectl -n flux-system describe kustomization webapp
# CRD の状態確認
kubectl get crds | grep fluxcd
# Flux のヘルスチェック
flux check
13. 実践的な構成パターン
13.1 モノレポ構成
単一の Git リポジトリですべてのクラスターとアプリケーションを管理するパターン。
fleet-infra/
├── clusters/
│ ├── staging/
│ │ ├── flux-system/ # Flux のブートストラップファイル
│ │ ├── infrastructure.yaml # インフラ Kustomization
│ │ └── apps.yaml # アプリ Kustomization
│ └── production/
│ ├── flux-system/
│ ├── infrastructure.yaml
│ └── apps.yaml
├── infrastructure/
│ ├── controllers/ # Ingress, Cert-Manager 等
│ │ ├── base/
│ │ ├── staging/
│ │ └── production/
│ ├── configs/ # ClusterIssuer, StorageClass 等
│ │ ├── base/
│ │ ├── staging/
│ │ └── production/
│ └── monitoring/ # Prometheus, Grafana 等
│ ├── base/
│ ├── staging/
│ └── production/
└── apps/
├── base/
│ ├── webapp/
│ ├── api-server/
│ └── worker/
├── staging/
│ └── kustomization.yaml
└── production/
└── kustomization.yaml
クラスター定義ファイルの例:
# clusters/production/infrastructure.yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: infrastructure-controllers
namespace: flux-system
spec:
interval: 1h
retryInterval: 1m
timeout: 5m
sourceRef:
kind: GitRepository
name: flux-system
path: ./infrastructure/controllers/production
prune: true
wait: true
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: infrastructure-configs
namespace: flux-system
spec:
interval: 1h
dependsOn:
- name: infrastructure-controllers
sourceRef:
kind: GitRepository
name: flux-system
path: ./infrastructure/configs/production
prune: true
---
# clusters/production/apps.yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: apps
namespace: flux-system
spec:
interval: 10m
dependsOn:
- name: infrastructure-configs
sourceRef:
kind: GitRepository
name: flux-system
path: ./apps/production
prune: true
wait: true
postBuild:
substitute:
ENVIRONMENT: production
DOMAIN: app.example.com
13.2 マルチレポ構成
インフラストラクチャとアプリケーションを別々のリポジトリで管理するパターン。
# fleet-repo: クラスター設定リポジトリ
---
# アプリケーションリポジトリへの参照
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
name: webapp-repo
namespace: flux-system
spec:
interval: 5m
url: https://github.com/my-org/webapp-deploy.git
ref:
branch: main
secretRef:
name: webapp-git-auth
---
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
name: api-repo
namespace: flux-system
spec:
interval: 5m
url: https://github.com/my-org/api-deploy.git
ref:
branch: main
secretRef:
name: api-git-auth
---
# Kustomization で各リポジトリを適用
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: webapp
namespace: flux-system
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: webapp-repo
path: ./deploy/production
prune: true
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: api
namespace: flux-system
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: api-repo
path: ./deploy/production
prune: true
13.3 Helm + Kustomize のハイブリッド構成
Helm チャートをベースとして使用し、Kustomize で環境固有のカスタマイズを行うパターン。
# HelmRelease でベースとなるチャートをインストール
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: prometheus-stack
namespace: monitoring
spec:
interval: 1h
chart:
spec:
chart: kube-prometheus-stack
version: ">=60.0.0 <61.0.0"
sourceRef:
kind: HelmRepository
name: prometheus-community
values:
grafana:
enabled: true
adminPassword: "${GRAFANA_ADMIN_PASSWORD}"
prometheus:
prometheusSpec:
retention: 30d
storageSpec:
volumeClaimTemplate:
spec:
storageClassName: fast-ssd
resources:
requests:
storage: 100Gi
# Kustomization で追加リソースを適用
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: monitoring-config
namespace: flux-system
spec:
interval: 30m
dependsOn:
- name: monitoring-stack
sourceRef:
kind: GitRepository
name: fleet-infra
path: ./monitoring/config/production
prune: true
monitoring/config/production/ にはカスタム Grafana ダッシュボード、PrometheusRule、ServiceMonitor などを配置する。
13.4 Progressive Delivery(Flagger との連携)
Flux は Flagger と連携して、カナリアデプロイ、A/B テスト、ブルーグリーンデプロイを実現できる。
# Flagger のインストール(HelmRelease)
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: flagger
namespace: flagger-system
spec:
interval: 1h
chart:
spec:
chart: flagger
version: ">=1.37.0"
sourceRef:
kind: HelmRepository
name: flagger
values:
meshProvider: istio # istio, linkerd, nginx, etc.
metricsServer: http://prometheus.monitoring:9090
---
# カナリアリソースの定義
apiVersion: flagger.app/v1beta1
kind: Canary
metadata:
name: webapp
namespace: webapp-production
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: webapp
progressDeadlineSeconds: 60
service:
port: 80
targetPort: 8080
analysis:
interval: 30s
threshold: 5
maxWeight: 50
stepWeight: 10
metrics:
- name: request-success-rate
thresholdRange:
min: 99
interval: 1m
- name: request-duration
thresholdRange:
max: 500
interval: 1m
14. セキュリティベストプラクティス
14.1 最小権限の原則
# テナントごとの専用サービスアカウント
apiVersion: v1
kind: ServiceAccount
metadata:
name: webapp-deployer
namespace: webapp
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: webapp-deployer
namespace: webapp
rules:
- apiGroups: ["apps"]
resources: ["deployments", "replicasets"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: [""]
resources: ["services", "configmaps", "secrets"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["networking.k8s.io"]
resources: ["ingresses"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: webapp-deployer
namespace: webapp
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: webapp-deployer
subjects:
- kind: ServiceAccount
name: webapp-deployer
namespace: webapp
14.2 Git リポジトリのセキュリティ
# SSH 鍵認証(推奨)
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
name: webapp
namespace: flux-system
spec:
interval: 5m
url: ssh://git@github.com/my-org/webapp-deploy.git
secretRef:
name: webapp-ssh-key
# コミット署名の検証
verify:
provider: cosign # cosign or notation
secretRef:
name: cosign-pub # 公開鍵を含む Secret
14.3 OCI アーティファクトの署名検証
apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: OCIRepository
metadata:
name: app-manifests
namespace: flux-system
spec:
interval: 5m
url: oci://ghcr.io/my-org/app-manifests
ref:
tag: latest
verify:
provider: cosign
secretRef:
name: cosign-pub
14.4 ネットワークポリシー
Flux コントローラーのネットワークアクセスを制限する。
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: flux-system-egress
namespace: flux-system
spec:
podSelector: {}
policyTypes:
- Egress
egress:
# DNS の許可
- to: []
ports:
- port: 53
protocol: TCP
- port: 53
protocol: UDP
# Kubernetes API Server
- to:
- ipBlock:
cidr: 10.0.0.1/32
ports:
- port: 443
protocol: TCP
# Git リポジトリ(GitHub)
- to:
- ipBlock:
cidr: 0.0.0.0/0
ports:
- port: 443
protocol: TCP
- port: 22
protocol: TCP
14.5 Pod Security Standards
apiVersion: v1
kind: Namespace
metadata:
name: flux-system
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restricted
15. CI/CD パイプラインとの統合
15.1 GitHub Actions との統合
# .github/workflows/flux-diff.yaml
name: Flux Diff
on:
pull_request:
branches: [main]
jobs:
flux-diff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Flux CLI
uses: fluxcd/flux2/action@main
- name: Validate Flux manifests
run: |
flux check --pre
# Kustomize のビルド検証
for dir in clusters/*/; do
echo "Validating $dir"
kustomize build "$dir" | kubectl apply --dry-run=client -f -
done
- name: Diff against cluster
env:
KUBECONFIG: ${{ secrets.KUBECONFIG }}
run: |
flux diff kustomization flux-system \
--path=./clusters/production
15.2 イメージ自動更新を含む CI/CD ワークフロー
# .github/workflows/ci.yaml
name: CI
on:
push:
branches: [main]
jobs:
build-and-push:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Login to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v6
with:
push: true
tags: |
ghcr.io/${{ github.repository }}:${{ github.sha }}
ghcr.io/${{ github.repository }}:v1.0.${{ github.run_number }}
Flux の ImagePolicy と ImageUpdateAutomation が自動的に新しいタグを検知し、デプロイメントマニフェストを更新する。
15.3 Flux の検証を含む PR チェック
# .github/workflows/validate.yaml
name: Validate
on:
pull_request:
paths:
- "clusters/**"
- "infrastructure/**"
- "apps/**"
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup tools
run: |
# kubeconform のインストール
curl -sL https://github.com/yannh/kubeconform/releases/latest/download/kubeconform-linux-amd64.tar.gz | \
tar xz -C /usr/local/bin
- name: Validate Kubernetes manifests
run: |
find . -name "*.yaml" -path "*/apps/*" | xargs -I {} \
kubeconform -strict -summary \
-schema-location default \
-schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
{}
- name: Validate Flux custom resources
uses: fluxcd/flux2/action@main
with:
command: |
flux check --pre 2>/dev/null || true
16. 高度な設定
16.1 Sharding(シャーディング)
大規模環境では、コントローラーをシャーディングしてスケーラビリティを向上させることができる。
# シャード 1: チーム A のリソース
apiVersion: apps/v1
kind: Deployment
metadata:
name: kustomize-controller-shard1
namespace: flux-system
spec:
template:
spec:
containers:
- name: manager
args:
- --watch-label-selector=sharding.fluxcd.io/key=shard1
---
# リソースにシャードラベルを付与
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: team-a-apps
namespace: flux-system
labels:
sharding.fluxcd.io/key: shard1
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: team-a
path: ./apps
16.2 リソース制限の設定
apiVersion: apps/v1
kind: Deployment
metadata:
name: source-controller
namespace: flux-system
spec:
template:
spec:
containers:
- name: manager
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
cpu: "1"
memory: 1Gi
args:
- --storage-adv-addr=source-controller.flux-system.svc.cluster.local
- --storage-path=/data
- --storage-max-size=10Gi # アーティファクトストレージの最大サイズ
16.3 Webhook TLS の設定
Receiver の Webhook エンドポイントに TLS を設定する。
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: flux-receiver
namespace: flux-system
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
tls:
- hosts:
- flux-webhook.example.com
secretName: flux-receiver-tls
rules:
- host: flux-webhook.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: notification-controller
port:
number: 80
17. Flux と ArgoCD の比較
| 特徴 | FluxCD | ArgoCD |
|---|---|---|
| アーキテクチャ | マイクロサービス(複数コントローラー) | モノリシック(単一アプリケーション) |
| UI | CLI + Kubernetes Dashboard | 専用 Web UI |
| CRD | 専門的な CRD の組み合わせ | Application CRD 中心 |
| Helm サポート | HelmRelease CRD | Application CRD 内で定義 |
| Kustomize | ネイティブサポート | ネイティブサポート |
| マルチテナンシー | 名前空間ベース + RBAC | AppProject ベース |
| イメージ自動更新 | 内蔵(Image Automation) | Argo CD Image Updater(別プロジェクト) |
| OCI サポート | ネイティブ | v2.8+ |
| 通知 | 内蔵(Notification Controller) | 内蔵 |
| プログレッシブデリバリー | Flagger との統合 | Argo Rollouts |
| 学習曲線 | 中(CRD の理解が必要) | 低(UI が直感的) |
| リソース使用量 | 軽量 | やや重い |
| CNCF ステータス | Graduated | Graduated |
選択の指針
FluxCD が適している場合:
- Kubernetes ネイティブなアプローチを重視する
- 軽量でリソース効率の良いソリューションが必要
- CLI ベースの運用に慣れている
- イメージ自動更新を統合的に管理したい
- マイクロサービスアーキテクチャの柔軟性を求める
ArgoCD が適している場合:
- 視覚的な Web UI が必要
- 開発者が直接デプロイ状態を確認する必要がある
- 単一のアプリケーション CRD でシンプルに管理したい
- SSO/OIDC 統合が重要
18. まとめ
18.1 FluxCD 導入のメリット
- 宣言的管理: すべてのインフラストラクチャとアプリケーションの設定が Git で管理され、監査可能
- 自動リコンシリエーション: 手動操作による設定のドリフトを自動的に修正
- Kubernetes ネイティブ: CRD と RBAC を活用した自然な統合
- 軽量: 必要なコンポーネントだけをデプロイでき、リソース効率が良い
- セキュリティ: プル型のアプローチにより、CI/CD パイプラインにクラスター認証情報を露出させない
- マルチテナンシー: 名前空間ベースのテナント分離で複数チームが安全に共存
- マルチクラスター: 単一のリポジトリから複数クラスターを統一的に管理
18.2 導入時の注意点
- 学習コスト: 複数の CRD とコントローラーの理解が必要
- デバッグ: UI がないため、CLI とログベースのデバッグが中心
- Git 運用: ブランチ戦略とレビュープロセスの整備が重要
- シークレット管理: SOPS/Age の運用フローの確立が必要
- ネットワーク: クラスターから Git リポジトリへのアウトバウンド接続が必要
18.3 推奨される導入ステップ
- PoC 環境での検証: 開発クラスターで Flux をインストールし、基本的なワークフローを確認
- リポジトリ構造の設計: モノレポかマルチレポかの戦略を決定
- CI/CD パイプラインの整備: イメージビルドと Flux の連携を確立
- シークレット管理の設計: SOPS/Age による暗号化フローを構築
- 通知の設定: Slack 等への通知を設定して可視性を確保
- ステージング環境での運用: 本番適用前に十分なテストを実施
- 本番環境への展開: 段階的にアプリケーションを Flux 管理に移行
- マルチクラスター拡張: 必要に応じて複数クラスターの管理に拡張
付録 A: Flux CLI コマンドリファレンス
ブートストラップ
flux bootstrap github --owner=ORG --repository=REPO --path=PATH
flux bootstrap gitlab --owner=GROUP --repository=REPO --path=PATH
flux bootstrap git --url=URL --path=PATH
ソース管理
flux create source git NAME --url=URL --branch=BRANCH
flux create source helm NAME --url=URL
flux create source oci NAME --url=URL --tag=TAG
flux get sources git
flux get sources helm
flux reconcile source git NAME
flux delete source git NAME
Kustomization 管理
flux create kustomization NAME --source=GitRepository/NAME --path=PATH
flux get kustomizations
flux reconcile kustomization NAME
flux suspend kustomization NAME
flux resume kustomization NAME
flux delete kustomization NAME
flux diff kustomization NAME --path=PATH
HelmRelease 管理
flux create helmrelease NAME --chart=CHART --source=HelmRepository/NAME
flux get helmreleases
flux reconcile helmrelease NAME
flux suspend helmrelease NAME
flux resume helmrelease NAME
flux delete helmrelease NAME
通知管理
flux create alert-provider NAME --type=slack --address=URL
flux create alert NAME --provider-ref=PROVIDER --event-source=KIND/NAME
flux create receiver NAME --type=github --event=push --resource=GitRepository/NAME
flux get alert-providers
flux get alerts
flux get receivers
イメージ自動化
flux create image repository NAME --image=IMAGE
flux create image policy NAME --image-ref=NAME --semver=RANGE
flux create image update NAME --git-repo-ref=NAME --git-repo-path=PATH
flux get image repository
flux get image policy
flux get image update
全体管理
flux get all [--all-namespaces]
flux check [--pre]
flux install [--components=LIST]
flux uninstall
flux logs [--all-namespaces] [--since=DURATION]
flux events [--for KIND/NAME]
flux export kustomization NAME > kustomization.yaml
flux export helmrelease NAME > helmrelease.yaml
付録 B: よく使う Kustomize パターン
ConfigMap Generator
# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
configMapGenerator:
- name: app-config
literals:
- APP_ENV=production
- LOG_LEVEL=info
files:
- configs/app.conf
Secret Generator
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
secretGenerator:
- name: db-creds
literals:
- username=admin
- password=secret123
type: Opaque
コモンラベルとアノテーション
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
commonLabels:
app.kubernetes.io/managed-by: flux
environment: production
commonAnnotations:
team: platform
付録 C: 用語集
| 用語 | 説明 |
|---|---|
| リコンシリエーション | 望ましい状態と実際の状態を比較し、差分を修正するプロセス |
| ブートストラップ | Flux をクラスターにインストールし、自己管理可能にする初期化プロセス |
| プルーニング | Git から削除されたリソースをクラスターからも自動削除する機能 |
| ドリフト | 手動変更などにより、実際の状態が望ましい状態から逸脱した状態 |
| ソース | Flux が監視する外部リソース(Git リポジトリ、Helm リポジトリ等) |
| アーティファクト | Source Controller がソースから取得し内部キャッシュした成果物 |
| GOTK | GitOps Toolkit の略。Flux v2 の基盤 |
| CRD | Custom Resource Definition。Kubernetes API を拡張するメカニズム |
| SOPS | Secrets OPerationS。暗号化されたファイルの管理ツール |
| OCI | Open Container Initiative。コンテナフォーマットの標準仕様 |