Security & FinOps · Enterprise

Cloudflare Rate Limiting and SSL Rules as Code with Terraform (plus Cloud Armor)

Manage Cloudflare DNS, certificates, ruleset-based SSL mode overrides and rate limiting in Terraform, and mirror the throttling policy in Google Cloud Armor so edge protection is reviewed, versioned and reproducible.

  • Cloudflare
  • Terraform
  • Cloud Armor
  • DNS
  • cert-manager
  • Rulesets
  • WAF
  • GitHub Actions

// Why this matters

Cloudflare terraform rate limiting is worth doing because edge settings are production controls that change quickly and are rarely reviewed. A rate limit adjusted in a dashboard during an incident stays that way for months; an SSL mode flipped for one hostname is forgotten until a certificate expires. Putting these in Git means every change has an author, a reason and a diff.

The second motivation is consistency across many hostnames. A platform with dozens of customer or environment hostnames needs the same baseline everywhere: proxied DNS, strict origin certificate validation, sensible throttling on login and API paths. Copying settings by hand guarantees drift; a generated rule per host does not.

Finally, the edge is not a single place. Traffic may reach the origin through Cloudflare, directly through a cloud load balancer, or from internal clients. The throttling intent should hold on each path, which is why the same policy is expressed in both Cloudflare and Cloud Armor.

// The problem

Zone-level settings are blunt. Switching a whole zone to strict SSL breaks every hostname whose origin still serves a certificate Cloudflare cannot validate, so teams delay the change indefinitely and the zone stays in a weaker mode. What you want is strict per host, enabled as each origin is ready.

Rate limiting through the dashboard has no review trail and no testing story. Thresholds are guessed, expressions are typed by hand and mistakes show up as legitimate users receiving errors. With many hostnames the rule count grows, and nobody can say which rules are still needed.

DNS and certificate validation records are the third source of toil. Records created manually for each new hostname or for certificate issuance get lost or duplicated, and cleanup after a customer leaves rarely happens.

// The solution

Everything starts from one map of hostnames. Each entry has a name, an origin target, an SSL mode and a rate-limit profile name. Terraform expands that map into three things: a proxied DNS record, an entry in a configuration rules ruleset that sets the SSL mode for matching hosts, and membership in a rate-limit ruleset through the profile. Because rules are generated, adding a hostname is one map entry and the plan shows exactly the record and rule that will appear.

Rate-limit profiles are small objects: a request expression (for example paths under /login or /api/), a characteristic to count by (client IP, optionally with a header), a threshold, a period and an action with a mitigation timeout. Terraform renders each profile into a rule inside a cloudflare_ruleset in the http_ratelimit phase. Putting rules in one ruleset per zone keeps ordering explicit and avoids the "which ruleset won" confusion.

Certificates and validation records follow the same pattern. If you use origin certificates or a certificate manager for Cloudflare-validated hostnames, the DNS records needed for validation are created by Terraform alongside the hostname, and deleted with it. The API token the pipeline uses is scoped to exactly the zone and permissions it needs: zone read, DNS edit, zone settings edit and the ruleset permissions, and nothing account-wide.

For traffic that bypasses Cloudflare, a Cloud Armor security policy carries the same intent: a throttle rule with rate_based_ban on the same paths and thresholds, attached to the backend service. Keeping the numbers in shared variables means the two edges move together. We rejected the dashboard (no review), zone-wide settings (all-or-nothing migrations) and a separate tool for Cloud Armor (two sources of truth). See Guardrails and Engineering Telemetry: Org Policy, Project Factory, Gatekeeper, Four Keys for how guardrails like this are tracked, and Cloud Governance as Code with Cloud Custodian for the compliance side.

How it flows flow1. Hostname map → 2. DNS → 3. Certificates → 4. SSL ruleset → 5. Rate-limit ruleset → 6. Gate: plan review → 7. Apply → 8. Cloud Armor → 9. Monitor01Hostname map02DNS03Certificates04SSL ruleset05Rate-limit ruleset06 · GATEGate: plan review07Apply08Cloud Armor09Monitor
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Hostname mapname, origin, SSL mode, rate-limit profile
  2. DNSproxied records generated from the map
  3. Certificatesvalidation records created automatically
  4. SSL rulesetper-host strict mode override
  5. Rate-limit rulesetprofiles expanded into expressions
  6. Gate: plan review gateedge changes are production changes
  7. Applypipeline with a scoped API token
  8. Cloud Armormatching throttle policy for direct paths
  9. Monitoranalytics and logs feed tuning
From hostname map to edge rules flow1. Hostname map → 2. DNS records → 3. Configuration rules → 4. Rate-limit profiles → 5. Gate: plan review → 6. Apply01Hostname map02DNS records03Configuration rules04Rate-limit profiles05 · GATEGate: plan review06Apply
From hostname map to edge rules. One data structure feeds DNS, SSL mode and throttling.
  1. Hostname mapname, origin, ssl, profile
  2. DNS recordsproxied A or CNAME per host
  3. Configuration rulesSSL mode per host expression
  4. Rate-limit profilesexpression, threshold, period, action
  5. Gate: plan review gateedge changes are production changes
  6. Applyscoped token, remote state
Source of truthHostname mapRate-limit profilesCloudflare edgeProxied DNSConfig rulesRate-limit rulesetCloud edgeCloud Armor policyrate_based_ban ruleOriginLoad balancerStrict TLSApplication
Two edges, one policy. The same thresholds apply on both paths to the origin.

// Before you start

  • A Cloudflare account with the zone added and an API token scoped to that zone (DNS edit, zone settings edit, ruleset edit).
  • Terraform 1.5+ and the cloudflare/cloudflare provider 4.x or 5.x (resource names differ between majors; check yours).
  • A Google Cloud project with a backend service behind a load balancer if you want the Cloud Armor half.
  • A rough baseline of legitimate request rates per path, from analytics, before choosing thresholds.
  • A CI pipeline with remote state and a protected environment for apply.
  • Origins serving a certificate that Cloudflare can validate before you enable strict mode for them.

// Step-by-step implementation

  1. 01 Describe hostnames and rate-limit profiles as data

    Put everything adjustable into variables with sensible defaults. The hostname map is the interface for teams; the profiles map is owned by the platform and changes rarely. Using objects with explicit fields avoids free-form strings becoming a second configuration language.

    Keep expressions out of the hostname map; reference a profile name instead, so a threshold change is one edit.

  2. 02 Generate proxied DNS records

    One record per host, proxied so traffic passes through the edge and the rules apply. Generate from the map so deleting a host from the map deletes its record, which is how cleanup actually happens.

    Use a short TTL only for unproxied records; proxied records ignore it.

  3. 03 Apply SSL mode per host with a configuration ruleset

    A ruleset in the http_config_settings phase can set SSL mode for requests matching an expression. Generate one rule per host that does not want the zone default. This is what lets you migrate to strict one hostname at a time: flip a value in the map, review the plan, apply.

    Write the expression on the exact host name to avoid substring matches catching another host.

  4. 04 Expand profiles into a rate-limiting ruleset

    The http_ratelimit phase holds rate-limit rules. Each profile becomes a rule: count by client IP, block (or challenge) for a timeout once the threshold is crossed. Combine the host expression with the profile expression so a profile only applies to the hosts that reference it.

    Start with the log action in a staging window to see who would have been blocked, then switch to block or managed_challenge.

  5. 05 Create certificate validation records alongside hosts

    If a hostname needs a certificate whose issuance validates over DNS, create the validation record in the same module as the host and key it by the same name. When the host leaves the map, its validation record goes with it; manual records are the ones that outlive their purpose.

    Many certificate managers output the record name and value; feed those in as variables from the issuing module.

  6. 06 Mirror the throttle policy in Cloud Armor

    Traffic that reaches the origin without passing through Cloudflare (internal clients, health checks, a forgotten direct hostname) should meet the same limits. Cloud Armor's rate_based_ban rule type expresses the same intent: count requests per client IP over an interval and ban for a duration.

    Reuse the same numbers by reading them from the profile variables so the two policies cannot drift apart silently. Also restrict the origin to accept traffic from Cloudflare ranges only, so the Cloudflare edge cannot be bypassed.

  7. 07 Scope the API token and run it through a pipeline

    The pipeline token should be able to edit exactly this zone: zone settings, DNS and rulesets, nothing account-wide and no billing. Store it as a CI secret and expose it only to the apply job in a protected environment. Plan runs with a read-only token on pull requests.

    Run terraform plan on every pull request and post the summary; edge changes are production changes and deserve review.

// How to verify it works

  • terraform plan after adding one host to the map shows one DNS record and one SSL rule (and no unrelated changes).
  • curl -sI https://app.example.com returns the expected headers through the edge, and the TLS check against the origin succeeds with strict mode.
  • A burst of requests above the threshold to /login returns 429 (or a challenge) and then recovers after the timeout; in log mode it only appears in analytics.
  • Direct requests to the origin address through the load balancer hit the Cloud Armor rule and return 429 above the same threshold.
  • terraform plan run again after apply shows no changes, proving nobody edited the dashboard in between.

// Design decisions and trade-offs

  • Zone settings, rulesets and DNS are all in Terraform; the dashboard is read-only for humans.
  • Per-host rules are generated from a map, so adding a hostname adds one DNS record and one rule entry.
  • Rate limits are expressed as data (path, threshold, period, action) and reviewed like any other change.
  • Strict SSL mode is applied by ruleset per host instead of one zone-wide setting, so migration is gradual.
  • The same policy intent is implemented in Cloud Armor for traffic that does not pass through Cloudflare.

// Pitfalls and lessons learned

  • Switching a host to strict before its origin presents a valid certificate yields 526 errors immediately; flip one host, check, then proceed.
  • Rate-limit counting by IP behind shared NATs (offices, mobile carriers) blocks legitimate users; add a header or session characteristic and prefer challenges over blocks for login paths.
  • Provider major versions rename resources and arguments (cloudflare_record vs cloudflare_dns_record, ruleset block syntax). Pin the version and upgrade deliberately.
  • Only one ruleset per phase and zone is the entry point; creating a second one for the same phase conflicts. Keep all rules for a phase in a single ruleset.
  • Validation records for certificate issuance must not be proxied.
  • If the origin accepts traffic from anywhere, attackers bypass the edge entirely; restrict the origin to Cloudflare ranges or authenticated origin pulls.
  • Importing existing dashboard rules into state before applying is essential, or the first apply will duplicate or delete them.

// Frequently asked questions

How do I configure Cloudflare rate limiting with Terraform?

Create a cloudflare_ruleset in the http_ratelimit phase with rules that include a ratelimit block (characteristics, period, requests_per_period, mitigation_timeout).

Can I set SSL strict mode for only some hostnames?

Yes, use a configuration ruleset (http_config_settings phase) with an expression matching the hostname and set the ssl parameter.

How do I import existing Cloudflare rules into Terraform?

Use terraform import with the zone id and ruleset id, then adjust the config until plan shows no changes before making edits.

Do I need Cloud Armor if I use Cloudflare?

Only if the origin can be reached some other way; restricting the origin to Cloudflare is better, and Cloud Armor then covers internal and direct paths.

What permissions does the API token need?

Zone read, DNS edit, zone settings edit and the ruleset permissions, scoped to the one zone.

// The outcome

Edge behaviour (SSL mode, throttling, DNS, certificate validation records) is declared, reviewed and reproducible, and adding a hostname is a small data change. The same throttling intent exists at both edges, so an attacker cannot simply pick the less protected one.

// Where to take it next

// Keep reading