Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Power off and Snapshot a DigitalOcean Droplet
#!/usr/bin/env ruby
require 'droplet_kit'
require 'json'
token = ENV['DO_TOKEN']
client = DropletKit::Client.new(access_token: token)
droplet_id = ARGV[0]
snapshot_name = ARGV[1] || Time.now.strftime("%b. %d, %Y - %H:%M:%S %Z")
def power_off(client, id)
res = client.droplet_actions.shutdown(droplet_id: id)
until res.status == "completed"
res = client.actions.find(id: res.id)
sleep(2)
end
puts " * Action status: #{res.status}"
rescue NoMethodError
puts JSON.parse(res)['message']
end
def take_snapshot(client, id, name)
res = client.droplet_actions.snapshot(droplet_id: id, name: name)
puts " * Action status: #{res.status}"
rescue NameError
puts JSON.parse(res)['message']
end
unless droplet_id.nil?
puts "Powering off droplet..."
power_off(client, droplet_id)
sleep(2)
puts "Taking snapshot..."
take_snapshot(client, droplet_id, snapshot_name)
else
puts "Power off and snapshot a droplet. Requires a droplet ID and optionally a snapshot name."
puts "Usage: #{$0} droplet_id ['snapshot name']"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment