还要让镜像系统能从OpenStack的元数据服务中读取必要的信息并更新系统中的配置文件,如hostname,否则新建的实例不会根据实例名更改hostname。要实现这个,可以安装openstack的cloud-in组件,也可以自己写启动脚本,以启动脚本为例:
vi /mnt/CentOS-image/etc/rc.local
在#!/bin/sh和touch /var/lock/subsys/local之间加上如下的脚本:
if [ ! -d /root/.ssh ]; then
mkdir -p /root/.ssh
chmod 700 /root/.ssh
fi
# Fetch hostname using HTTP
ATTEMPTS=30
FAILED=0
while [ ! -f /tmp/metadata-hostname ]; do
curl -f http://169.254.169.254/latest/meta-data/hostname > /tmp/metadata-hostname 2>/dev/null
if [ $? -eq 0 ]; then
TEMP_HOST=`cat /tmp/metadata-hostname | awk -F '.' '{print $1}'`
sed -i "s/^HOSTNAME=.*$/HOSTNAME=$TEMP_HOST/g" /etc/sysconfig/network
/bin/hostname $TEMP_HOST
echo "Successfully retrieved hostname from instance metadata"
echo "*****************"
echo "HOSTNAME CONFIG"
echo "*****************"
cat /etc/sysconfig/network
echo "*****************"
else
echo "Failed to retrieve hostname from instance metadata. This is a soft error, so we'll continue"
FAILED=$(($FAILED + 1))
if [ $FAILED -ge $ATTEMPTS ]; then
echo "Failed to retrieve hostname from instance metadata after $FAILED attempts, quitting"
break
fi
echo "Could not retrieve hostname from instance metadata (attempt #$FAILED/$ATTEMPTS), retrying in 5 seconds..."
rm -f /tmp/metadata-hostname
sleep 5
fi
done
rm -f /tmp/metadata-hostname
然后配置系统的用户:
chroot /mnt/centos-image/
passwd
adduser xc
passwd xc
chmod u+w /etc/sudoers
vi /etc/sudoers
chmod u-w /etc/sudoers
mkinitrd --with virtio_pci --with virtio_ring --with virtio_blk --with virtio_net --with virtio_balloon --with virtio -f /boot/initramfs-$(ls /lib/modules/).img $(ls /lib/modules/)
exit
4. 上传镜像
准备好镜像:
cp /mnt/centos-image/boot/initramfs-$(ls /mnt/centos-image/lib/modules/).img ~/centos-image/
cp /mnt/centos-image/boot/vmlinuz* ~/centos-image/
umount /mnt/centos-image
将做好的镜像文件(包含三个文件)拷贝到OpenStack Controller Node上:
scp -r ~/centos-image xxx@10.77.xx.xx:~/centos-image
rm -rf ~/centos-image
rm -rf /mnt/centos-image
登录到OpenStack Controller Node上,将镜像上传到OpenStack中,上传之前要先设置glance的环境变量,这里不说了:
glance add name="CentOS 6.4 b52img kernel" is_public=true container_format=aki disk_format=aki < ~/centos-image/vmlinuz-2.6.32-358.11.1.el6.x86_64
glance add name="CentOS 6.4 b52img ramdisk" is_public=true container_format=ari disk_format=ari < ~/centos-image/initramfs-2.6.32-358.11.1.el6.x86_64.img
glance add name="CentOS 6.4 b52img" is_public=true container_format=ami disk_format=ami kernel_id=xxx ramdisk_id=xxx < ~/centos-image/centos.img
其中的xxx分别是,执行前两句得到的kernel id和ramdisk id。
用新建的镜像启动一个实例,正常的话就算是成功了。
