Skip to content

Instantly share code, notes, and snippets.

@Vedrillan
Last active January 16, 2019 09:30
Show Gist options
  • Save Vedrillan/4e0d6a214b3b4b66dc84ac77a377746b to your computer and use it in GitHub Desktop.
Save Vedrillan/4e0d6a214b3b4b66dc84ac77a377746b to your computer and use it in GitHub Desktop.
Script used to create the lxc container
#!/bin/bash
POSITIONAL=()
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-n|--name)
NAME="$2"
shift # past argument
shift # past value
;;
-i|--image)
IMAGE="$2"
shift # past argument
shift # past value
;;
-m|--create-mount)
CREATE_MOUNT_POINT="YES"
shift # past argument
;;
*) # unknown option
POSITIONAL+=("$1") # save it in an array for later
shift # past argument
;;
esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters
IMAGE=${IMAGE:-ubuntu:16.04}
if [ -z "$NAME" ]
then
echo "You must provide a container name"
exit 1
fi
if ! lxc launch "$IMAGE" $NAME; then
exit 1
fi
lxc config set $NAME boot.autostart true
# wait for network to be setup
TIMEOUT=30
while ! lxc info $NAME | grep 'eth0:' | grep -qw inet; do
sleep 1
TIMEOUT=$(($TIMEOUT - 1))
if [ $TIMEOUT -eq 0 ] ; then
exit 1
fi
done
echo "Setup ssh service"
# add sshd to lxc
lxc exec $NAME -- /bin/bash -c "apt install -y openssh-server python sudo" &>/dev/null
LXCIPADDR=$(lxc info $NAME | grep 'eth0:' | grep -w inet | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
# add container to host file
if ! grep "$NAME.lxd #lxdeploy" /etc/hosts ; then
echo -en "$LXCIPADDR $NAME.lxd #lxdeploy\n" | sudo tee -a /etc/hosts >/dev/null
fi
# add container key to known hosts file
ssh-keyscan "$NAME.lxd" >> ~/.ssh/known_hosts 2> /dev/null
ssh-keyscan "$LXCIPADDR" >> ~/.ssh/known_hosts 2> /dev/null
# add user ssh pub key to container root authorized keys
lxc exec $NAME -- /bin/bash -c "mkdir -p /root/.ssh"
for key in ~/.ssh/*.pub
do
lxc exec $NAME -- /bin/bash -c "echo $(cat $key) >> /root/.ssh/authorized_keys"
done
# create mount point
if [ "$CREATE_MOUNT_POINT" = "YES" ]; then
lxc exec $NAME -- /bin/bash -c "mkdir -p /var/www/$NAME/current"
lxc config device add $NAME project_source disk source=$(pwd) path=/var/www/$NAME/current
fi
# manage user mapping
echo -en "uid $(id -u) 1101\ngid $(id -g) 33" | lxc config set $NAME raw.idmap -
lxc restart -f $NAME
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment