Skip to content

Instantly share code, notes, and snippets.

@artizirk
Last active April 23, 2020 11:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artizirk/28f2f8c140c77fb33f60c3619eb142de to your computer and use it in GitHub Desktop.
Save artizirk/28f2f8c140c77fb33f60c3619eb142de to your computer and use it in GitHub Desktop.
#!/bin/bash -e
BASE="/var/lib/machines"
LANG="C.UTF-8"
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root" 1>&2
exit 1
fi
function deleteContainer {
rm -rf $BASE/$name
exit;
}
while getopts 'hn:d' flag; do
case "${flag}" in
h) echo "-n container name; -h help";;
n) name="${OPTARG}" ;;
d) deleteContainer ;;
*) echo "Unexpected option ${flag}" ;;
esac
done
if [ -z ${name+x} ]; then
echo "container name is unset"
exit;
else
echo "Container name is $name"
fi
function mustRun {
"$@"
local status=$?
if [ $status -ne 0 ]; then
echo "error with $1" >&2
exit;
fi
return $status
}
mustRun mkdir -p "$BASE/$name"
mustRun debootstrap --variant=minbase --include=systemd,systemd-sysv,dbus,ssh,iputils-ping,iproute2 xenial "$BASE/$name"
if [ ! -d "$BASE/$name/root/.ssh" ]; then
mkdir "$BASE/$name/root/.ssh"
chmod 700 "$BASE/$name/root/.ssh"
if [ ! -f "$BASE/$name/root/.ssh/authorized_keys" ]; then
cp -v /root/.ssh/authorized_keys "$BASE/$name/root/.ssh/authorized_keys"
chmod 600 "$BASE/$name/root/.ssh/authorized_keys"
echo "added ssh keys to root"
fi
else
echo "ssh keys probably already added"
fi
if [[ ! -L "$BASE/$name/etc/resolv.conf" ]]; then
rm "$BASE/$name/etc/resolv.conf"
fi
if [[ -e "$BASE/$name/etc/hostname" ]]; then
rm "$BASE/$name/etc/hostname"
fi
echo $name | awk '{print toupper($0)}' | figlet > "$BASE/$name/etc/motd"
echo "PS1='\[\033[01;31m\]\u\[\033[37m\]@\[\033[01;93m\]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '" >> "$BASE/$name/root/.bashrc"
mustRun systemd-nspawn -D "$BASE/$name" --pipe /bin/bash <<'EOF'
echo "Now running inside nspawn $(pwd)"
systemctl enable systemd-networkd
systemctl enable systemd-resolved
systemctl enable ssh
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment