Skip to content

Instantly share code, notes, and snippets.

@t9md
Created June 4, 2011 16:21
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save t9md/1008031 to your computer and use it in GitHub Desktop.
Save t9md/1008031 to your computer and use it in GitHub Desktop.
vagrant snapshot management command for one vm.
## place this file to same directory of `Vagrantfile' then simply require "snap.rb" in Vagrantfile
module Snap
module VBox
class SnapShot
require "forwardable"
extend Forwardable
def_delegators :@snap, :name, :uuid, :time_stamp
@@snaps = []
class << self
def is_endnode?() @@current.uuid == @@snaps.last.uuid end
def snaps() @@snaps end
def parse_tree(vmname)
vm = VirtualBox::VM.find( vmname )
@@current = vm.current_snapshot
return unless @@current
new(vm.root_snapshot).walk
end
end
def initialize(snap)
@snap = snap
self.class.snaps << self
end
def current?
snap.uuid == @@current.uuid
end
def register
end
attr_reader :snap
def have_child?
! @snap.children.empty?
end
def first_child
snap.children.first
end
def walk
if have_child?
s = self.class.new first_child
s.walk
end
end
end
end
class Command < Vagrant::Command::GroupBase
register "snap","Manages a snap"
no_tasks {
def vmname
@vagrant_env ||= Vagrant::Environment.new
@instance_name ||= "#{@vagrant_env.vms[:default].vm.name}"
@instance_name
end
}
desc "list", "list snapshot"
def list
format = " %s %-20s %s"
VBox::SnapShot.parse_tree( vmname )
result = VBox::SnapShot.snaps.map do |s|
cur_mark = s.current? ? "*" : " "
format % [ cur_mark, s.time_stamp.strftime("%Y%m%d-%H:%M:%S"), s.name ]
end
puts result
end
desc "go [SNAPNAME]", "go to specified snapshot"
def go(snapshot_name)
system "VBoxManage controlvm #{vmname} poweroff"
system "VBoxManage snapshot #{vmname} restore #{snapshot_name}"
system "VBoxManage startvm #{vmname} --type headless"
end
desc "back", "back to current snapshot"
def back
system "VBoxManage controlvm #{vmname} poweroff"
system "VBoxManage snapshot #{vmname} restorecurrent"
system "VBoxManage startvm #{vmname} --type headless"
end
desc "take", "take snapshot"
def take
VBox::SnapShot.parse_tree( vmname )
last = VBox::SnapShot.snaps.last
new_name = last ? last.name.succ : vmname + "-01"
# new_name = last.name.succ
if not last or VBox::SnapShot.is_endnode?
system "VBoxManage snapshot #{vmname} take #{new_name} --pause"
else
puts "Can not create"
end
end
desc "delete", "delete snapshot"
def delete(snapshot_name)
system "VBoxManage snapshot #{vmname} delete #{snapshot_name}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment