Langsung ke konten utama

Auto Snapshot Droplet Digitalocean

Sumbernya sih disini,

Jadi gini, saya punya droplet di DO, pengennya saya itu seminggu sekali droplet otomatis snapshot. Ndak masalah bagi saya droplet ndak bisa diakses (karena snapshot mengHARUSkan droplet dalam keadaan mati dan snapshot itu sendiri bisa memakan waktu hingga 10 menit untuk ukuran SSD 20GB). Masalah muncul lagi ketika saya bisa otomatis snapshot, yaitu belum bisa otomatis delete iamge (image adalah hasil dari snapshot yang bisa di create jadi droplet), jadi tiap bulan ada 4 image snapshot dan akan nyampah jika tidak dihapus.


Buat dulu API-Key di Digitalocean, trus disimpen, itu ntar buat kode token.
Misal API-Key-nya adalah b37013An937k0wEdul
Misal kita pake user gagas. User gagas udah masuk grup sudo.
Misal id_droplet yang mau di autosnapshot adalah 292929

Install curl
$sudo apt-get install php5-curl

Install ruby
$ curl -sSL https://rvm.io/mpapis.asc | gpg2 --import -
$ \curl -sSL https://get.rvm.io | bash -s stable --ruby

Memperoleh info droplet 292929
$curl -X GET -H "Content-Type: application/json" \
    -H "Authorization: Bearer b37013An937k0wEdul" \
    "https://api.digitalocean.com/v2/droplets/292929"

Power off droplet and make snapshot menggunakan curl
curl -X POST -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer b37013An937k0wEdul' \
    -d '{"type":"snapshot","name":"Hasil_autosnap"}' \
    "https://api.digitalocean.com/v2/droplets/6659646/actions"

Kalo mau liat snapshotnya selesai atau belum, cek status snapshot
curl -X GET -H "Content-Type: application/json" \
    -H "Authorization: Bearer b37013An937k0wEdul" \
    "https://api.digitalocean.com/v2/actions/6659646"

Sudah bisakah? OK. Lanjut biar otomatis yah. Kita pake ruby (ngikut sumber :p)

Install rvm (ruby version manager)
$\curl -sSL https://get.rvm.io | bash -s stable --ruby
$gpg2 --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
$\curl -sSL https://get.rvm.io | bash -s stable --ruby
$source ~/.rvm/scripts/rvm


##########script autosnapshot pakai ruby

#!/usr/bin/env ruby                                                                                                                                                                                
require 'rest_client'                                                                                                                                                                              
require 'json'

$api_token  = ENV['DO_TOKEN']
$baseUrl    = "https://api.digitalocean.com/v2/"
$headers    = {:content_type => :json, "Authorization" => "Bearer #{$api_token}"}

class ResponseError < StandardError; end

def droplet_on?(droplet_id)
  url     = $baseUrl + "droplets/#{droplet_id}"
  droplet = get(url)['droplet']

  droplet['status'] == 'active'
end

def power_off(droplet_id)
  url = $baseUrl + "droplets/#{droplet_id}/actions"
  params = {'type' => 'power_off'}
  post(url, params)
end

def snapshot(droplet_id)
  url = $baseUrl + "droplets/#{droplet_id}/actions"
  params = {'type' => 'snapshot', 'name' => "Droplet #{droplet_id} " + Time.now.strftime("%Y-%m-%d")}
  post(url, params)
end

def get(url)
  response = RestClient.get(url, $headers){|response, request, result| response }
  puts response.code

  if response.code == 200
#    sleep 10
    JSON.parse(response)
  else
    raise ResponseError, JSON.parse(response)["message"]
  end
end

def post(url, params)
  response = RestClient.post(url, params.to_json, $headers){|response, request, result| response }

  if response.code == 201
    JSON.parse(response)
  else
    raise ResponseError, JSON.parse(response)["message"]
  end
end

droplets = ARGV

droplets.each do |droplet_id|
  puts "Attempting #{droplet_id}"
#  sleep 10
  begin
    if droplet_on?(droplet_id)
      power_off(droplet_id)

      while droplet_on?(droplet_id) do
#        sleep 10
      end
      puts "Powered Off #{droplet_id}"
#      sleep 10
    end

    snapshot(droplet_id)
    puts "Snapshotted #{droplet_id}"
  rescue ResponseError => e
    puts "Error Snapshotting #{droplet_id} - #{e.message}"
  end
end

*script diatas ndak perlu di modif, udah bisa dijalankan. Sleep saya komen soalnya kalo pake sleep, lama sih prosesnya :D. Tarus script di direktori /home/gagas/otosnap kasih nama otosnapruby.rb

#############script mengeksekusi otosnapruby.rb, kasih nama exec_otosnapruby.sh
DO_TOKEN="b37013An937k0wEdul" /home/gagas/.rvm/wrappers/ruby-2.2.1/ruby /home/gagas/otosnap/otosnapruby.rb 292929

*Liat direktori ruby, direktori otosnapruby.rb dan id_droplet, jangan sampai keliru

Buat cron pake user gagas (karena yang install ruby adalah user gagas)
00 01 * * 0 /home/gagas/otosnap/exec_otosnapruby.sh
Setiap minggu jam 1 pagi akan dibuat snapshot.



MASALAH :

/home/gagas/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- rest_client (LoadError)
        from /home/gagas/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
        from ./snapshot.rb:2:in `<main>'

SOLUSI :
gem install rest_client
gem install rest-client

Komentar