Skip to content

Instantly share code, notes, and snippets.

@radmen
Last active April 12, 2023 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radmen/a3115aef0da118d23962e0bdba4b6b60 to your computer and use it in GitHub Desktop.
Save radmen/a3115aef0da118d23962e0bdba4b6b60 to your computer and use it in GitHub Desktop.
Generate Cloudflare config tunnel and run it

This is a simple script that will generate a config for cloudflared (with the spec you provide) and run it.

Usage

Generate a single tunnel that redirects mydomain.work to localhost:8080:

cftunnel :8080

This command will generate two tunnels:

  • mydomain.work -> localhost:8080
  • api.mydomain.work -> localhost:3000
cftunnel :8080 api:3000

Requirements

  • NuShell
  • cloudflared

The script assumes that you created the basic set up of the Cloudflare Tunnel and created self-hosted tunnel named "mytunnel".

#!/usr/bin/env nu
def parse-arg [
domain: string
item: string
] {
let split = ($item | split row ":")
let subdomain = ($split | get 0)
let port = ($split | get 1)
let hostname = ($"($subdomain).($domain)" | str trim -l -c '.')
let service = $"http://localhost:($port)"
{ hostname: $hostname, service: $service }
}
def main [
--domain='mydomain.work' # The domain that should be used
...args: string # List of forwarded hosts
] {
let ingress = ($args | each { |item| (parse-arg $domain $item) })
let ingress = ($ingress | append { service: "http_status:404" })
let config = ({
tunnel: "mytunnel",
ingress: $ingress
} | to yaml)
return $config
$config | save --force ~/.cloudflared/config.yml
cloudflared --protocol http2 tunnel run mytunnel
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment