dots

git clone git://mattcarlson.org/repos/dots.git
Log | Files | Refs

vultr.sh (1651B)


      1 #!/bin/sh
      2 #
      3 # vultr
      4 
      5 # disable double quote warning
      6 # shellcheck disable=2086
      7 
      8 get_ids() { awk -F ',' '{ for (i = 1; i <= NF; i++) if ($i ~ /"id"/) print $i }' | awk -F ':' '{ for (i = 1; i <= NF; i++) if ($i ~ /-/) print $i }' | tr -d \" ; }
      9 
     10 # DO NOT SHARE THIS
     11 VULTR_API_KEY='RETRACTED'
     12 
     13 INSTANCE='mattcarlson.org'
     14 
     15 INSTANCE_ID="$(curl 'https://api.vultr.com/v2/instances'    \
     16                 -X GET                                      \
     17                 -H "Authorization: Bearer ${VULTR_API_KEY}" \
     18                 | get_ids)"
     19 
     20 snapshot_ids="$(curl 'https://api.vultr.com/v2/snapshots'   \
     21                 -X GET                                      \
     22                 -H "Authorization: Bearer ${VULTR_API_KEY}" \
     23                 | get_ids)"
     24 
     25 # Get oldest snapshot ID -- will be first in list
     26 set -- ${snapshot_ids}
     27 oldest_snapshot_id="${1}"
     28 
     29 # Vultr only allows eleven(?) snapshots at this moment
     30 SNAPSHOT_LIMIT=1
     31 snapshot_count=$(printf '%s\n' "${snapshot_ids}" | wc -w)
     32 
     33 main() {
     34     # Delete oldest snapshot if limit if reached
     35     if [ "${snapshot_count}" -eq "${SNAPSHOT_LIMIT}" ]; then
     36         curl "https://api.vultr.com/v2/snapshots/${oldest_snapshot_id}" -X DELETE -H "Authorization: Bearer ${VULTR_API_KEY}" || exit 1;
     37     fi
     38 
     39     # Create new snapshot for instance
     40     curl 'https://api.vultr.com/v2/snapshots'         \
     41         -X POST                                       \
     42         -H "Authorization: Bearer ${VULTR_API_KEY}"   \
     43         -H 'Content-Type: application/json'           \
     44         --data '{
     45             "instance_id":"'${INSTANCE_ID}'",
     46             "description":"Snapshot of '${INSTANCE}'"
     47         }'
     48 }
     49 
     50 main "${@}"