Create daily snapshots using Python on Digitalocean

In order to use this script, you will need to generate an API key and find your droplet id.
To optain your API KEY you will have to login into your digitalocean account, click on API, then Generate New Token. Once you have it, just update the API_KEY variable.

 

You can find your droplet id by opening your droplet graphs page ( https://cloud.digitalocean.com/droplets/123456/graphs?i=abcde ). In my case, the droplet id is 123456. After that update the variable DROPLET_ID.

 

#!/usr/bin/env python
import os
import sys
import requests
import json
import datetime

# Digitalocean variables
API_KEY = ''
DROPLET_ID = ''
SNAPSHOT_NAME = 'DROPLET_NAME_' + str(datetime.datetime.now())
KEEP_SNAPSHOTS = 1

# API URL
API_LIST_SHAPSHOTS = 'https://api.digitalocean.com/v2/droplets/' + str(DROPLET_ID) + '/snapshots'
API_CREATE_SNAPSHOT = 'https://api.digitalocean.com/v2/droplets/' + str(DROPLET_ID) + '/actions'

headers = {
    'content-type': 'application/json',
    'Authorization': 'Bearer ' + API_KEY
}
payload = {}
mode = False
try:
    mode = sys.argv[1]
except Exception as e:
    pass

if (mode):
    # Remove the old snapshots
    if mode == 'clean':
        r = requests.get(API_LIST_SHAPSHOTS, data=json.dumps(payload), headers=headers)
        data = r.json()
        snapshots = data['snapshots']
        counter = 1

        if (len(snapshots) > KEEP_SNAPSHOTS - 1):
            for snapshot in reversed(snapshots):
                if counter > KEEP_SNAPSHOTS:
                    print "Removing " + snapshot['name'] + ", having the id : " + str(snapshot['id'])
                    api_url = 'https://api.digitalocean.com/v2/snapshots/' + str(snapshot['id'])
                    r = requests.delete(api_url, data=json.dumps(payload), headers=headers)
                    print r
                else:
                    print "Keeping " + snapshot['name']
                counter = counter + 1
    if mode == 'create':
        d = {
            'type': 'snapshot',
            'name': SNAPSHOT_NAME
        }
        r = requests.post(API_CREATE_SNAPSHOT, data=json.dumps(d), headers=headers)
        print r

 

How to use this script:

python script.py create # For snapshot creation
python script.py clean # To remove the old snapshot(s)

 

Linux Python Security
Use Python Requests to Authenticate
Using requests, you can authenticate on a secure website. This method, will also read the CSRF field and cookie, and get it ready for the validation.
Linux Python Django Tutorials
Serve Django Applications with uWSGI and Nginx on CentOS
In this tutorial you will learn how to install and configure VirtualEnv and VirtualEnvWrapper on centos. Also, you will learn how to create your first django application and deploy it.
Top