~mkelly/experiments

dc9fd890f5078baf35b881b0c4a8526099100154 — Michael Kelly 4 months ago c5d4441 master
LXC automation experiments
A lxc/README.md => lxc/README.md +10 -0
@@ 0,0 1,10 @@
# LXC

These are experimental scripts to create LXC containers that are usable as
long-lived workstations or servers. They are designed to be an alternative to
VMs.

These scripts all require you to have a working unprivileged LXC setup locally.

I wrote about my thought process and setup procedure here:
<https://blog.michaelkelly.org/2023/09/lxc-containers-on-debian-part-1-setup/>

A lxc/install-base.sh => lxc/install-base.sh +25 -0
@@ 0,0 1,25 @@
function systemd_wrap() {
  systemd-run --user --scope -p "Delegate=yes" -- "$@"
}

function get_container_ip() {
  local container=$1
  return $(systemd_wrap lxc-ls -f -F NAME,IPV4 | awk "\$1==\"$NAME\" { print \$2; }")
}

function lxc_create() {
  local name=$1
  local dist=$2
  local release=$3
  local arch=$4
  local variant=$5
  systemd_wrap lxc-create -t download -n "${name}" \
    -- --dist "${dist}" --release "${release}" --arch "${arch}" --variant "${variant}"
}

function lxc_start() {
  local name=$1
  systemd_wrap lxc-start "${name}"
}

export LXC_AUTHORIZED_KEYS=$(cat $HOME/.ssh/authorized_keys)

A lxc/install-debian.sh => lxc/install-debian.sh +16 -0
@@ 0,0 1,16 @@
#!/bin/bash
set -e
set -u

NAME=$1
source "$(dirname $0)/install-base.sh"

# Install and start container
lxc_create "$NAME" "debian" "bookworm" "amd64" "default"
lxc_start "$NAME"

# Very minimal and hacky provisioning
for script in provisioning/*; do
	echo -e "\n*** Running: ${script} ***"
	cat "${script}" | systemd_wrap lxc-attach "${NAME}" -- /bin/bash
done

A lxc/provisioning/01-user-setup.sh => lxc/provisioning/01-user-setup.sh +20 -0
@@ 0,0 1,20 @@
set -x

# ==========
# User setup
# ==========
# This should be distro-agnostic.

# This works because environment variables survive lxc-attach
/sbin/adduser --disabled-password --gecos "" $USER
mkdir -p /home/$USER/.ssh
chmod 0700 /home/$USER/.ssh
chown -R $USER:$USER /home/$USER/.ssh
echo "$USER ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/01-$USER
echo "$LXC_AUTHORIZED_KEYS" > /home/$USER/.ssh/authorized_keys

# ===========
# Weird hacks
# ===========
# See https://forum.proxmox.com/threads/ping-with-unprivileged-user-in-lxc-container-linux-capabilities.42308/
/sbin/setcap cap_net_raw+p /bin/ping

A lxc/provisioning/02-deb-packages.sh => lxc/provisioning/02-deb-packages.sh +9 -0
@@ 0,0 1,9 @@
set -x

# ===================================
# Basic system setup - debian version
# ===================================
apt-get update
apt-get upgrade -y
apt-get install -y openssh-server man curl python3