Skip to content

Instantly share code, notes, and snippets.

@andrewsomething
Created February 26, 2015 21:08

Revisions

  1. andrewsomething created this gist Feb 26, 2015.
    39 changes: 39 additions & 0 deletions snapshot.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    #!/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