Maksym Prokopov personal blog
Idea is a something worth sharing

CloudFlare Tunnel Terraform

15.07.2023

Reading time: 1 min.

How to provision CloudFlare tunnel using Terraform

CloudFlare Tunnel can be useful to use reliable alternative to ngrok when you need to expose your application running locally to the outside world.

The following example exposes my application locally running on port 3000 to the Internet on the hostname https://app.prokopov.me

Prerequisites

How does it work?

  1. cloudflared CLI is an agent running locally and connected to CloudFlare cloud.
  2. DNS record of type CNAME is created, pointing to the CloudFlare cloud.
  3. CloudFlare does the routing magic!

Terraform part

resource "cloudflare_tunnel" "main" {
  account_id = "777414c2d4e87234087ebac4685e7df6"
  name       = "tunnel-to-app"
  secret     = random_id.main.b64_std
}

resource "cloudflare_tunnel_config" "main" {
  account_id = "777414c2d4e87234087ebac4685e7df6"
  tunnel_id  = cloudflare_tunnel.main.id

  config {
    warp_routing {
      enabled = true
    }
    ingress_rule {
      hostname = "app.prokopov.me"
      service  = "http://localhost:3000"
    }
    ingress_rule {
      service = "http_status:404"
    }
  }
}

resource "cloudflare_record" "main" {
  value   = "${cloudflare_tunnel.main.id}.cfargotunnel.com"
  proxied = true
  name    = "app"
  type    = "CNAME"
  zone_id = cloudflare_zone.main.id
}

Local tunnel part

  1. Find generated token for resource cloudflare_tunnel.main
TOKEN=$(terraform show -json | jq -r '.values.root_module.resources[] | select(.address=="cloudflare_tunnel.main").values.tunnel_token')
  1. Use token
cloudflared tunnel run --token=${TOKEN} tunnel-to-app