my-homelab-configs/bootstrap/provisioning/templates/prepare-template.sh.tftpl

96 lines
2.6 KiB
Bash

#!/bin/sh
set -eu
verify_kernel_cgroups() {
boot_options="${kernel_cgroup_boot_options}"
cmdline=" $(cat /proc/cmdline) "
for option in $boot_options; do
case "$cmdline" in
*" $option "*) ;;
*)
echo "Missing kernel boot option: $option" >&2
exit 1
;;
esac
done
if [ ! -d /sys/fs/cgroup ]; then
echo "Missing /sys/fs/cgroup" >&2
exit 1
fi
if [ -f /sys/fs/cgroup/cgroup.controllers ]; then
if ! grep -qw memory /sys/fs/cgroup/cgroup.controllers; then
echo "Missing memory controller in cgroup v2" >&2
exit 1
fi
return 0
fi
if ! awk '$1 == "memory" && $4 == "1" { found = 1 } END { exit found ? 0 : 1 }' /proc/cgroups; then
echo "Missing enabled memory cgroup controller" >&2
exit 1
fi
}
verify_kernel_cgroups
cat >/usr/local/sbin/homelab-firstboot-node.sh <<'SCRIPT'
#!/bin/sh
set -eu
systemd-machine-id-setup
ssh-keygen -A
template_hostname='${template_hostname}'
clone_hostname_prefix='${clone_hostname_prefix}'
template_domain='${template_domain}'
current_hostname="$(hostnamectl --static 2>/dev/null || hostname)"
if [ -z "$current_hostname" ] || [ "$current_hostname" = "$template_hostname" ] || [ "$current_hostname" = "localhost" ]; then
machine_id="$(cat /etc/machine-id 2>/dev/null | tr -dc '[:xdigit:]' | cut -c1-8)"
if [ -z "$machine_id" ]; then
machine_id="$(od -An -N4 -tx1 /dev/urandom | tr -d ' \n')"
fi
current_hostname="$clone_hostname_prefix-$machine_id"
hostnamectl set-hostname "$current_hostname"
fi
if grep -q '^127[.]0[.]1[.]1[[:space:]]' /etc/hosts; then
sed -i "s/^127[.]0[.]1[.]1[[:space:]].*/127.0.1.1 $current_hostname.$template_domain $current_hostname/" /etc/hosts
else
printf '127.0.1.1 %s.%s %s\n' "$current_hostname" "$template_domain" "$current_hostname" >>/etc/hosts
fi
rm -f /etc/homelab-template-sealed
systemctl disable homelab-firstboot-node.service >/dev/null 2>&1 || true
SCRIPT
chmod 0755 /usr/local/sbin/homelab-firstboot-node.sh
cat >/etc/systemd/system/homelab-firstboot-node.service <<'SERVICE'
[Unit]
Description=Initialize cloned homelab node identity
Before=ssh.service
ConditionPathExists=/etc/homelab-template-sealed
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/homelab-firstboot-node.sh
[Install]
WantedBy=multi-user.target
SERVICE
systemctl enable homelab-firstboot-node.service >/dev/null
cloud-init clean --logs >/dev/null 2>&1 || true
rm -f /etc/ssh/ssh_host_*
rm -f /var/lib/dbus/machine-id
ln -sf /etc/machine-id /var/lib/dbus/machine-id
: >/etc/machine-id
touch /etc/homelab-template-sealed
apt-get clean
rm -rf /tmp/* /var/tmp/*
sync
echo "Power off this VM and convert it to a Pimox template."