Flux CD Flux CD

使用 Flux CLI 管理 Flux

在终端中检查、查看、协调、对比、追踪、暂停并排查 Flux 资源。

10 min 初级

Flux 没有内置的 Web UI。你的日常工作都通过 flux CLI 和 kubectl 完成,这也使它很容易脚本化。本指南假设 Flux 已完成 bootstrap,并且前面指南中的 webapp Kustomization 已存在。

安装 CLI 并检查集群

安装 CLI(macOS 上使用 brew install fluxcd/tap/flux,或使用 curl -s https://fluxcd.io/install.sh | sudo bash),然后检查:

flux --version
flux check --pre   # before installing: is the cluster compatible?
flux check         # after installing: are the controllers healthy?

运行 flux --help 列出命令。大多数命令默认读取 flux-system 命名空间。添加 -A(--all-namespaces)可以查看所有命名空间,或用 -n <namespace> 指定某个命名空间。

查看现有内容

flux get all -A
flux get sources git
flux get kustomizations
flux get helmreleases -A

每一行显示对象的修订版本、是否 Ready、是否被暂停,以及最新的状态消息。当出现异常时,flux get all -A 是一个很好的首选命令。要查看对象之间的关系:

flux tree kustomization flux-system
flux trace deployment webapp -n webapp

tree 列出某个 Kustomization 所管理的一切。trace 则反过来:给定一个实时对象,它显示该对象来自哪个 Kustomization,以及哪个 Git source 和修订版本。

按需协调

Flux 按间隔轮询。若要立即强制执行:

flux reconcile source git flux-system
flux reconcile kustomization webapp --with-source
flux reconcile helmrelease podinfo -n podinfo

--with-source 会在应用之前先刷新 Git source,所以你刚推送的提交会被立即拾取。

在推送前预览

有两个命令可以在不改变集群的前提下渲染并比较,这在代码审查和 CI 中很有用:

flux build kustomization webapp --path ./apps/webapp --dry-run
flux diff kustomization webapp --path ./apps/webapp

build 打印 Flux 将要应用的清单。diff 将它们与正在运行的内容进行比较。两者都从本地文件夹读取,所以请在仓库的克隆中运行。

排查问题

flux logs --all-namespaces --level=error --follow
flux events --for Kustomization/webapp
kubectl describe kustomization webapp -n flux-system

flux logs 流式输出控制器日志,flux events 显示特定对象的 Kubernetes 事件,kubectl describe 显示对象的状况和最新的错误。Kustomization 失败的常见原因有:path 错误、缺少依赖(检查 dependsOn)、无效的 YAML,或设置了 wait: true 时健康检查失败。对于卡住的 GitRepository,describe 通常会显示认证错误。

无需编写 YAML 即可创建资源

大多数 flux create 命令都可以打印 YAML 而不是直接应用。将输出提交到 Git,这样一切都保持声明式:

flux create source git webapp-config \
  --url=https://github.com/your-org/webapp-config \
  --branch=main --interval=1m --export > webapp-source.yaml

flux create kustomization webapp \
  --source=GitRepository/webapp-config \
  --path=./apps/webapp --prune=true --interval=10m --export > webapp.yaml

没有 --export 时,命令会直接应用对象,这对实验没有问题,但会让集群与 Git 不同步。要将现有对象转储为 YAML,请使用 flux export:

flux export source git --all
flux export kustomization --all

暂停、恢复与清理

flux suspend kustomization webapp
flux resume kustomization webapp
flux delete kustomization webapp
flux uninstall

suspend 停止协调,resume 重新启动。delete 删除 Kustomization,并且在 prune: true 时,也会删除它所管理的资源,因此可能需要片刻。uninstall 会从集群中移除 Flux 本身。之后运行 flux get kustomizations 进行确认。

一些实用的额外功能

  • flux stats 汇总存在多少 Flux 资源以及有多少已就绪。
  • Flux 2.9 增加了 CLI 插件系统(flux plugin),带有 mirror 和 schema 等插件。运行 flux plugin --help 查看你的版本提供了什么。
  • 由于没有 UI,许多团队会在 Flux 暴露的指标之上添加 Grafana 仪表板或社区仪表板。

热门指南