lxc-config/hooks/create-lxc-config

79 lines
2.4 KiB
Ruby
Executable File

#!/usr/bin/env ruby
require "json"
require "pathname"
require 'ostruct'
require 'optparse'
require 'json'
require 'netaddr'
require_relative 'lib/container'
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!
CONFIG_PATH = Pathname.new("/etc/lxc/")
container_data = CONFIG_PATH.join("container.json")
data = if File.exists?(container_data)
JSON.load(File.open(container_data))
else
{}
end
data["network"] ||= {}
data["network"][options.container_name] = {}
network = data["network"][options.container_name]
network["ipv4"] = NetAddr::CIDR.create(ipv4_address).to_s(Short: true)
network["ipv6"] = NetAddr::CIDR.create(ipv6_address).to_s(Short: true)
network["group"] = options.group
network["vars"] = options.vars
open(container_data, File::CREAT|File::TRUNC|File::RDWR) do |f|
f.write(JSON.pretty_generate(data))
end
container = Container.new(data,
name: options.container_name,
ipv4: ipv4_address,
ipv6: ipv6_address,
rootfs: options.rootfs,
dn42_ipv4: options.dn42_ipv4,
dn42_ipv6: options.dn42_ipv4)
container.write_config(options.container_config)