49 lines
1.4 KiB
Bash
49 lines
1.4 KiB
Bash
#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
|
|
USER="$1"
|
|
KEYFILE="$2"
|
|
CONTAINER="lxc-${USER}"
|
|
|
|
echo "Creating LXC container ${CONTAINER}..."
|
|
# lxc-create -n "$CONTAINER" -t download -- -d ubuntu -r noble -a amd64
|
|
lxc-create -n "$CONTAINER" -f /etc/lxc/default.conf -t download -- -d ubuntu -r noble -a amd64
|
|
|
|
# start it
|
|
lxc-start -n "$CONTAINER"
|
|
|
|
# wait for networking
|
|
sleep 5
|
|
|
|
# set root password, install SSH, inject key
|
|
lxc-attach -n "$CONTAINER" -- /bin/bash -c "
|
|
apt-get update && apt-get install -y openssh-server
|
|
mkdir -p /root/.ssh
|
|
chmod 700 /root/.ssh
|
|
sed -i 's/#PermitRootLogin.*/PermitRootLogin prohibit-password/' /etc/ssh/sshd_config
|
|
systemctl enable ssh
|
|
systemctl restart ssh
|
|
"
|
|
|
|
# push the key in
|
|
cat "$KEYFILE" | lxc-attach -n "$CONTAINER" -- tee /root/.ssh/authorized_keys > /dev/null
|
|
lxc-attach -n "$CONTAINER" -- chmod 600 /root/.ssh/authorized_keys
|
|
|
|
# auto-start on boot
|
|
echo "lxc.start.auto = 1" >> "/var/lib/lxc/${CONTAINER}/config"
|
|
|
|
# get container IP
|
|
CONTAINER_IP=$(lxc-info -n "$CONTAINER" -iH | head -1)
|
|
|
|
# create host user that maps to this container
|
|
useradd -m -s /bin/bash -G labmates "$USER" 2>/dev/null || true
|
|
mkdir -p "/home/${USER}/.ssh"
|
|
cp "$KEYFILE" "/home/${USER}/.ssh/authorized_keys"
|
|
chown -R "${USER}:${USER}" "/home/${USER}/.ssh"
|
|
chmod 700 "/home/${USER}/.ssh"
|
|
|
|
# store mapping
|
|
echo "$CONTAINER" > "/home/${USER}/.lxc-container"
|
|
|
|
echo "Done. ${USER} SSH -> root@${CONTAINER} (${CONTAINER_IP})"
|