Skip to content

Instantly share code, notes, and snippets.

@bomsn
Created December 2, 2023 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bomsn/2f7df4f25637955a0de3b3a94ed4cc84 to your computer and use it in GitHub Desktop.
Save bomsn/2f7df4f25637955a0de3b3a94ed4cc84 to your computer and use it in GitHub Desktop.
Get notified when your Vultr balance get low.
#!/bin/bash
###################################################################################################
# For instructions, see here:
# https://alikhallad.com/how-to-setup-automated-low-balance-notifications-for-your-vultr-account/
###################################################################################################
# Load the API key from the environment file
source "$(dirname "$0")/.env"
# Define thresholds for balance and pending charges percentage
SOFT_LIMIT_BALANCE=100
HARD_LIMIT_BALANCE=80
CRITICAL_LIMIT_BALANCE=60
SOFT_LIMIT_PERCENTAGE=50
HARD_LIMIT_PERCENTAGE=65
CRITICAL_LIMIT_PERCENTAGE=85
# Email configuration
FROM_EMAIL="your_email@example.com"
TO_EMAIL="recipient_email@example.com"
# Function to send email
send_email() {
local subject=$1
local body=$2
echo "$body" | mail -s "$subject" -r "$FROM_EMAIL" "$TO_EMAIL"
}
# Function to check balance and send notifications
check_balance() {
local balance=$1
local pending_charges=$2
local balance_abs=${balance#-} # Remove the negative sign if present
local percentage=$(echo "scale=2; $pending_charges / $balance_abs * 100" | bc)
if (($(echo "$balance_abs < $CRITICAL_LIMIT_BALANCE || $percentage > $CRITICAL_LIMIT_PERCENTAGE" | bc -l))); then
send_email "Critical Vultr Balance Alert" "Your Vultr balance is critically low. Immediate action required."
elif (($(echo "$balance_abs < $HARD_LIMIT_BALANCE || $percentage > $HARD_LIMIT_PERCENTAGE" | bc -l))); then
send_email "Hard Limit Vultr Balance Alert" "Your Vultr balance is below the hard limit. Please add funds."
elif (($(echo "$balance_abs < $SOFT_LIMIT_BALANCE || $percentage > $SOFT_LIMIT_PERCENTAGE" | bc -l))); then
send_email "Soft Limit Vultr Balance Alert" "Your Vultr balance is approaching the soft limit. Consider adding funds."
fi
}
# Main script execution
response=$(curl -s -H "Authorization: Bearer $VULTR_API_KEY" "https://api.vultr.com/v2/account")
balance=$(echo "$response" | jq -r '.account.balance')
pending_charges=$(echo "$response" | jq -r '.account.pending_charges')
check_balance "$balance" "$pending_charges"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment