- shell_exec: documentation ( source)
- strpos: documentation ( source)
- json_decode: documentation ( source)
- array_filter: documentation ( source)
- trim: documentation ( source)
- date: documentation ( source)
- usort: documentation ( source)
#!/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 );
?>