diff --git a/monitor_ip.conf.example b/monitor_ip.conf.example new file mode 100644 index 0000000..43562ef --- /dev/null +++ b/monitor_ip.conf.example @@ -0,0 +1,6 @@ +# +# Configuration file for monitor_ip.sh +# +# + +SERVICES="nginx" \ No newline at end of file diff --git a/monitor_ip.sh b/monitor_ip.sh new file mode 100644 index 0000000..ea60e17 --- /dev/null +++ b/monitor_ip.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash + +# Copyright (C) 2021 by LHProjects +# +# Permission is granted to use, copy, modify, and/or distribute this work for any purpose with or without fee. This work is offered as-is, with absolutely no warranty whatsoever. The author is not responsible for any damages that result from using this work. +# +# + +# Monitors host public IP, when it differs, restart services. +# +# +# I wrote this script for services like Nginx, which caches hostnames and fall out of sync when hostname IP changes. +# This is problematic when you have edge servers connecting to backends with hostnames that change +# ips frequently. + +# Define variables +CONF_NAME="monitor_ip.conf" +POSSIBLE_PATHS="./ /etc" +CACHE_IP_FILE=/tmp/monitor_ip.cache +PUBLIC_IP=$(curl --silent https://api.ipify.org/) + +FOUND=false +IFS=" " +for P in $POSSIBLE_PATHS; do + if test -f "$P"/$CONF_NAME; then + FOUND=true + source "$P"/$CONF_NAME + fi +done + +if [ $FOUND = false ]; then + echo "Configuration file not found in '$POSSIBLE_PATHS'" + exit 1 +fi + +# Check if we have cache IP +if test -f $CACHE_IP_FILE; then + CACHE_IP=$(cat $CACHE_IP_FILE) + if [ "$PUBLIC_IP" != "$CACHE_IP" ]; then + for S in $SERVICES; do + systemctl restart "$S" + done + fi +else + echo "$PUBLIC_IP" > $CACHE_IP_FILE +fi +exit 0 \ No newline at end of file