How to Setup Alerts for Your Vultr Account Balance
Introduction
According to Vultr’s documentation, accumulated charges are invoiced to your account on the 1st of every month. If they are unable to process payment of fees, they may suspend or cancel your services. In this brief post, I’ll show you how to generate a push alert/notification to your email if your account balance falls below a given threshold.
Prerequisites
- Enabled and configured API access from your Vultr account settings:
- You should have a valid API key. I’ve stored my key as an environment variable, VULTR_API_KEY, in /etc/environment.
- Whitelisted your instance to use the API key.
- jq to easily parse the JSON payload.
- bc for arbitrary-precision arithmetic.
- SMTP server to send emails. If you don’t have an SMTP server set up, there is likely some free alerting/notifcation service that you can leverage.
The Script
Here’s the small script:
#!/bin/sh
# This script expects 2 arguments:
# $1: Email address to send the notification to.
# $2: Account balance threshold. If the balance falls below this value, the
# user will be notified by email.
# Dependencies:
# API Key is stored as an environment variable, VULTR_API_KEY, in /etc/environment
# jq to parse the JSON payload
# bc for arbitrary-precision arithmetic
# SMTP server to send emails
# Get email and threshold
email=$1
threshold=$2
# Get current balance
balance=$(curl -s -H "Authorization: Bearer ${VULTR_API_KEY}" https://api.vultr.com/v2/account | jq '.account.balance')
# Make balance positive
balance=`echo $balance*-1 | bc`
[ `echo $balance'<'$threshold | bc -l` -eq 1 ] && echo "Threshold: $threshold. Current balance: $balance" | \
mail -s "[Vultr Account Balance Alert]: Add Funds" $email
Don’t forget to make the script executable:
chmod +x get_vultr_balance.sh
Add Cron Entry
The final task is to make an entry in the crontab. Here’s my configuration which is scheduled to run daily at 9AM EST:
00 09 * * * sh $HOME/scripts/bash/get_vultr_balance.sh foo@email.com 5
If the account balance falls below $5, an alert will be sent to foo@email.com.