用 Terraform 管理 AnyLB
把源站池、调度策略与健康检查写成代码,并在各环境之间晋级。
最后更新: 2026年8月29日 · 约 6 分钟
安装 Provider
在 Terraform 配置中声明 Provider,并通过环境变量提供 API Token 完成认证,无需其他凭据。
hcl
terraform { required_providers { anylb = { source = "anylb/anylb" version = "~> 2.4" } }} provider "anylb" { # Reads ANYLB_TOKEN from the environment.}定义源站池与负载均衡实例
源站池把源站与健康检查组装在一起;负载均衡实例则把一个域名绑定到一个或多个源站池,并指定调度策略。
hcl
resource "anylb_pool" "api" { name = "api-prod" strategy = "latency" origin { address = "api-sin1.internal" weight = 100 } origin { address = "api-fra1.internal" weight = 100 } health_check { path = "/healthz" interval_seconds = 2 timeout_seconds = 1 unhealthy_threshold = 2 }} resource "anylb_load_balancer" "api" { hostname = "api.example.com" pool_ids = [anylb_pool.api.id]}计划、评审、应用
先执行 plan 查看将要发生的精确差异。应用后的变更会在数秒内传播到所有 Cloudflare 地域。
shell
$ anylb lb create \ --hostname api.example.com \ --strategy latency \ --origin api-sin1.internal \ --origin api-fra1.internal \ --health-check /healthz --interval 2s ✔ Pool created api-prod (2 origins)✔ Health checks on 3 probe regions✔ Certificate issued api.example.com✔ Load balancer live https://api.example.com Next: point a CNAME at edge.anylb.com检测并修复配置漂移
AnyLB 会为每次变更记录版本号,因此针对线上状态执行 plan 就能准确告诉你哪里发生了漂移、以及何时发生。