Skip to content

Instantly share code, notes, and snippets.

@Lp-Francois
Last active October 28, 2020 16:11
Show Gist options
  • Select an option

  • Save Lp-Francois/b5d87630b02b7162c1cd1e72a9297f50 to your computer and use it in GitHub Desktop.

Select an option

Save Lp-Francois/b5d87630b02b7162c1cd1e72a9297f50 to your computer and use it in GitHub Desktop.
Update DigitalOcean Firewall with your current IP (Include a basic cache system).
#!/bin/bash
set -o pipefail
doctl="/usr/local/bin/doctl"
FW_ID=the-id-of-the-firewall-wqd-2312-qwdq
FW_NAME=my-databases-firewall-for-admin
CACHE_PATH="/path/to/my/cache/named/.cache"
TAG_NAMES=mongodb,mysql,other
function valid_ip()
{
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
function is_my_ip_in_the_firewall()
{
if doctl compute firewall get $FW_ID | grep -q $CURRENT_IP; then
echo ' [>] IP already present in the firewall'
# 0 = true
return 0
else
echo ' [>] IP not present in the firewall'
return 1
fi
}
function delete_old_ip_fom_fw()
{
local OLD_IP=$(cat ${CACHE_PATH})
valid_ip $OLD_IP
if [[ $? -ne 0 ]] ; then
echo " ⚠️ cached IP non valid"
exit 1
fi
NEW_INBOUND_RULE=${NEW_INBOUND_RULE/",address:$OLD_IP"/""}
echo " [>] Delete cached IP from string."
}
CURRENT_IP=$(curl -SsL ipv4.icanhazip.com)
# check if IP returned is a valid IP
valid_ip $CURRENT_IP
if [[ $? -ne 0 ]] ; then
echo " ⚠️ IP non valid"
exit 1
fi
echo ' [>] IP valid'
if is_my_ip_in_the_firewall; then
echo -e "\n ✅ - Shutdown\n"
exit 0
fi
OLD_INBOUND_RULE=$(doctl compute firewall get ${FW_ID} | awk 'NR>1 {print $5}')
echo -e " [>] Old Inbound Rule:\n\n" $OLD_INBOUND_RULE
NEW_INBOUND_RULE=${OLD_INBOUND_RULE/"ports:0"/"ports:all"}
# if cache, remove it from fw
if test -f "$CACHE_PATH"; then
echo " [>] Use cache to clean firewall..."
delete_old_ip_fom_fw
fi
# Add new IP
NEW_INBOUND_RULE="${NEW_INBOUND_RULE},address:${CURRENT_IP}"
# cache the IP
echo $CURRENT_IP > $CACHE_PATH
echo -e ' [>] New Inbound Rule:\n\n' $NEW_INBOUND_RULE
doctl compute firewall update $FW_ID --inbound-rules $NEW_INBOUND_RULE --name $FW_NAME --tag-names $TAG_NAMES
if [[ $? -ne 0 ]] ; then
echo " ⚠️ - Error occured"
exit 1
fi
echo -e "\n [>] Updated"
echo -e "\n ✅ - Shutdown\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment