Skip to content

Instantly share code, notes, and snippets.

@charlyie
Last active August 12, 2020 07:21
Show Gist options
  • Save charlyie/a82835ed1ae3dc94551b48ea0783d0a9 to your computer and use it in GitHub Desktop.
Save charlyie/a82835ed1ae3dc94551b48ea0783d0a9 to your computer and use it in GitHub Desktop.
Will use Scaleway API to fetch public and private IP linked to an account, and paste them in a file. Can trigger when IP are updated, and relaunch a firewall
#!/bin/bash
### description : fetch local network IP through Scaleway API (local IP changes on each reboot), and expose these IP in a file (e.g : for firewall purposed)
### Author : Charles Bourgeaux <charles@maecia.com>
### Date : 11 AUG 2020
### requires `jq` package
### Editable variables
SCALEWAY_TOKEN='xxxx-xxx-xxx-xxx-xxx'
SCALEWAY_ZONE='fr-par-1'
IP_LIST_FILE='/opt/sbin/local_authorized_ip'
LOGS='/var/log/ip_update'
### End of editable variables
DATE_LOGS=$(date '+%Y-%m-%d %H:%M:%S')
if [[ ! -f $IP_LIST_FILE ]]
then
touch $IP_LIST_FILE
fi
CURRENT_SHA_SUM=$(sha1sum ${IP_LIST_FILE}|awk '{print $1}')
printf 'Current file checksum : %s\n' "$CURRENT_SHA_SUM"
#Purge file
cat /dev/null > ${IP_LIST_FILE}
printf '[%s] Requesting Scaleway API...\n' "$DATE_LOGS"
api_response=$(curl -s -H "X-Auth-Token: $SCALEWAY_TOKEN" "https://api.scaleway.com/instance/v1/zones/${SCALEWAY_ZONE}/servers")
if [ -n "$api_response" ]; then
if jq -e . >/dev/null 2>&1 <<<"$api_response"; then
echo 'JSON is valid'
else
printf '[%s] Failed to parse JSON !\n' "$DATE_LOGS" | tee -a $LOGS
exit
fi
data=$(echo "$api_response" | jq .servers | jq -r '.[]' | jq .public_ip.address,.private_ip)
while IFS= read -r line
do
echo "$line" | cut -d '"' -f 2 >> ${IP_LIST_FILE}
done < <(printf '%s\n' "$data")
NEW_SHA_SUM=$(sha1sum ${IP_LIST_FILE}|awk '{print $1}')
if [[ $NEW_SHA_SUM != "$CURRENT_SHA_SUM" ]];
then
printf '[%s] IP seems to have changed. New IP are :\n' "$DATE_LOGS" | tee -a $LOGS
cat ${IP_LIST_FILE} | tee -a $LOGS
# Action like : sudo /etc/init.d/firewall restart
fi
else
printf '[%s] Empty response from Scaleway API, aborting !\n' "$DATE_LOGS" | tee -a $LOGS
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment