Taking a snapshot with DigitalOcean new API

Recently i came across a client who wanted to take weekly snapshots of his DigitalOcean droplet.
Before i used to do everything through the Python module build by Lorenzo Setale ( you should really check out everything this guy ever made ) but then i decided i wanted to give the new 2.0 API a go.
most of the times when i read code nobody cares about the imports. I do, so lets start with that

i’m using python 2.7.6 for this so i’m importing the print command implented in python 3.x
also i’m using requests. so so so much easier then urllib.

now for some VARS:

I’m setting up the script with the API key giving by DigitalOcean for my account and also specifying the droplet id that i want to take a snapshot from.
The headers of the request will list my api key and the fact the i want my responses in json.
I’m also setting a boolean var named shutdown. you will see why later.

And now to the Main code:

I start by initializing a URI for my post requests with the droplet id i created before.

Now all i have to do is call the API twice:
1. Shutdown the server.
2. Take the snapshot.

The server will automatically start up when the snapshot is over so no need to post a power up request.
After i finish i’m using requests internal function called ‘json’ to marshal the response and send it to my loop function.

The loop function gets a json object and sends it to the Errors()function for evaluation.
If for some reason the post action was not commited this function will take care of the errors.

next if the action is in progress we’ll start a while loop checking the state of the action in progress.
there are 3 states to consider: in-progress, errored and completed.
If the action is still running ( in-progress ) the script will hold for 1 minute before trying the API again.
the get request for the state of the action is read by the function Status():

if for some reason the state is errored the script will go to the termination function called PowerUp()

this functions checks if the droplet was shutdown and send the power_on action to wake it up.
in any case the script will quit.

That’s about it! the script is ready to be used with crontab or whatever you feel like!

The full version looks like this:

Leave a Reply

Your email address will not be published. Required fields are marked *