Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/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