lxc-config/hooks/create-lxc-config

61 lines
1.9 KiB
Ruby
Executable File

#!/usr/bin/env ruby
require "ostruct"
require "optparse"
require "json"
require_relative "lib/lxc"
def try_env(key)
ENV[key] or abort("environment variable '#{key}' not set")
end
options = OpenStruct.new
options.container_name = try_env("LXC_NAME")
options.container_config = try_env("LXC_CONFIG_FILE")
options.rootfs = try_env("LXC_ROOTFS_PATH")
OptionParser.new do |opts|
opts.banner = "Usage: create-lxc-config [options]"
opts.on("-4", "--ipv4", "private Ipv4 subnet") do |v|
options.ipv4 = v
end
opts.on("-6", "--ipv6", "public Ipv6 subnet") do |v|
options.ipv6 = v
end
opts.on("--dn42-ipv4", String, "dn42 ipv4") do |v|
options.dn42_ipv4 = v
end
opts.on("--dn42-ipv6", String, "dn42 ipv6") do |v|
options.dn42_ipv6 = v
end
opts.on("--group GROUP", String, "set ansible group (default NONE)") do |group|
options.group = group
end
opts.on("--vars FILE", String, "set json file for ansible variables") do |vars|
begin
options.vars = JSON.load(File.open(vars))
unless options.vars.is_a? Hash
abort "vars: Should be a json object"
end
rescue SystemCallError => e
abort "Failed to open '#{vars}': #{e.message}"
rescue JSON::ParserError => e
abort "Failed to parse ansible variables: #{e.message}"
end
end
end.parse!
registry = Lxc::Registry.new
container = Lxc::Container.new(registry.data,
name: options.container_name,
ipv4: options.ipv4,
ipv6: options.ipv6,
rootfs: options.rootfs,
dn42_ipv4: options.dn42_ipv4,
dn42_ipv6: options.dn42_ipv4,
group: options.group,
vars: options.vars)
container.write_config(options.container_config)
registry.save