Last active
November 10, 2024 12:02
-
-
Save andrasbacsai/f92af3afa1a8294bb60ea6f333998be6 to your computer and use it in GitHub Desktop.
Update a Hetzner Firewall rule with your IP address
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 | |
# Script to update a firewall rule in a Hetzner Firewall with your current IP address. | |
# Good if you would like to restrict SSH access only for your current IP address (secure). | |
################# | |
# WARNING: This script will overwrite all rules in the firewall rules, so make sure you | |
# added all the required rules. | |
# I use a separate firewall rule just for SSH access. | |
################# | |
# Prerequisites: | |
# 1. Download: hcloud cli (https://github.com/hetznercloud/cli) | |
# 2. Authenticate: hcloud context create | |
# 3. Need to make the firewall rule in advance, add resources to it. | |
# Get the name with 'hcloud firewall list' | |
FIREWALL_NAME="<your-firewall-name>" | |
MY_IP_ADDRESS=$(curl -4s https://icanhazip.com) | |
if [ $? -ne 0 ]; then | |
echo "Failed to get my IP address" | |
exit 1 | |
fi | |
# Add your own rules here if necessary. | |
RULES=$(cat <<EOF | |
[ | |
{ | |
"description": "SSH for me", | |
"direction": "in", | |
"port": "22", | |
"protocol": "tcp", | |
"source_ips": ["$MY_IP_ADDRESS/32"] | |
} | |
] | |
EOF | |
) | |
CURRENT_RULES=$(hcloud firewall describe $FIREWALL_NAME --output json | jq -r '.rules[] | select(.description == "SSH for me") | .source_ips[0]' | cut -d'/' -f1) | |
if [ $? -ne 0 ]; then | |
echo "Failed to get current firewall rules with name $FIREWALL_NAME" | |
exit 1 | |
fi | |
echo "My IP: $MY_IP_ADDRESS" | |
echo "IP in firewall: $CURRENT_RULES" | |
if [ "$MY_IP_ADDRESS" != "$CURRENT_RULES" ]; then | |
echo "IP changed, updating firewall" | |
hcloud firewall replace-rules $FIREWALL_NAME --rules-file - <<<"$RULES" | |
else | |
echo "IP is the same, skipping" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment