Skip to content

Instantly share code, notes, and snippets.

@Dari4sho
Created August 7, 2025 22:18
Show Gist options
  • Select an option

  • Save Dari4sho/698a231ce67f1b43e4fa7d4a23dca03c to your computer and use it in GitHub Desktop.

Select an option

Save Dari4sho/698a231ce67f1b43e4fa7d4a23dca03c to your computer and use it in GitHub Desktop.
Keep alive hetzner firewall whitelist
#!/bin/bash
# Function to get current public IP address with fallbacks
get_public_ip() {
# Try to get the public IP from multiple services
for service in ifconfig.me icanhazip.com api.ipify.org ipinfo.io/ip; do
PUBLIC_IP=$(curl -s --max-time 10 "$service")
if [ -n "$PUBLIC_IP" ]; then
echo "$PUBLIC_IP"
return
fi
done
echo "Failed to obtain public IP" >&2
exit 1
}
# Get the directory where the script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
cd "$SCRIPT_DIR" || exit 1
echo "Executing from directory: $SCRIPT_DIR"
########################################################################################
# Define variables
FIREWALL_ID=$(pulumi stack output firewallId --stack organization/database-hetzner/prod)
PUBLIC_IP=$(get_public_ip)
# Create context for hcloud cli
echo "Creating necessary context for hcloud cli"
hcloud context create xxxx <<<"Y"
echo "Using hcloud version: $(hcloud version)"
# Function to revoke the firewall rule (cleanup)
cleanup() {
echo ""
echo "Revoking current public IP ($PUBLIC_IP) from the firewall..."
hcloud firewall delete-rule "$FIREWALL_ID" --direction=in --port=3306 --protocol=tcp --source-ips="$PUBLIC_IP/32" --description="Allow MySQL access from dev host"
echo "Firewall rule revoked. Exiting."
exit 0
}
# Trap SIGINT (Ctrl+C), SIGTERM, and EXIT so that cleanup is always called
trap cleanup SIGINT SIGTERM EXIT
# Grant access by adding the firewall rule
echo "Adding current public IP ($PUBLIC_IP) to the firewall..."
hcloud firewall add-rule "$FIREWALL_ID" --direction=in --port=3306 --protocol=tcp --source-ips="$PUBLIC_IP/32" --description="Allow MySQL access from dev host"
echo "Firewall rule added. Press Ctrl+C to terminate and revoke access."
# Keep the script running until interrupted.
while true; do
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment