INTEGRITY Документация

Настройка правил ограничения скорости с помощью Terraform

На этой странице приведены примеры создания правила ограничения частоты запросов в зоне или аккаунте с помощью Terraform.

Если вы используете Cloudflare API, см. следующие ресурсы:

Прежде чем начать

Получите нужные идентификаторы аккаунта или зоны

Для конфигураций Terraform, приведённых на этой странице, требуется идентификатор зоны (или идентификатор аккаунта), в которой вы будете развёртывать наборы правил.

Импорт или удаление существующих наборов правил

Terraform исходит из того, что полностью контролирует наборы правил аккаунта и зоны. Если у вас уже настроены наборы правил в аккаунте или зоне, выполните одно из следующих действий:


Создание правила ограничения скорости на уровне зоны

В этом примере создаётся правило ограничения скорости запросов в зоне с идентификатором <ZONE_ID> блокирующее трафик, превышающий настроенную скорость:

Необходимые разрешения API-токена

Хотя бы одно из следующих права доступа токена требуется:

  • Zone WAF Write

Настройте cloudflare_ruleset ↗ ресурс:

resource "cloudflare_ruleset" "zone_rl" {
  zone_id     = var.cloudflare_zone_id
  name        = "Rate limiting for my zone"
  description = ""
  kind        = "zone"
  phase       = "http_ratelimit"

  rules = [{
    ref         = "rate_limit_api_requests_ip"
    description = "Rate limit API requests by IP"
    expression  = "(http.request.uri.path matches \"^/api/\")"
    action      = "block"
    ratelimit = {
      characteristics     = ["cf.colo.id", "ip.src"]
      period              = 60
      requests_per_period = 100
      mitigation_timeout  = 600
    }
  }]
}
resource "cloudflare_ruleset" "zone_rl" {
  zone_id     = "<ZONE_ID>"
  name        = "Rate limiting for my zone"
  description = ""
  kind        = "zone"
  phase       = "http_ratelimit"

  rules {
    ref         = "rate_limit_api_requests_ip"
    description = "Rate limit API requests by IP"
    expression  = "(http.request.uri.path matches \"^/api/\")"
    action      = "block"
    ratelimit {
      characteristics = ["cf.colo.id", "ip.src"]
      period = 60
      requests_per_period = 100
      mitigation_timeout = 600
    }
  }
}

Чтобы создать ещё одно правило ограничения скорости запросов, добавьте новый rules объект в тот же cloudflare_ruleset ресурс.


Создание правила ограничения скорости на уровне аккаунта

В этом примере определяется пользовательский набор правил с одним правилом ограничения скорости запросов в аккаунте с ID <ACCOUNT_ID> , которое блокирует трафик для /api/ путь, превышающий настроенную скорость. Второй cloudflare_ruleset ресурс определяет execute правило, разворачивающее пользовательский набор правил для трафика, направленного на example.com.

Необходимые разрешения API-токена

Все перечисленные ниже права доступа токена обязательны:

  • Account WAF Write
  • Account Rulesets Write

Настройте cloudflare_ruleset ↗ ресурс:

resource "cloudflare_ruleset" "account_rl" {
  account_id  = var.cloudflare_account_id
  name        = "Rate limiting rules for APIs"
  description = ""
  kind        = "custom"
  phase       = "http_ratelimit"

  rules = [{
    ref         = "rate_limit_api_ip"
    description = "Rate limit API requests by IP"
    expression  = "http.request.uri.path contains \"/api/\""
    action      = "block"
    ratelimit = {
      characteristics     = ["cf.colo.id", "ip.src"]
      period              = 60
      requests_per_period = 100
      mitigation_timeout  = 600
    }
  }]
}

# Account-level entry point ruleset for the 'http_ratelimit' phase
resource "cloudflare_ruleset" "account_rl_entrypoint" {
  account_id  = var.cloudflare_account_id
  name        = "Account-level rate limiting"
  description = ""
  kind        = "root"
  phase       = "http_ratelimit"

  depends_on = [cloudflare_ruleset.account_rl]

  rules = [{
    # Deploy the previously defined custom ruleset containing a rate limiting rule
    ref         = "deploy_rate_limit_example_com"
    description = "Deploy custom ruleset with RL rule"
    expression  = "cf.zone.name eq \"example.com\" and cf.zone.plan eq \"ENT\""
    action      = "execute"
    action_parameters = {
      id = cloudflare_ruleset.account_rl.id
    }
  }]
}
resource "cloudflare_ruleset" "account_rl" {
  account_id  = "<ACCOUNT_ID>"
  name        = "Rate limiting rules for APIs"
  description = ""
  kind        = "custom"
  phase       = "http_ratelimit"

  rules {
    ref         = "rate_limit_api_ip"
    description = "Rate limit API requests by IP"
    expression  = "http.request.uri.path contains \"/api/\""
    action      = "block"
    ratelimit {
      characteristics     = ["cf.colo.id", "ip.src"]
      period              = 60
      requests_per_period = 100
      mitigation_timeout  = 600
    }
  }
}

# Account-level entry point ruleset for the 'http_ratelimit' phase
resource "cloudflare_ruleset" "account_rl_entrypoint" {
  account_id  = "<ACCOUNT_ID>"
  name        = "Account-level rate limiting"
  description = ""
  kind        = "root"
  phase       = "http_ratelimit"

  depends_on = [cloudflare_ruleset.account_rl]

  rules {
    # Deploy the previously defined custom ruleset containing a rate limiting rule
    ref         = "deploy_rate_limit_example_com"
    description = "Deploy custom ruleset with RL rule"
    expression  = "cf.zone.name eq \"example.com\" and cf.zone.plan eq \"ENT\""
    action      = "execute"
    action_parameters {
      id = cloudflare_ruleset.account_rl.id
    }
  }
}

Чтобы создать ещё одно правило ограничения скорости запросов, добавьте новый rules объект в тот же cloudflare_ruleset ресурс.


Создание расширенного правила ограничения скорости

В этом примере создаётся правило ограничения скорости запросов в зоне с идентификатором <ZONE_ID> с:

Необходимые разрешения API-токена

Хотя бы одно из следующих права доступа токена требуется:

  • Zone WAF Write

Настройте cloudflare_ruleset ↗ ресурс:

resource "cloudflare_ruleset" "zone_rl_custom_response" {
  zone_id     = var.cloudflare_zone_id
  name        = "Advanced rate limiting rule for my zone"
  description = ""
  kind        = "zone"
  phase       = "http_ratelimit"

  rules = [{
    ref         = "rate_limit_example_com_status_404"
    description = "Rate limit requests to www.example.com when exceeding the threshold of 404 responses on /status/"
    expression  = "http.host eq \"www.example.com\" and (http.request.uri.path matches \"^/status/\")"
    action      = "block"
    action_parameters = {
      response = {
        status_code  = 429
        content      = "{\"response\": \"block\"}"
        content_type = "application/json"
      }
    }
    ratelimit = {
      characteristics     = ["ip.src", "cf.colo.id"]
      period              = 10
      requests_per_period = 5
      mitigation_timeout  = 30
      counting_expression = "(http.host eq \"www.example.com\") and (http.request.uri.path matches \"^/status/\") and (http.response.code eq 404)"
    }
  }]
}
resource "cloudflare_ruleset" "zone_rl_custom_response" {
  zone_id     = "<ZONE_ID>"
  name        = "Advanced rate limiting rule for my zone"
  description = ""
  kind        = "zone"
  phase       = "http_ratelimit"

  rules {
    ref         = "rate_limit_example_com_status_404"
    description = "Rate limit requests to www.example.com when exceeding the threshold of 404 responses on /status/"
    expression  = "http.host eq \"www.example.com\" and (http.request.uri.path matches \"^/status/\")"
    action      = "block"
    action_parameters {
      response {
        status_code  = 429
        content      = "{\"response\": \"block\"}"
        content_type = "application/json"
      }
    }
    ratelimit {
      characteristics     = ["ip.src", "cf.colo.id"]
      period              = 10
      requests_per_period = 5
      mitigation_timeout  = 30
      counting_expression = "(http.host eq \"www.example.com\") and (http.request.uri.path matches \"^/status/\") and (http.response.code eq 404)"
    }
  }
}

Чтобы создать ещё одно правило ограничения скорости запросов, добавьте новый rules объект в тот же cloudflare_ruleset ресурс.