### Handle Cloudflare API Errors Source: https://context7.com/socketry/cloudflare/llms.txt Implement error handling for Cloudflare API requests using the `RequestError` class. This example demonstrates how to catch and process API errors, including accessing detailed error messages and values. ```ruby require "cloudflare" Cloudflare.connect(token: token) do |connection| begin zone = connection.zones.find_by_name("example.com") # Attempt to create a duplicate DNS record zone.dns_records.create("A", "www", "192.0.2.1") rescue Cloudflare::RequestError => e puts "API Error: #{e.message}" puts "Error Details: #{e.value}" # e.value contains the full error response including error codes end end ``` -------------------------------- ### Retrieve Cloudflare IP Ranges Source: https://context7.com/socketry/cloudflare/llms.txt Get Cloudflare's IP ranges (CIDRs) for firewall configuration. This function allows fetching all IPv4 and IPv6 ranges, or specific ones based on the IP version. ```ruby Cloudflare.connect(token: token) do |connection| # Get all Cloudflare IP CIDRs (IPv4 and IPv6) all_cidrs = connection.cidrs puts "All Cloudflare IPs: #{all_cidrs}" # Get only IPv4 CIDRs ipv4_cidrs = connection.cidrs(ipv: 4) puts "IPv4 ranges: #{ipv4_cidrs}" # Get only IPv6 CIDRs ipv6_cidrs = connection.cidrs(ipv: 6) puts "IPv6 ranges: #{ipv6_cidrs}" end ``` -------------------------------- ### Establishing a Connection Source: https://context7.com/socketry/cloudflare/llms.txt Demonstrates how to establish an authenticated connection to the Cloudflare API using different authentication methods and connection management styles. ```APIDOC ## Establishing a Connection ### Description Connect to the Cloudflare API using API keys, tokens, or manual async management. ### Method `Cloudflare.connect` ### Parameters #### Block Style (Auto-closes connection) - **key** (String) - Optional - Your Cloudflare API key. - **email** (String) - Optional - Your Cloudflare account email (required if using API key). - **token** (String) - Optional - Your Cloudflare API token (bearer token). #### Manual Async Management - **key** (String) - Optional - Your Cloudflare API key. - **email** (String) - Optional - Your Cloudflare account email (required if using API key). - **token** (String) - Optional - Your Cloudflare API token (bearer token). ### Request Example (API Key & Email) ```ruby require "cloudflare" email = ENV["CLOUDFLARE_EMAIL"] key = ENV["CLOUDFLARE_KEY"] Cloudflare.connect(key: key, email: email) do |connection| # Work with the connection zones = connection.zones puts "Connected successfully, found #{zones.count} zones" end ``` ### Request Example (Bearer Token) ```ruby require "cloudflare" token = ENV["CLOUDFLARE_TOKEN"] Cloudflare.connect(token: token) do |connection| user = connection.user puts "Authenticated as: #{user.email}" end ``` ### Request Example (Manual Async) ```ruby require "async" Async do connection = Cloudflare.connect(token: ENV["CLOUDFLARE_TOKEN"]) begin zones = connection.zones zones.each { |zone| puts zone.name } ensure connection.close end end ``` ### Response #### Success Response (Connection Object) - **connection** (Object) - An authenticated connection object to interact with the API. #### Error Response - **error** (Object) - Details about the authentication failure. ``` -------------------------------- ### Manage Cloudflare Custom Hostnames (SSL for SaaS) Source: https://context7.com/socketry/cloudflare/llms.txt This snippet shows how to manage custom hostnames for SSL for SaaS. It includes creating hostnames with HTTP validation, checking SSL status, updating settings, and deleting hostnames. Requires a Cloudflare connection and zone object. ```ruby Cloudflare.connect(token: token) do |connection| zone = connection.zones.find_by_name("example.com") custom_hostnames = zone.custom_hostnames # Create a custom hostname with HTTP validation hostname = custom_hostnames.create( "app.customer.com", ssl: { method: "http", type: "dv" }, origin: "origin.example.com", metadata: { customer_id: "12345" } ) puts "Created hostname: #{hostname.hostname} (ID: #{hostname.id})" # Check SSL status puts "SSL Status: #{hostname.ssl.status}" puts "SSL Active: #{hostname.ssl.active?}" # Get validation info for pending certificates if hostname.ssl.pending_validation? puts "HTTP Validation URL: #{hostname.ssl.http_url}" puts "HTTP Validation Body: #{hostname.ssl.http_body}" puts "CNAME Target: #{hostname.ssl.cname_target}" end # Force SSL validation check (triggers Cloudflare to re-check) hostname.ssl_active?(true) # Update hostname settings hostname.update_settings( origin: "new-origin.example.com", ssl: { method: "cname", type: "dv" }, metadata: { customer_id: "12345", tier: "premium" } ) # Access SSL settings settings = hostname.ssl.settings puts "Min TLS Version: #{settings.min_tls_version}" puts "TLS 1.3 Enabled: #{settings.tls_1_3?}" # Configure SSL settings settings.min_tls_version = "1.2" settings.tls_1_3 = true settings.http2 = true # Find hostname by name hostname = custom_hostnames.find_by_hostname("app.customer.com") # Delete a custom hostname hostname.delete end ``` -------------------------------- ### Managing Zones Source: https://context7.com/socketry/cloudflare/llms.txt Provides functionality to list, find, create, purge cache, and delete DNS zones associated with your Cloudflare account. ```APIDOC ## Managing Zones ### Description Interact with DNS zones, including listing, finding, creating, and managing zone-specific operations like cache purging. ### Method `connection.zones` ### Endpoint `/zones` ### Parameters #### Query Parameters - **name** (String) - Optional - Filter zones by name. - **status** (String) - Optional - Filter zones by status (e.g., "active"). ### Request Example (Iterate Zones) ```ruby Cloudflare.connect(token: token) do |connection| zones = connection.zones zones.each do |zone| puts "Zone: #{zone.name} (ID: #{zone.result[:id]})" end end ``` ### Request Example (Find Zone) ```ruby Cloudflare.connect(token: token) do |connection| zone = connection.zones.find_by_name("example.com") puts "Found zone: #{zone.name}" zone = connection.zones.find_by_id("023e105f4ecef8ad9ca31a8372d0c353") end ``` ### Request Example (Create Zone) ```ruby Cloudflare.connect(token: token) do |connection| account = connection.accounts.first new_zone = connection.zones.create("newdomain.com", account, jump_start: true) puts "Created zone: #{new_zone.name}" end ``` ### Request Example (Purge Cache) ```ruby Cloudflare.connect(token: token) do |connection| zone = connection.zones.find_by_name("example.com") zone.purge_cache # Purge everything zone.purge_cache(files: ["https://example.com/style.css"]) # Selective purge end ``` ### Request Example (Activation Check & Delete) ```ruby Cloudflare.connect(token: token) do |connection| zone = connection.zones.find_by_name("example.com") zone.activation_check zone.delete end ``` ### Response #### Success Response (Zone Object) - **id** (String) - The unique identifier for the zone. - **name** (String) - The domain name of the zone. - **status** (String) - The current status of the zone (e.g., "active"). - **result** (Object) - Additional details about the zone. #### Error Response - **error** (Object) - Details about the error during zone operation. ``` -------------------------------- ### Connect to Cloudflare with Bearer Token (Ruby) Source: https://github.com/socketry/cloudflare/blob/main/readme.md Shows how to establish a connection to the Cloudflare API using a bearer token for authentication. This method allows for more granular control over API privileges. ```ruby require "cloudflare" token = "a_generated_api_token" Cloudflare.connect(token: token) do |connection| # ... end ``` -------------------------------- ### Connect and Manage Cloudflare Zones and DNS Records (Ruby) Source: https://github.com/socketry/cloudflare/blob/main/readme.md Demonstrates how to connect to the Cloudflare API using email and API key, retrieve zone information, manage DNS records, and block IP addresses using firewall rules. Requires CLOUDFLARE_EMAIL and CLOUDFLARE_KEY environment variables. ```ruby require "cloudflare" # Grab some details from somewhere: 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: zone = connection.zones.find_by_id("...") zone = connection.zones.find_by_name("example.com") # Get DNS records for a given zone: dns_records = zone.dns_records # Show some details of the DNS record: dns_record = dns_records.first puts dns_record.name # Add a DNS record. Here we add an A record for `batman.example.com`: zone = zones.find_by_name("example.com") zone.dns_records.create("A", "batman", "1.2.3.4", proxied: false) # 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 ``` -------------------------------- ### Manage Cloudflare Workers KV Storage Source: https://context7.com/socketry/cloudflare/llms.txt This snippet demonstrates interacting with Cloudflare Workers KV storage. It covers creating, finding, writing, reading, listing keys, renaming, and deleting KV namespaces and their values. Requires a Cloudflare connection and account object. ```ruby Cloudflare.connect(token: token) do |connection| account = connection.accounts.first kv_namespaces = account.kv_namespaces # Create a new namespace namespace = kv_namespaces.create("my-application-data") puts "Created namespace: #{namespace.title} (ID: #{namespace.id})" # Find namespace by title namespace = kv_namespaces.find_by_title("my-application-data") # Write a value success = namespace.write_value("user:123", '{"name": "John", "email": "john@example.com"}') puts "Write successful: #{success}" # Read a value data = namespace.read_value("user:123") puts "Retrieved: #{data}" # List all keys in the namespace namespace.keys.each do |key| puts "Key: #{key.name}" end # Delete a value namespace.delete_value("user:123") # Rename the namespace namespace.rename("production-app-data") # Delete the namespace namespace.delete end ``` -------------------------------- ### Paginate Cloudflare API Collections Source: https://context7.com/socketry/cloudflare/llms.txt Utilize the `Paginate` module for automatic pagination of collection endpoints. This allows for default pagination, custom parameter settings, checking for empty collections, and lazy evaluation using enumerators. ```ruby Cloudflare.connect(token: token) do |connection| zones = connection.zones # Default pagination (page 1, 50 per page) zones.each { |zone| puts zone.name } # Custom pagination parameters zones.each(page: 2, per_page: 10) do |zone| puts zone.name end # Check if collection is empty puts "No zones found" if zones.empty? # Get enumerator for lazy evaluation zone_enum = zones.each first_five = zone_enum.take(5) end ``` -------------------------------- ### Connect to Cloudflare API (Ruby) Source: https://context7.com/socketry/cloudflare/llms.txt Establishes an authenticated connection to the Cloudflare API using API key/email or bearer token. Supports block-style usage for automatic connection closing and manual management for async workflows. ```ruby require "cloudflare" # Using API key and email authentication email = ENV["CLOUDFLARE_EMAIL"] key = ENV["CLOUDFLARE_KEY"] Cloudflare.connect(key: key, email: email) do |connection| # Work with the connection zones = connection.zones puts "Connected successfully, found #{zones.count} zones" end # Using Bearer token authentication (recommended for limited privileges) token = ENV["CLOUDFLARE_TOKEN"] Cloudflare.connect(token: token) do |connection| user = connection.user puts "Authenticated as: #{user.email}" end # Manual connection management with Async require "async" Async do connection = Cloudflare.connect(token: ENV["CLOUDFLARE_TOKEN"]) begin zones = connection.zones zones.each { |zone| puts zone.name } ensure connection.close end end ``` -------------------------------- ### Asynchronous Cloudflare Connection (Ruby) Source: https://github.com/socketry/cloudflare/blob/main/readme.md Illustrates how to use the Cloudflare gem within an asynchronous execution context. This is useful for non-blocking I/O operations. Ensures the connection is closed properly. ```ruby Async do connection = Cloudflare.connect # ... do something with connection ... ensure connection.close end ``` -------------------------------- ### Manage Cloudflare Accounts Source: https://context7.com/socketry/cloudflare/llms.txt This snippet shows how to access and manage Cloudflare accounts associated with your credentials. It covers listing all accounts and accessing account-level resources like KV namespaces. Requires a Cloudflare connection object. ```ruby Cloudflare.connect(token: token) do |connection| accounts = connection.accounts # List all accounts accounts.each do |account| puts "Account ID: #{account.id}" puts "Account Details: #{account.result}" end # Get the first account (useful for single-account setups) account = accounts.first # Access account-level resources kv_namespaces = account.kv_namespaces end ``` -------------------------------- ### Manage Cloudflare Origin Certificates Source: https://context7.com/socketry/cloudflare/llms.txt Create and manage Cloudflare Origin CA certificates for secure communication. This involves connecting to the Cloudflare API, listing existing certificates, and creating new ones using a CSR in PEM format. ```ruby Cloudflare.connect(token: token) do |connection| certificates = connection.certificates # List all certificates certificates.each do |cert| puts "Certificate: #{cert.certificate}" end # Create a new origin certificate csr_pem = <<~CSR -----BEGIN CERTIFICATE REQUEST----- MIICijCCAXICAQAwRTELMAkGA1UEBhMCVVMx... -----END CERTIFICATE REQUEST----- CSR cert = certificates.create( csr_pem, ["example.com", "*.example.com"], "origin-rsa", # request_type: origin-rsa or origin-ecc 5475 # validity in days (default: 15 years) ) puts "New Certificate:\n#{cert.certificate}" end ``` -------------------------------- ### Manage Cloudflare Firewall Rules Source: https://context7.com/socketry/cloudflare/llms.txt This snippet demonstrates how to manage firewall rules for a Cloudflare zone. It covers listing, blocking, challenging, whitelisting IPs, and deleting rules. Requires a Cloudflare connection object and a zone name. ```ruby Cloudflare.connect(token: token) do |connection| zone = connection.zones.find_by_name("example.com") firewall_rules = zone.firewall_rules # List all firewall rules firewall_rules.each do |rule| puts "#{rule.configuration[:value]} - #{rule.mode} - #{rule.notes}" end # Block an IP address rule = firewall_rules.set("block", "203.0.113.50", notes: "SSH brute force attack") puts "Blocked: #{rule}" # Challenge an IP (CAPTCHA) firewall_rules.set("challenge", "198.51.100.0/24", notes: "Suspicious activity from subnet") # Whitelist a trusted IP firewall_rules.set("whitelist", "10.0.0.1", notes: "Office IP") # JavaScript challenge firewall_rules.set("js_challenge", "192.0.2.100", notes: "Bot mitigation") # Find rules by IP value firewall_rules.each_by_value("203.0.113.50") do |rule| puts "Found rule: #{rule.mode} - #{rule.notes}" rule.delete # Remove the rule end end ``` -------------------------------- ### Manage Cloudflare Zones (Ruby) Source: https://context7.com/socketry/cloudflare/llms.txt Provides functionality to manage Cloudflare zones, including iterating through all zones with automatic pagination, finding zones by name or ID, creating new zones, purging cache (all or selective), triggering activation checks, and deleting zones. ```ruby Cloudflare.connect(token: token) do |connection| zones = connection.zones # Iterate through all zones with automatic pagination zones.each do |zone| puts "Zone: #{zone.name} (ID: #{zone.result[:id]})" end # Find a specific zone by name zone = zones.find_by_name("example.com") puts "Found zone: #{zone.name}" # Find a zone by ID zone = zones.find_by_id("023e105f4ecef8ad9ca31a8372d0c353") # Create a new zone (requires account reference) account = connection.accounts.first new_zone = zones.create("newdomain.com", account, jump_start: true) puts "Created zone: #{new_zone.name}" # Purge zone cache zone.purge_cache # Purge everything zone.purge_cache(files: ["https://example.com/style.css"]) # Selective purge # Trigger activation check zone.activation_check # Delete a zone zone.delete end ``` -------------------------------- ### DNS Records Management Source: https://context7.com/socketry/cloudflare/llms.txt Manage DNS records within a zone, including creating, retrieving, updating, and deleting various record types. ```APIDOC ## DNS Records Management ### Description Perform CRUD operations on DNS records for a given zone, supporting all standard record types and options. ### Method `zone.dns_records` ### Endpoint `/zones/:zone_id/dns_records` ### Parameters #### Query Parameters - **type** (String) - Optional - Filter records by type (e.g., "A", "CNAME"). - **name** (String) - Optional - Filter records by name. ### Request Example (List Records) ```ruby Cloudflare.connect(token: token) do |connection| zone = connection.zones.find_by_name("example.com") dns_records = zone.dns_records dns_records.each do |record| puts "#{record.name} #{record.type} #{record.content} (proxied: #{record.proxied?})" end end ``` ### Request Example (Create Records) ```ruby Cloudflare.connect(token: token) do |connection| zone = connection.zones.find_by_name("example.com") dns_records = zone.dns_records # Create an A record record = dns_records.create("A", "www", "192.0.2.1", proxied: true, ttl: 1) puts "Created: #{record.name} -> #{record.content}" # Create a CNAME record dns_records.create("CNAME", "blog", "www.example.com", proxied: true) # Create an MX record dns_records.create("MX", "example.com", "mail.example.com", priority: 10) # Create a TXT record for SPF dns_records.create("TXT", "example.com", "v=spf1 include:_spf.google.com ~all") end ``` ### Request Example (Find, Update, Delete Record) ```ruby Cloudflare.connect(token: token) do |connection| zone = connection.zones.find_by_name("example.com") dns_records = zone.dns_records record = dns_records.find_by_name("www.example.com") # Update a record's content record.update_content("192.0.2.2", proxied: false, ttl: 3600) # Delete a record record.delete end ``` ### Response #### Success Response (DNS Record Object) - **id** (String) - The unique identifier for the DNS record. - **type** (String) - The type of DNS record (e.g., "A", "CNAME"). - **name** (String) - The name of the DNS record. - **content** (String) - The content or value of the DNS record. - **proxied** (Boolean) - Whether the record is proxied through Cloudflare. - **ttl** (Integer) - The Time To Live for the record. - **priority** (Integer) - The priority for MX records. #### Error Response - **error** (Object) - Details about the error during DNS record operation. ``` -------------------------------- ### Manage Cloudflare DNS Records (Ruby) Source: https://context7.com/socketry/cloudflare/llms.txt Enables full CRUD operations for DNS records within a Cloudflare zone, supporting all record types (A, AAAA, CNAME, MX, TXT, etc.). Allows creating proxied or unproxied records, updating content, and deleting records. ```ruby Cloudflare.connect(token: token) do |connection| zone = connection.zones.find_by_name("example.com") dns_records = zone.dns_records # List all DNS records with pagination dns_records.each do |record| puts "#{record.name} #{record.type} #{record.content} (proxied: #{record.proxied?})" end # Create an A record record = dns_records.create("A", "www", "192.0.2.1", proxied: true, ttl: 1) puts "Created: #{record.name} -> #{record.content}" # Create a CNAME record dns_records.create("CNAME", "blog", "www.example.com", proxied: true) # Create an MX record dns_records.create("MX", "example.com", "mail.example.com", priority: 10) # Create a TXT record for SPF dns_records.create("TXT", "example.com", "v=spf1 include:_spf.google.com ~all") # Find a record by name record = dns_records.find_by_name("www.example.com") # Update a record's content record.update_content("192.0.2.2", proxied: false, ttl: 3600) # Delete a record record.delete end ``` -------------------------------- ### Access Zone Logs Source: https://context7.com/socketry/cloudflare/llms.txt Access and iterate through zone logs for traffic analysis and debugging. This involves finding a specific zone by name and then processing its log entries. ```ruby Cloudflare.connect(token: token) do |connection| zone = connection.zones.find_by_name("example.com") logs = zone.logs # Iterate through log entries logs.each do |entry| puts "Log Entry: #{entry}" # Format: rayid-ClientRequestURI puts "Full data: #{entry.result}" end end ``` -------------------------------- ### Retrieve Cloudflare User Information Source: https://context7.com/socketry/cloudflare/llms.txt This snippet demonstrates how to retrieve information about the authenticated Cloudflare user. It displays the user's ID, email, and full details. Requires a Cloudflare connection object. ```ruby Cloudflare.connect(token: token) do |connection| user = connection.user puts "User ID: #{user.id}" puts "Email: #{user.email}" puts "Full Details: #{user.result}" end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.