chrootを用いた簡易な開発環境の構築
Linuxにおいて開発環境の為に仮想機械やdockerを試したが、強力すぎて宝の持ち腐れな上にリソースを食うので簡単な仮想環境としてchrootを扱うことが増えてきたのでまとめ。
debootstrapなどを用いて環境を作るまではいいが、そのあとやらなければならないことがある。
それは
- file system としてカーネルから提供されてるAPIのprocfsとsysfsとdevfs。
- resolv.conf
最低限はここらへんだと思う。
/etc/fstabに書き込めばって感じだけど、適当に作って適当に壊す環境がほしいので今回は見送り
今回はこれに加えて
- chroot内からのXを用いるアプリケーション
- ssh key
これらを毎回手動でやるのも疲れるのでshell scriptにまとめた。
shell scriptもいい感じに書けないので、変更したほうが良い点などを教えてもらえれば嬉しい。
#!/bin/bash
# set -x
set -eu
if [ $# -ne 1 ]; then
echo 'example'
echo ' $ chroot_plus.sh /home/hogehoge/chroot/debian_root'
exit
fi
if [ ${EUID:-${UID}} != 0 ]; then
echo 'You are not root'
exit
fi
if [[ -v SUDO_USER ]]; then
echo username: $SUDO_USER
user=$SUDO_USER
else
echo "cannot detect user."
exit 1
fi
dest_dir=$1
mount_out=`mount`
# tmpfs
if ! echo ${mount_out} | grep ${dest_dir}/tmp > /dev/null ; then
mount -t tmpfs tmpfs ${dest_dir}/tmp
echo "[tmpfs] mounted."
else
echo "[tmpfs] already mounted."
fi
# devfs
if ! echo ${mount_out} | grep ${dest_dir}/dev > /dev/null; then
mount --rbind /dev ${dest_dir}/dev
echo "[devfs] mounted."
else
echo "[devfs] already mounted."
fi
# sysfs
if ! echo ${mount_out} | grep ${dest_dir}/sys > /dev/null; then
mount -t sysfs sysfs ${dest_dir}/sys
echo "[sysfs] mounted."
else
echo "[sysfs] already mounted."
fi
# copy resolv.conf
if [ ! -d ${dest_dir}/etc ]; then
echo "${dest_dir}/etc is not found."
exit 1
else
cp /etc/resolv.conf ${dest_dir}/etc/resolv.conf
fi
# mount .ssh dir
if [ ! -d ${dest_dir}/home/${user}/.ssh ]; then
echo "${dest_dir}"/home/${user}/.ssh is not found.
exit 1
else
mount --rbind /home/${user}/.ssh ${dest_dir}/home/${user}/.ssh
fi
# for x application
xhost +local:
# change root!
chroot ${dest_dir} /bin/bash
exit 1
posix警察に殺されそう