Last active
September 16, 2024 13:54
-
-
Save DTTerastar/aabed5084d4173787724ba1f2f3971c6 to your computer and use it in GitHub Desktop.
Create a simple dynamic config for a locally running server
This file contains 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 | |
set -e | |
# Set variables | |
TRAEFIK_DYNAMIC_DIR="/etc/traefik/dyn" | |
# Check if script is run as root | |
if [[ $EUID -ne 0 ]]; then | |
echo "This script must be run as root" | |
exit 1 | |
fi | |
# Function to validate hostname | |
validate_hostname() { | |
if [[ ! $1 =~ ^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$ ]]; then | |
echo "Invalid hostname format" | |
return 1 | |
fi | |
return 0 | |
} | |
# Function to validate port number | |
validate_port() { | |
if ! [[ $1 =~ ^[0-9]+$ ]] || [ $1 -lt 1 ] || [ $1 -gt 65535 ]; then | |
echo "Invalid port number. Must be between 1 and 65535." | |
return 1 | |
fi | |
return 0 | |
} | |
# Prompt for hostname | |
while true; do | |
read -p "Enter the hostname (e.g., example.com): " HOSTNAME | |
if validate_hostname "$HOSTNAME"; then | |
break | |
fi | |
done | |
# Prompt for local port | |
while true; do | |
read -p "Enter the local port number: " LOCAL_PORT | |
if validate_port "$LOCAL_PORT"; then | |
break | |
fi | |
done | |
# Generate a safe filename | |
FILENAME=$(echo "$HOSTNAME" | sed 's/[^a-zA-Z0-9]/_/g') | |
# Create the dynamic configuration file | |
cat << EOF > "${TRAEFIK_DYNAMIC_DIR}/${FILENAME}.yml" | |
http: | |
routers: | |
${FILENAME}: | |
rule: "Host(\`${HOSTNAME}\`)" | |
service: ${FILENAME} | |
entryPoints: | |
- websecure | |
tls: | |
certResolver: cloudflare | |
services: | |
${FILENAME}: | |
loadBalancer: | |
servers: | |
- url: "http://127.0.0.1:${LOCAL_PORT}" | |
EOF | |
echo "Configuration file created: ${TRAEFIK_DYNAMIC_DIR}/${FILENAME}.yml" | |
echo "Traefik will route traffic for ${HOSTNAME} to localhost:${LOCAL_PORT}" | |
echo "Make sure your DNS is configured to point ${HOSTNAME} to this server's IP address." | |
echo "If Traefik is running, it should automatically detect and apply this new configuration." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment