Cloudflare Ruby Wrapper

repository·main·Indexed 41 days ago

https://github.com/socketry/cloudflare

A lightweight Ruby wrapper for the Cloudflare V4 API built using RestClient::Resource. It provides tools to manage Cloudflare Zones, DNS records, Firewall rules, Accounts, KV namespaces, and Custom Hostnames. Supports authentication via Bearer Tokens, Global API Keys with email, or User Service Keys, and integrates with the async gem for connection lifecycle management.

Tokens
6.2K
Snippets
29
Records
31
Agent score
100%

What's inside cloudflare

  1. Install the cloudflare gem

    main

    You can install the cloudflare gem using Bundler by adding it to your Gemfile, or by installing it directly via the command line.

    # Add to Gemfile
    gem "cloudflare"

    Or install via CLI

    $ gem install cloudflare

    Then run

    $ bundle

  2. Manage Zones and DNS Records

    main

    The Cloudflare wrapper allows you to interact with your zones and their associated DNS records.

    Key operations include:

    • List all zones: connection.zones
    • Find a zone: Use find_by_id("...") or find_by_name("example.com") on the zones collection.
    • List DNS records: Access zone.dns_records.
    • Create a DNS record: Use zone.dns_records.create(type, name, content, options).

    Example of creating an A record:

    zone.dns_records.create("A", "batman", "1.2.3.4", proxied: false)
    require "cloudflare"
    
    email = ENV["CLOUDFLARE_EMAIL"]
    key = ENV["CLOUDFLARE_KEY"]
    
    Cloudflare.connect(key: key, email: email) do |connection|
      # Get all available zones
      zones = connection.zones
      
      # Get a specific zone by name
      zone = connection.zones.find_by_name("example.com")
      
      # Get DNS records for a given zone
      dns_records = zone.dns_records
      
      # Add a DNS record (A record for batman.example.com)
      zone.dns_records.create("A", "batman", "1.2.3.4", proxied: false)
    end
  3. Manage Firewall Rules

    main

    You can manage firewall rules at the zone level.

    Key operations include:

    • List firewall rules: zone.firewall_rules
    • Set/Block an IP: Use zone.firewall_rules.set(action, ip, options).

    Example of blocking an IP:

    rule = zone.firewall_rules.set("block", "1.2.3.4", notes: "ssh dictionary attack")
    require "cloudflare"
    
    email = ENV["CLOUDFLARE_EMAIL"]
    key = ENV["CLOUDFLARE_KEY"]
    
    Cloudflare.connect(key: key, email: email) do |connection|
      zone = connection.zones.find_by_name("example.com")
      
      # Get firewall rules
      all_rules = zone.firewall_rules
      
      # Block an ip
      rule = zone.firewall_rules.set("block", "1.2.3.4", notes: "ssh dictionary attack")
    end
  4. Connect to Cloudflare using Async

    main

    If you are using the async gem, you can manage the connection lifecycle manually within an Async block. Ensure you call connection.close in an ensure block to prevent resource leaks.

    Async do
      connection = Cloudflare.connect
      
      # ... do something with connection ...
    ensure
      connection.close
    end
  5. Connect to Cloudflare using Email and API Key

    main

    To use the wrapper with traditional Cloudflare credentials, use Cloudflare.connect providing your email and key. It is recommended to use environment variables for security.

    require "cloudflare"
    
    email = ENV["CLOUDFLARE_EMAIL"]
    key = ENV["CLOUDFLARE_KEY"]
    
    Cloudflare.connect(key: key, email: email) do |connection|
      # Use the connection object here
    end
  6. Connect to Cloudflare using a Bearer Token

    main

    For better security and limited privileges, you can connect using a Cloudflare API Bearer Token instead of an email/key pair.

    require "cloudflare"
    
    token = "a_generated_api_token"
    
    Cloudflare.connect(token: token) do |connection|
      # Use the connection object here
    end
  7. Interact with a CustomHostname resource

    main

    A Cloudflare::CustomHostname instance represents a single custom hostname resource.

    Available Attributes

    • id: The unique identifier for the hostname.
    • hostname: The hostname string (also accessible via .to_s).
    • custom_origin: Returns the custom origin server (only available if enabled for your zone).
    • custom_metadata: Returns custom metadata (only available if enabled for your zone).
    • ssl: Returns an SSLAttribute object containing SSL configuration.

    Updating Settings

    Use update_settings to modify the hostname's configuration. You can update metadata, origin, or ssl settings via a single call.

    Validating SSL Certificates

    Use ssl_active?(force_update: true) to check if the SSL certificate is active. If force_update is set to true and the certificate is currently in a pending_validation? state, the client will send a request to Cloudflare to trigger a re-validation attempt.

    # Accessing attributes
    puts hostname.id
    puts hostname.hostname
    
    # Updating settings
    hostname.update_settings(
      metadata: { "app": "api" },
      origin: "new-origin.example.com"
    )
    
    # Checking and forcing SSL validation
    if hostname.ssl_active?(true)
      puts "SSL is active!"
    end
  8. Configure SSL settings for Cloudflare custom hostnames

    main

    The Cloudflare::CustomHostname::SSLAttribute::Settings class is used to manage SSL-related configuration for custom hostnames. It allows you to control cipher suites, HTTP/2 support, minimum TLS versions, and TLS 1.3 support.

    Key Attributes

    • ciphers: A list of allowed cipher suites.
    • http2: Enables or disables HTTP/2. Use the http2? predicate to check the status.
    • min_tls_version: Sets the minimum allowed TLS version.
    • tls_1_3: Enables or disables TLS 1.3. Use the tls_1_3? predicate to check the status.

    Boolean Handling

    When setting boolean values (http2= or tls_1_3=), the class internally maps them to Cloudflare's expected string values ("on" or "off"). If you pass nil, the key is removed from the settings entirely. To check the current state, use the predicate methods http2? and tls_1_3?, which return true only if the value is exactly "on".

    # Initialize settings
    ssl_settings = Cloudflare::CustomHostname::SSLAttribute::Settings.new
    
    # Configure attributes
    ssl_settings.ciphers = ["TLS_AES_128_GCM_SHA256"]
    ssl_settings.http2 = true
    ssl_settings.tls_1_3 = true
    ssl_settings.min_tls_version = "1.2"
    
    # Check status using predicates
    puts ssl_settings.http2?   # => true
    puts ssl_settings.tls_1_3? # => true
  9. Create a new DNS record

    main

    Use the create method on a Cloudflare::DNS::Records collection instance to add a new DNS record to a zone. This method performs a POST request. It returns a new Cloudflare::DNS::Record instance representing the created record.

    # Assuming 'records' is an instance of Cloudflare::DNS::Records
    new_record = records.create('A', 'batman.example.com', '1.2.3.4', proxied: true)
  10. Connect to Cloudflare using Cloudflare.connect

    main

    Use Cloudflare.connect to establish a connection to the Cloudflare API. This method supports both block-based usage (which automatically closes the connection when the block finishes) and manual connection management.

    Authentication can be provided via keyword arguments (e.g., token:, email:, api_key:). If a block is provided, the connection is wrapped in an Async sync block to handle asynchronous operations and ensures the connection is closed in an ensure block.

    # Block-based usage (recommended: automatically closes connection)
    Cloudflare.connect(token: 'YOUR_TOKEN') do |connection|
      # Use connection here
    end
    
    # Manual usage
    connection = Cloudflare.connect(token: 'YOUR_TOKEN')
    # ... use connection ...
    connection.close
  11. Read, write, and delete values in Cloudflare KV

    main

    Within a Cloudflare::KV::Namespace, you can manage individual key-value pairs using the following methods:

    • write_value(name, value): Stores a value at the specified name.
    • read_value(name): Retrieves the value associated with the given name.
    • delete_value(name): Removes the value associated with the given name.
    namespace = Cloudflare::KV::Namespaces.new(resource).find_by_title("my-namespace")
    
    # Write a value
    namespace.write_value("my_key", "my_value")
    
    # Read a value
    val = namespace.read_value("my_key")
    
    # Delete a value
    namespace.delete_value("my_key")
  12. Authenticate a Cloudflare connection

    main

    To interact with the Cloudflare API, you must create an authenticated Cloudflare::Connection instance. The authenticated method supports three authentication patterns:

    1. Bearer Token: Use the token: keyword argument.
    2. Global API Key with Email: Use both key: and email: keyword arguments.
    3. User Service Key: Use the key: keyword argument without an email.

    The method returns a new connection instance configured with the appropriate headers.

    # Using a Bearer Token
    connection = Cloudflare::Connection.authenticated(token: 'YOUR_TOKEN')
    
    # Using Global API Key and Email
    connection = Cloudflare::Connection.authenticated(key: 'YOUR_API_KEY', email: 'user@example.com')
    
    # Using a User Service Key
    connection = Cloudflare::Connection.authenticated(key: 'YOUR_SERVICE_KEY')