lxc-config/hooks/update-hetzner-rdns

52 lines
1.5 KiB
Ruby
Executable File

#!/usr/bin/env ruby
require "netaddr"
require "set"
require_relative "lib/lxc"
def update_hetzner_rdns6(user, password, domain, subnet, network)
api = Lxc::Hetzner.new(user, password)
rdns = api.get("/rdns")
records = {}
rdns.each do |val|
rec = val["rdns"]
cidr = NetAddr::CIDR.create(rec["ip"])
next unless cidr.version == 6 and subnet.contains?(rec["ip"])
records[rec["ip"]] = rec["ptr"]
end
processed_ips = Set.new
network.each do |host, data|
cidr = data["ipv6"]
next if cidr.nil?
cidr = NetAddr::CIDR.create(cidr)
next unless cidr.version == 6 and subnet.contains?(data["ipv6"])
hostname = data["rdns6"] || "#{host}.#{domain}"
ip = cidr.ip(Short: true)
next if processed_ips.include?(ip)
processed_ips << ip
ptr = records.delete(ip)
if ptr.nil? or ptr != hostname
puts "add ptr: #{ip} -> #{hostname}"
api.post("/rdns/#{ip}", ptr: hostname)
end
end
records.each do |ip, ptr|
puts "delete ptr: #{ip} -> #{ptr}"
api.delete("/rnds/#{ip}", allow_404: true)
end
end
registry = Lxc::Registry.new
registry.data["zone"] ||= {}
domain = registry.data["zone"]["ipv6-domain"] || "lxc"
subnet = registry.data["zone"]["v6_subnet"]
if subnet
subnet_cidr = NetAddr::CIDR.create(subnet)
credentials = File.read(Lxc::CONFIG_ROOT.join("hetzner.key"))
user, password = credentials.split(":")
network = registry.data["network"] || {}
update_hetzner_rdns6(user, password, domain, subnet_cidr, network)
else
puts "no v6_subnet specified in container.json. skip rdns records"
end