Skip to content

Instantly share code, notes, and snippets.

@te-lang-wakker
Created November 5, 2024 19:43
Show Gist options
  • Save te-lang-wakker/bcec0f53437bceca1b385b188a377258 to your computer and use it in GitHub Desktop.
Save te-lang-wakker/bcec0f53437bceca1b385b188a377258 to your computer and use it in GitHub Desktop.
Terraform CloudFlare Tunnel module for Coder
terraform {
required_providers {
cloudflare = {
source = "cloudflare/cloudflare"
}
}
}
variable "zone" {
description = "Cloudflare zone including zone, zone_id, and account_id"
type = object({
id = string
domain = string
account_id = string
})
}
variable "credentials" {
description = "Cloudflare key and e-mail"
type = object({
key = string
email = string
})
}
variable "application" {
description = "The name of the application"
type = string
}
variable "docker_url" {
description = "The url to the application as seen from within the Docker network"
type = string
}
variable "subdomain" {
description = "The subdomain to host the application on"
type = string
}
variable "policies" {
description = "CloudFlare Access policies"
type = list(string)
}
locals {
hostname = "${var.subdomain}.${var.zone.domain}"
}
# set up provider
provider "cloudflare" {
email = var.credentials.email
api_key = var.credentials.key
}
# resources
resource "random_password" "tunnel_token" {
length = 64
}
resource "cloudflare_zero_trust_tunnel_cloudflared" "app_tunnel" {
account_id = var.zone.account_id
name = var.application
secret = base64sha256(random_password.tunnel_token.result)
}
resource "cloudflare_zero_trust_tunnel_cloudflared_config" "config" {
account_id = var.zone.account_id
tunnel_id = cloudflare_zero_trust_tunnel_cloudflared.app_tunnel.id
config {
warp_routing {
enabled = false # not worth the setup
}
ingress_rule {
hostname = local.hostname
service = var.docker_url
}
ingress_rule {
service = "http_status:404"
}
}
}
resource "cloudflare_record" "http_app" {
zone_id = var.zone.id
name = local.hostname
content = cloudflare_zero_trust_tunnel_cloudflared.app_tunnel.cname
type = "CNAME"
proxied = true
}
resource "cloudflare_zero_trust_access_application" "app_access" {
zone_id = var.zone.id
name = var.application
domain = local.hostname
type = "self_hosted"
session_duration = "12h"
policies = var.policies
}
output "tunnel_token" {
value = cloudflare_zero_trust_tunnel_cloudflared.app_tunnel.tunnel_token
sensitive = true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment