CloudflareWorkers, caching and APIguide
Extending your Terraform configuration with the http provider
A Terraform provider that has not implemented pagination for a data source leaves you with the first page only. The cloudflare_accounts data source in provider 4.5.2 is one of those: the API (application programming interface) returns 20 items by default and the provider hands back exactly that. This guide calls the API directly through the hashicorp/http provider and folds the pages back together in locals, on any 4.x provider, because the pagination is done in the data sources rather than the provider.
# 1. Configure required providersterraform { required_providers { http = { source = "hashicorp/http" version = "~> 3.0" } cloudflare = { source = "cloudflare/cloudflare" version = "~> 4.0" } }}
# 2. Declare the API token variablevariable "cloudflare_api_token" { description = "Cloudflare API Token with Account Settings read permissions" type = string sensitive = true}
# 3. Configure the Cloudflare provider (optional, only if using Cloudflare resources)provider "cloudflare" { api_token = var.cloudflare_api_token}
# 4. Fetch first page of accounts (50 per page)data "http" "first_page" { url = "https://api.cloudflare.com/client/v4/accounts?per_page=50"
request_headers = { "Authorization" = "Bearer ${var.cloudflare_api_token}" "Content-Type" = "application/json" }}
# 5. Parse response and calculate paginationlocals { first_response = jsondecode(data.http.first_page.response_body)
# Check if request was successful success = try(local.first_response.success, false) first_results = local.success ? try(local.first_response.result, []) : [] total_pages = local.success ? try(local.first_response.result_info.total_pages, 1) : 0
# Create list of remaining pages (2, 3, 4, etc.) remaining_pages = local.total_pages > 1 ? range(2, local.total_pages + 1) : []}
# 6. Fetch remaining pages if neededdata "http" "remaining_pages" { for_each = local.success ? toset([for p in local.remaining_pages : tostring(p)]) : toset([])
url = "https://api.cloudflare.com/client/v4/accounts?page=${each.value}&per_page=50"
request_headers = { "Authorization" = "Bearer ${var.cloudflare_api_token}" "Content-Type" = "application/json" }}
# 7. Combine all resultslocals { remaining_results = flatten([ for page in data.http.remaining_pages : try(jsondecode(page.response_body).result, []) ])
# All accounts combined all_accounts = concat(local.first_results, local.remaining_results)
# Create lookup maps for easy access accounts_by_id = { for acc in local.all_accounts : acc.id => acc }
accounts_by_name = { for acc in local.all_accounts : acc.name => acc }}
# 8. Outputsoutput "success" { description = "Whether the API calls were successful" value = local.success}
output "error" { description = "Error message if authentication failed" value = local.success ? null : try(local.first_response.errors[0].message, "Unknown error")}
output "accounts" { description = "All Cloudflare accounts" value = local.all_accounts}
output "account_ids" { description = "List of all account IDs" value = [for acc in local.all_accounts : acc.id]}
output "account_names" { description = "List of all account names" value = [for acc in local.all_accounts : acc.name]}
output "total_accounts" { description = "Total number of accounts" value = length(local.all_accounts)}Using accounts in resources
Section titled “Using accounts in resources”Example 1: create zones for each account
Section titled “Example 1: create zones for each account”# Create a zone in each accountresource "cloudflare_zone" "example" { for_each = local.accounts_by_id
account_id = each.key
zone = "example-${replace(lower(each.value.name), " ", "-")}.com" plan = "free" type = "full"}Example 2: access specific account by name
Section titled “Example 2: access specific account by name”# Get a specific account by namelocals { production_account = try(local.accounts_by_name["Production"], null)}
resource "cloudflare_zone" "prod_zone" { count = local.production_account != null ? 1 : 0
account { id = local.production_account.id }
zone = "production.com" plan = "enterprise"}Example 3: filter accounts by criteria
Section titled “Example 3: filter accounts by criteria”# Filter accounts by name patternlocals { prod_accounts = { for acc in local.all_accounts : acc.id => acc if strcontains(lower(acc.name), "prod") }
# Filter by account type enterprise_accounts = { for acc in local.all_accounts : acc.id => acc if try(acc.type, "") == "enterprise" }}Verification
Section titled “Verification”terraform output successreturnstruewhen the first page request authenticated.terraform output errorcarries the API error message when it did not, andnullwhen the call succeeded.terraform output total_accountsis the length oflocal.all_accounts; compare it with the account count in the Cloudflare dashboard to confirm every page was folded in.terraform output account_nameslists the same accounts,account_idslists their ids.
Gotchas and lessons learned
Section titled “Gotchas and lessons learned”- An API token needs only
Account Settingsread; the global key path additionally needs the account email, so it carries more privilege for the same read. cloudflare/cloudflareis only required by the resource examples. The account-fetching configuration useshashicorp/httpalone.- A failed first request is not an error at plan time:
successgoes false,local.total_pagesbecomes 0, the remaining-pagefor_eachis an empty set, and the account list comes back empty.output "error"is the only signal, so check it before usingaccount_ids. for_eachover the remaining pages stringifies the page number, so the loop yields page objects keyed"2","3"and so on, not a list of responses.accounts_by_nameis a map keyed by account name, so two accounts sharing a name collapse to whichever comes last.strcontains(lower(acc.name), "prod")is a substring match: it selectsproductionandnon-prodalike. Filter onaccounts_by_idwith an explicit list when the distinction matters.
File reference
Section titled “File reference”The steps are one Terraform root module: the blocks go into a single .tf file, or split across providers.tf, main.tf and outputs.tf with no change in behaviour. No file path is pinned by the configuration itself.
| Object | What it is |
|---|---|
terraform.required_providers | Pins hashicorp/http 3.0+ and, for the examples, cloudflare/cloudflare 4.0+ |
variable.cloudflare_api_token | Sensitive token variable, Account Settings read |
data.http.first_page | First page of accounts, per_page=50 |
local.remaining_pages and data.http.remaining_pages | The page numbers left to fetch, keyed by string |
local.all_accounts, local.accounts_by_id, local.accounts_by_name | Combined results and the two lookup maps |
output.success, output.error, output.accounts, output.account_ids, output.account_names, output.total_accounts | The module’s outputs |
resource.cloudflare_zone.example, resource.cloudflare_zone.prod_zone | Worked consumers of the locals |