+ mode "644"
+ content YAML.dump(netplan)
+end
+
+package "cloud-init" do
+ action :purge
+end
+
+if node[:networking][:wireguard][:enabled]
+ wireguard_id = persistent_token("networking", "wireguard")
+
+ node.default[:networking][:wireguard][:address] = "fd43:e709:ea6d:1:#{wireguard_id[0, 4]}:#{wireguard_id[4, 4]}:#{wireguard_id[8, 4]}:#{wireguard_id[12, 4]}"
+
+ package "wireguard-tools" do
+ compile_time true
+ end
+
+ directory "/var/lib/systemd/wireguard" do
+ owner "root"
+ group "systemd-network"
+ mode "750"
+ compile_time true
+ end
+
+ file "/var/lib/systemd/wireguard/private.key" do
+ action :create_if_missing
+ owner "root"
+ group "systemd-network"
+ mode "640"
+ content %x(wg genkey)
+ compile_time true
+ end
+
+ node.default[:networking][:wireguard][:public_key] = %x(wg pubkey < /var/lib/systemd/wireguard/private.key).chomp
+
+ file "/var/lib/systemd/wireguard/preshared.key" do
+ action :create_if_missing
+ owner "root"
+ group "systemd-network"
+ mode "640"
+ content keys["wireguard"]
+ end
+
+ if node[:roles].include?("gateway")
+ search(:node, "roles:gateway") do |gateway|
+ next if gateway.name == node.name
+ next unless gateway[:networking][:wireguard] && gateway[:networking][:wireguard][:enabled]
+
+ allowed_ips = gateway.interfaces(:role => :internal).map do |interface|
+ "#{interface[:network]}/#{interface[:prefix]}"
+ end
+
+ node.default[:networking][:wireguard][:peers] << {
+ :public_key => gateway[:networking][:wireguard][:public_key],
+ :allowed_ips => allowed_ips,
+ :endpoint => "#{gateway.name}:51820"
+ }
+ end
+ end
+
+ template "/etc/systemd/network/wireguard.netdev" do
+ source "wireguard.netdev.erb"
+ owner "root"
+ group "systemd-network"
+ mode "640"
+ end
+
+ template "/etc/systemd/network/wireguard.network" do
+ source "wireguard.network.erb"
+ owner "root"
+ group "root"
+ mode "644"
+ end
+
+ if node[:lsb][:release].to_f < 20.04
+ execute "ip-link-delete-wg0" do
+ action :nothing
+ command "ip link delete wg0"
+ subscribes :run, "template[/etc/systemd/network/wireguard.netdev]"
+ only_if { ::File.exist?("/sys/class/net/wg0") }
+ end
+
+ service "systemd-networkd" do
+ action :nothing
+ subscribes :restart, "template[/etc/systemd/network/wireguard.netdev]"
+ subscribes :restart, "template[/etc/systemd/network/wireguard.network]"
+ not_if { ENV.key?("TEST_KITCHEN") }
+ end
+ else
+ execute "networkctl-delete-wg0" do
+ action :nothing
+ command "networkctl delete wg0"
+ subscribes :run, "template[/etc/systemd/network/wireguard.netdev]"
+ only_if { ::File.exist?("/sys/class/net/wg0") }
+ end
+
+ execute "networkctl-reload" do
+ action :nothing
+ command "networkctl reload"
+ subscribes :run, "template[/etc/systemd/network/wireguard.netdev]"
+ subscribes :run, "template[/etc/systemd/network/wireguard.network]"
+ not_if { ENV.key?("TEST_KITCHEN") }
+ end
+ end