Last active
February 16, 2018 22:27
-
-
Save blockloop/66cfb498e57521068779254db105c920 to your computer and use it in GitHub Desktop.
update digitalocean ssh firewall to local IP
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 -o pipefail | |
doctl="/usr/local/bin/doctl" | |
# name of your tag | |
TAG_NAME="" | |
# the DO token from https://cloud.digitalocean.com/settings/api/tokens | |
TOKEN="" | |
# the firewall ID found by running "doctl compute firewall list" | |
FIREWALL_ID="" | |
# the firewall name found by running "doctl compute firewall list" | |
FIREWALL_NAME="" | |
IPV4_CACHE_FILE="$HOME/.config/publicipv4" | |
IPV6_CACHE_FILE="$HOME/.config/publicipv6" | |
[ -f "$IPV4_CACHE_FILE" ] || touch "$IPV4_CACHE_FILE" | |
[ -f "$IPV6_CACHE_FILE" ] || touch "$IPV6_CACHE_FILE" | |
CACHED_IPV4="$(cat "$IPV4_CACHE_FILE")" | |
CACHED_IPV6="$(cat "$IPV6_CACHE_FILE")" | |
# outbound rules | |
OBRULES="protocol:icmp,address:0.0.0.0/0,address:::/0 protocol:tcp,ports:all,address:0.0.0.0/0,address:::/0 protocol:udp,ports:all,address:0.0.0.0/0,address:::/0" | |
UDP_RULES="" | |
TCP_RULES="" | |
if IPV4=$(curl -SsL ipv4.icanhazip.com); then | |
TCP_RULES="protocol:tcp,ports:all,address:${IPV4}" | |
UDP_RULES="protocol:udp,ports:all,address:${IPV4}" | |
fi | |
if IPV6=$(curl -SsL ipv6.icanhazip.com); then | |
TCP_RULES="${TCP_RULES},address:${IPV6}" | |
UDP_RULES="${UDP_RULES},address:${IPV6}" | |
fi | |
if [ "$CACHED_IPV4" == "$IPV4" ] && [ "$CACHED_IPV6" == "$IPV6" ]; then | |
echo "IP unchanged. Not updating" | |
exit 0 | |
fi | |
if [ -z "$UDP_RULES" ] && [ -z "$TCP_RULES" ]; then | |
echo "No inbound rules to set. Exiting" > /dev/stderr | |
exit 1 | |
else | |
echo "Updating IP rules to allow only $UDP_RULES $TCP_RULES" | |
fi | |
function updatecache() { | |
echo -n "$IPV4" > "$IPV4_CACHE_FILE" | |
echo -n "$IPV6" > "$IPV6_CACHE_FILE" | |
} | |
$doctl --access-token "$TOKEN" compute firewall update "$FIREWALL_ID" \ | |
--name "$FIREWALL_NAME" --inbound-rules "$TCP_RULES $UDP_RULES" \ | |
--outbound-rules "$OBRULES" \ | |
--tag-names "$TAG_NAME" && updatecache | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment