KVM on Ubuntu 14 上に VM を自動生成するスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -e | |
[ ! -z $DEBUG ] && set -x | |
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin | |
if [ $# -ne 4 ]; then | |
echo "Usage: `basename $0` NAME IPADDR NETMASK GATEWAY" 1>&2 | |
exit 1 | |
fi | |
NAME=$1 | |
IPADDR=$2 | |
NETMASK=$3 | |
GATEWAY=$4 | |
PASSWD=`cat /dev/urandom | tr -cd '[:alnum:]' | fold -w32 | head -1` | |
RELEASE=${RELEASE:-trusty} | |
TIMEZONE=${TIMEZONE:-Asia/Tokyo} | |
BRIDGE=${BRIDGE:-br0} | |
MEMORY=${MEMORY:-512} | |
DISK=${DISK:-8} | |
CPU=${CPU:-2} | |
cd `dirname $0` | |
which uvt-kvm > /dev/null \ | |
|| sudo apt-get install -y uvtool | |
uvt-simplestreams-libvirt query | grep -q $RELEASE \ | |
|| uvt-simplestreams-libvirt sync release=$RELEASE arch=amd64 | |
if [ ! -f ~/.ssh/id_rsa.pub ]; then | |
mkdir -p ~/.ssh | |
ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa | |
fi | |
mkdir -p tmp | |
cat << __EOM__ > tmp/$NAME.sh | |
cp -p /usr/share/zoneinfo/$TIMEZONE /etc/localtime | |
echo "auto eth0 | |
iface eth0 inet static | |
address $IPADDR | |
netmask $NETMASK | |
gateway $GATEWAY | |
dns-nameservers 8.8.8.8 8.8.4.4" > /etc/network/interfaces.d/eth0.cfg | |
__EOM__ | |
if [ -f authorized_keys ]; then | |
PUBKEYS=`cat authorized_keys` | |
cat << __EOM__ >> tmp/$NAME.sh | |
echo "$PUBKEYS" >> /home/ubuntu/.ssh/authorized_keys | |
__EOM__ | |
fi | |
if [ -f setup.sh ]; then | |
cat setup.sh >> tmp/$NAME.sh | |
fi | |
echo "creating vm..." | |
uvt-kvm create \ | |
--memory $MEMORY \ | |
--disk $DISK \ | |
--cpu $CPU \ | |
--password $PASSWD \ | |
--run-script-once tmp/$NAME.sh \ | |
$NAME \ | |
release=$RELEASE | |
uvt-kvm wait --insecure $NAME | |
echo "done" | |
uvt-kvm ssh --insecure $NAME "sudo shutdown -h now" | |
sudo cp -pv /etc/libvirt/qemu/$NAME.xml /tmp/$NAME.xml | |
sudo chown $USER /tmp/$NAME.xml | |
sed -i -e 's/127\.0\.0\.1/0.0.0.0/' /tmp/$NAME.xml | |
sed -i -e "s/interface type='network'/interface type='bridge'/" /tmp/$NAME.xml | |
sed -i -e "s/source network='default'/source bridge='$BRIDGE'/" /tmp/$NAME.xml | |
virsh undefine $NAME | |
virsh define /tmp/$NAME.xml | |
echo "waiting shutdown..." | |
while [ 1 ]; do | |
STATE=`virsh domstate $NAME | head -1` | |
[ "$STATE" = "shut off" ] && break | |
sleep 2 | |
done | |
virsh start $NAME | |
echo ====================================== | |
echo "USER: ubuntu" | |
echo "PASS: $PASSWD" | |
echo ====================================== |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment