Mastering Cloudflare Ruleset Engine with Terraform
Tags: terraform, iac, cloudflare, security
Published: 2024-06-15 09:18:47

In this post, we'll learn about Cloudflare Ruleset Engine, a powerful tool for creating and deploying complex rules across various Cloudflare products. We'll explore its key elements, types of rulesets, and few examples on how to deploy them using Terraform.

## Introduction to Cloudflare Ruleset Engine

The **Cloudflare Ruleset Engine** allows you to create and deploy rules and rulesets using [Wireshark Display Filter language syntax](https://www.wireshark.org/docs/wsug_html_chunked/ChWorkBuildDisplayFilterSection.html), offering precise control over request handling to enhance traffic management across the Cloudflare global network.

## Functionalities of Cloudflare Ruleset Engine
- **Versatile Rule Creation**: Easily create and deploy rules using a syntax based on the wirefilter language, enabling advanced traffic management across various Cloudflare products.
- **Performance Efficiency**: Allows you to use numerous rules across different Cloudflare products with minimal impact on performance.
- **Comprehensive Integration**: Seamlessly integrates into multiple Cloudflare products, providing a unified configuration approach and supporting various request lifecycle phases
- **Unified API**: Access consistent API methods for configuring different products, streamlining customization and integration within the Cloudflare ecosystem.
- **Broad Availability**: Compatible with numerous Cloudflare products, with detailed availability information provided in each product’s documentation

### Key Elements of the Ruleset Engine

1. **Phases**: A phase represents a stage in the request-handling process where you can apply rulesets, occurring at both the account and zone levels. If rules are set for the same phase, those at the account level take precedence over zone-level rules. Currently, phases at the account level are only available in Enterprise plans.[Learn more about phases](https://developers.cloudflare.com/ruleset-engine/about/phases/).

2. **Rules**: A rule acts as a filter for your website traffic, where you define conditions (filter expressions) based on specific details in requests, such as URLs or headers. When a request matches a rule's condition, an action is triggered, like blocking traffic or redirecting website addresses. If there's no match, the rule is ignored, and traffic flows normally. Additionally, field values remain immutable within phases during rule evaluation but may change between phases. [Learn more about rules](https://developers.cloudflare.com/ruleset-engine/about/rules/). 

3. **Rulesets**: A collection of ordered rules that filter and manage website traffic on Cloudflare's global network. Rulesets belong to a phase and can only execute within the same phase. Each modification creates a new version, with Cloudflare using the latest version by default. [Learn more about Rulesets Documentation](https://developers.cloudflare.com/ruleset-engine/managed-rulesets/#get-started)

### Types of Rulesets
- **Phase Entry Point Ruleset**: An entry point ruleset, found at the account or zone level, contains ordered rules that initiate all rules in a phase. It may trigger other rulesets. Each phase has one entry point ruleset at the account or zone level, marked by 'root' or 'zone' respectively.
  
- **Managed Rulesets**: Managed rulesets are preconfigured by Cloudflare for deployment to a phase, with only Cloudflare able to modify them. They come with default actions and status, but you can customize them with overrides. Various Cloudflare products offer managed rulesets; refer to each product's documentation for details.

- **Custom Rulesets**: Custom rulesets are currently supported only by the Cloudflare WAF. They enable you to define your own sets of rules and deploy them to a phase by creating a rule that executes the ruleset.

## Listing and Viewing Rulesets
To view rulesets deployed in your Cloudflare account or zone, you'll need to utilize the Cloudflare API, as the Cloudflare console doesn't provide this functionality. This section is crucial because Terraform assumes full control over deployed rulesets in phases. If any rules are manually deployed to a phase, deploying them using Terraform could lead to conflicts.

### Example API request:
```
curl https://api.cloudflare.com/client/v4/zones/{zone_id}/rulesets \
--header "Authorization: Bearer <API_TOKEN>"
```

If there are rules defined at specific phases, you can import them using [Terraform import](https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/ruleset#:~:text=the%20current%20request.-,Import,-Import%20is%20supported).

## Implementing Cloudflare Rulesets with Terraform

Now, let's move on to the practical part—using Terraform to manage and deploy these rulesets.

### Prerequisites

1. **Install Terraform**: Ensure Terraform is installed on your system.
2. **Cloudflare Account**: Set up your Cloudflare account and generate API credentials.

### Introduction to the Module

The [Terraform Cloudflare Rulesets module](https://github.com/terrasible/terraform-cloudflare-rulesets) simplifies the deployment and management of Cloudflare rulesets. It enables defining rulesets as code, ensuring consistency and ease of management across various environments. The module exposes all necessary attributes to configure rules for any Cloudflare product, whether at the account or zone level.

#### Key Features

1. **Simplified Zone Identification**: Pass the `zone_name` instead of `zone_id`; the module fetches the `zone_id` for you.
2. **Account-Level Configuration**: Supports configuring rulesets at the account level.
3. **Flexible Ruleset Creation**: Create and deploy multiple ruleset engines according to your needs.
4. **Ease of Use**: Requires only three variables:
   - `zone_name`: The zone for which to create the ruleset.
   - `phase`: The point in the request/response lifecycle where the ruleset will be applied.
   - `ruleset_name`: Name of the ruleset.

#### Example: Ruleset Engine Terraform Configuration Without Rules

```hcl
terraform {
  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 4.0"
    }
  }
  required_version = ">= 1.8"
}

module "rulesets_example_zone-level-custom-waf" {
  source       = "terrasible/rulesets/cloudflare"
  version      = "0.3.0"
  zone_name    = "terrasible.com"
  ruleset_name = "my custom waf ruleset"
  kind         = "zone"
  phase        = "http_request_firewall_custom"
}
```

#### Example: Ruleset Engine Terraform Configuration With Rules

```hcl
terraform {
  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 4.0"
    }
  }
  required_version = ">= 1.8"
}

module "rulesets_example_zone-level-custom-waf" {
  source       = "terrasible/rulesets/cloudflare"
  version      = "0.3.0"
  zone_name    = "terrasible.com"
  ruleset_name = "my custom waf ruleset"
  description  = "Block request from source IP and execute Cloudflare Managed Ruleset on my zone-level phase entry point ruleset"
  kind         = "zone"
  phase        = "http_request_firewall_custom"

  rules = [
    {
      action      = "block"
      expression  = "(http.host eq \"prod.example.com\" and ip.src in {34.56.xx.xx/32 34.67.xx.xx/32})"
      description = "Block request from source IP"
      enabled     = true
      action_parameters = {
        response = [
          {
            content      = <<-EOT
                <!DOCTYPE html>
                <html lang="en">
                <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Access Denied</title>
                </head>
                <body style="background-color: Brown;">
                <h1>Ooops! You are not allowed to access this page.</h1>
                </body>
                </html>
              EOT
            content_type = "text/html"
            status_code  = 403
          }
        ]
      }
    },
  ]
}
```

By using the module, you can streamline your Cloudflare ruleset management, ensuring consistent and efficient traffic control across your infrastructure. For practical examples of managing complex rules in your environment, check out the [examples folder](https://github.com/terrasible/terraform-cloudflare-rulesets/tree/master/examples).


## Conclusion

You've now learned about Cloudflare Ruleset Engine and how to implement and manage rulesets using Terraform. By leveraging these tools, you can enhance the performance and security of your web traffic management. 

Feel free to explore more on the [Cloudflare Developer Documentation](https://developers.cloudflare.com/ruleset-engine/) and the [Terraform Registry](https://registry.terraform.io/providers/cloudflare/cloudflare/latest).