Terraform配置Cloudflare页面规则遇自引用错误求助
Ah, I see the issue here — that self-reference error pops up because you’re trying to use self.domain in the target field before the resource has even been created. Terraform can’t resolve self attributes until the resource is fully provisioned, so referencing it during initial config parsing throws that error.
Here’s the quick fix: since you’re already passing your domain via the var.domain variable, you can use that directly to build your target string instead of relying on self.domain.
Updated configuration:
resource "cloudflare_page_rule" "https-only" { zone = var.domain domain = var.domain target = "http://*${var.domain}/*" priority = 1 actions = { always_use_https = true } }
Why this works:
var.domainis a known value the moment Terraform parses your configuration, so it can safely be used to construct the target pattern right away.selfis meant for referencing attributes generated after the resource is created (like a unique ID or auto-generated DNS records), not for values you already have available via variables.
This adjusted rule will still do exactly what you want: redirect all incoming HTTP traffic (including subdomains, thanks to the * wildcard) to HTTPS. If you ever need to narrow it down to just the main domain, you can tweak the target to http://${var.domain}/*, but your original wildcard pattern is perfect for covering all subdomains too.
内容的提问来源于stack exchange,提问作者Anthony Kong

