Skip to content

Instantly share code, notes, and snippets.

@niladam
Forked from andrasbacsai/firewall.sh
Created October 30, 2024 17:25
Show Gist options
  • Save niladam/36ec8879eab65a797a774b3176de8472 to your computer and use it in GitHub Desktop.
Save niladam/36ec8879eab65a797a774b3176de8472 to your computer and use it in GitHub Desktop.
Update a Hetzner Firewall rule with your IP address
#!/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