Skip to content

Instantly share code, notes, and snippets.

@numinit
Created January 31, 2016 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save numinit/9b5462fa52f0b142d24a to your computer and use it in GitHub Desktop.
Save numinit/9b5462fa52f0b142d24a to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'erb'
require 'tempfile'
require 'shellwords'
require 'logger'
module Libvirt
class ERBContext
def initialize logger
@logger = logger
end
def include file
@logger.info "including `#{file}`"
File.read file
end
def get_binding
binding
end
end
end
raise "usage: #$0 input.xml.erb" unless ARGV.length == 1
# Create a logger
name = File.basename(__FILE__).freeze
logger = Logger.new STDERR
logger.progname = name
# Evaluate the erb
erb = File.realpath ARGV.first
logger.info "evaluating `#{erb}`"
xml = ERB.new(File.read(erb)).result Libvirt::ERBContext.new(logger).get_binding
# Create a tempfile
tmp = Tempfile.new name
tmp.sync = true
begin
# Write the XML
logger.info 'defining domain'
tmp.write xml
# Define it through virsh
result = `#{%W[virsh define #{tmp.path}].shelljoin}`
result = "virsh (#{$?.exitstatus}): #{result.strip}"
if $?.exitstatus == 0
logger.info result
else
logger.error result
end
ensure
# Close it out
tmp.close unless tmp.closed?
tmp.unlink
end
# Exit, using the status from virsh
exit $?.exitstatus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment