Created
May 25, 2023 00:08
-
-
Save sixman9/faeddbdbb61e2a0a43f4113986695f6b to your computer and use it in GitHub Desktop.
Cloudflare Tunnel to local HTTP creation as a Bash Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Let's ease Cloudflare Tunnel to local HTTP creation | |
# See also https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/local/ | |
# Check if cloudflared is installed | |
if ! command -v cloudflared &> /dev/null; then | |
echo "'cloudflared' is not installed. Installing it now..." | |
brew install cloudflare/cloudflare/cloudflared | |
else | |
echo "'cloudflared' is already installed." | |
fi | |
# Ask user if they need to login to Cloudflare | |
read -p "Do you need to login to Cloudflare? (yes/no): " login_needed | |
if [ "$login_needed" = "yes" ]; then | |
echo "Logging in to Cloudflare..." | |
cloudflared tunnel login | |
fi | |
# Ask user for the tunnel name | |
read -p "Enter the name for the new tunnel (this will also be used as the subdomain): " tunnel_name | |
# Create a new tunnel with the specified name | |
echo "Creating a new tunnel with name '$tunnel_name'..." | |
cloudflared tunnel create $tunnel_name | |
# Store the tunnel ID | |
tunnel_id=$(cloudflared tunnel list | grep -i ${tunnel_name} | awk '{x=$1}END{print x}') | |
# Ask user for the domain | |
read -p "Enter your domain (excluding subdomain): " domain_name | |
# Validate the domain name has at least one dot and does not start or end with a dot | |
if [[ $domain_name != *.* ]] || [[ $domain_name == .* ]] || [[ $domain_name == *.*. ]]; then | |
echo "Invalid domain name. Please include a top-level domain (e.g., 'yourdomain.com', not just 'yourdomain')." | |
exit 1 | |
fi | |
# Concatenate the tunnel_name and the domain_name to create the full_domain | |
full_domain="$tunnel_name.$domain_name" | |
# Configure the tunnel to route traffic | |
echo "Configuring tunnel to route traffic from $full_domain ..." | |
cloudflared tunnel route dns $tunnel_name $full_domain | |
# Ask user for the local service URL | |
read -p "Enter the local service URL (localhost:port): " local_url | |
tunnel_yml="$HOME/.cloudflared/$tunnel_name.yml" | |
# Create a configuration file for the tunnel to specify the local service URL | |
cat << EOF > $tunnel_yml | |
url: $local_url | |
tunnel: $tunnel_id | |
credentials-file: $HOME/.cloudflared/$tunnel_id.json | |
EOF | |
# Run the tunnel | |
echo "Running the tunnel..." | |
cloudflared tunnel --config $tunnel_yml run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment