Skip to content

Instantly share code, notes, and snippets.

@loveshizuka
Created December 18, 2017 23:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loveshizuka/17e0a6b122f7d74dced7618c79c915b5 to your computer and use it in GitHub Desktop.
Save loveshizuka/17e0a6b122f7d74dced7618c79c915b5 to your computer and use it in GitHub Desktop.
Automatic snapshots using Vultr API

Automated Snapshots / Backups via Vultr API

A more customizable alternative to Vultr's backup feature using Vultr API v1. Tested on Ubuntu 16.04. Run this php script on a Vultr instance to create a snapshot of itself and rotate out the oldest snapshot(s). Use the $backup_tag field to uniquely id a set of snapshots.

  1. Set $api_key to your Vultr API key.
  2. Set $num_of_backups to specify how many snapshots to keep.
  3. Set chmod +x vultr-snapshot.php.
  4. Add vultr-snapshot.php to your cron tab.
  5. Epic winning at life.

For example, add the crob jobs below in order to create 3 daily, weekly, and monthly snapshots. The oldest snapshots will be automatically rotated out.

0 0 * * * /home/user/scripts/vultr-snapshot.php
#!/usr/bin/php
<?php
// input parameters
$api_key = "YOUR_API_KEY";
// default arguments
$backup_tag = "daily";
$num_of_backups = 3;
// sunday = weekly, 1st day of month = monthly
if(intval(date('w')) == 0) $backup_tag = "weekly";
if(intval( date('d')) == 1) $backup_tag = "monthly";
$api_addr = "https://api.vultr.com/v1/";
$curl = "curl -s -H 'API-Key: " . $api_key . "' " . $api_addr;
$host = trim(shell_exec("hostname"));
$ip = trim(shell_exec("hostname -I"));
// find a subid that matches the current ip
$json = shell_exec( $curl . "server/list" );
$obj = json_decode($json,true);
$subid = 0;
foreach ($obj as $k => $v) {
if( $v['main_ip'] == $ip ){
$subid = $k;
break;
}
}
if($subid == 0){
echo "Couldn't find a Vultr instance with ip " . $ip;
exit(1);
}
// find old snapshot(s) to remove
$json = shell_exec( $curl . "snapshot/list" );
$obj = json_decode($json,true);
// filter non-backup snapshots
$obj = array_filter($obj, function ($x){
return strpos($x['description'], $GLOBALS['ip'] . "-" . $GLOBALS['backup_tag']) !== false;
});
// reverse sort by creation time
usort($obj, function($x, $y){
return $y['date_created'] <=> $x['date_created'];
});
// delete oldest snapshot(s)
for($i=0;$i<count($obj);$i++){
if($i >= $num_of_backups-1){
$id = $obj[$i]['SNAPSHOTID'];
$cmd = $curl . "snapshot/destroy";
shell_exec( $cmd . " --data 'SNAPSHOTID=" . $id . "'" );
}
}
// create new snapshot
$cmd = $curl . "snapshot/create";
$cmd .= " --data 'SUBID=" . $subid . "'";
$cmd .= " --data 'description=" . $host . "-" . $ip . "-" . $backup_tag . "'";
shell_exec( $cmd );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment