Skip to content

Instantly share code, notes, and snippets.

@ParagDoke
Last active November 2, 2020 15:21
Show Gist options
  • Save ParagDoke/2aa3f66b4d1be0161e50 to your computer and use it in GitHub Desktop.
Save ParagDoke/2aa3f66b4d1be0161e50 to your computer and use it in GitHub Desktop.
Bash script to create a bare bones CentOS 7 VirtualBox VM with guest additions, as a local Vagrant box
#!/bin/bash -e
echo "Starting `basename $0`"
box_os=CentOS
box_os_version=7.1
echo "Searching for grep ..."
which grep
echo "Searching for sed ..."
which sed
echo "Searching for VirtualBox ..."
which vboxmanage
echo "Searching for lftp ..."
which lftp
echo "Searching for fuseiso ..."
which fuseiso
echo "Searching for fusermount ..."
which fusermount
echo "Searching for gzip ..."
which gzip
echo "Searching for mkisofs ..."
which mkisofs
# As of 9 Nov 2015, there are 5 mirrors for centos in India
# Of those only, 1 is in Bombay/Mumbai (proximity to Pune)
mirror_url="http://centos.excellmedia.net/"
# TODO: Find metalink to pass to curl/aria2 for ISO
# Download filelist, then extract and figure ISO path
lftp -c "get ${mirror_url}/filelist.gz"
rm filelist || echo "No filelist to delete"
gzip -d filelist.gz
relative_iso_url=`grep -i minimal filelist | grep -i iso | grep -i ${box_os_version} | grep -v torrent | sed -e 's/^\.//'`
absolute_iso_url="${mirror_url}${relative_iso_url}"
absolute_iso_folder_url=`dirname ${absolute_iso_url}`
iso_filename=`basename ${absolute_iso_url}`
lftp -c "mirror --verbose --only-newer --parallel=4 --use-pget=4 --include=${iso_filename} ${absolute_iso_folder_url}"
# ISO will get downloaded to x86_64 folder
rm -r iso_extract || echo "No iso_extract" folder to clean
mkdir -p iso_extract
# Mount ISO
fuseiso ./x86_64/${iso_filename} ./iso_extract
chmod -R u+w iso_new || echo "No iso_new folder to make writable"
rm -r iso_new || echo "No iso_new folder to clean"
mkdir -p iso_new
lftp -c "mirror --parallel=8 --use-pget=8 file://`pwd`/iso_extract file://`pwd`/iso_new"
fusermount -u ./iso_extract
cp ks.cfg ./iso_new/
chmod +w ./iso_new/isolinux/isolinux.cfg
sed -r -i -e 's/^timeout [0-9]+/timeout 10/' -e '/menu default/d' ./iso_new/isolinux/isolinux.cfg
sed -r -i -e "s/label check/label custom\n menu label ^Unattended install\n kernel vmlinuz\n menu default\n append initrd=initrd.img ks=cdrom:\/ks.cfg in
st.stage2=hd:LABEL=${box_os}-${box_os_version}-Custom xvdriver=vesa nomodeset text\n\nlabel check/" ./iso_new/isolinux/isolinux.cfg
pushd iso_new
mkisofs -o ../${box_os}-${box_os_version}-Custom.iso -quiet -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -J
-R -V "${box_os}-${box_os_version}-Custom" .
popd
# Create bare bones VM using VirtualBox
virtualbox_vm_name="CentOS-7.1-minimal"
vboxmanage unregistervm ${virtualbox_vm_name} || echo "No VM by name ${virtualbox_vm_name}"
rm -r VirtualBoxVM || echo "No VirtualBoxVM folder to clean"
mkdir -p VirtualBoxVM
vboxmanage createvm --name ${virtualbox_vm_name} --ostype "RedHat_64" --register --basefolder=`pwd`/VirtualBoxVM
vboxmanage createhd --filename `pwd`/VirtualBoxVM/${virtualbox_vm_name}.vdi --size 2048
vboxmanage storagectl ${virtualbox_vm_name} --name "SATA Controller" --add sata --controller IntelAHCI
vboxmanage storageattach ${virtualbox_vm_name} --storagectl "SATA Controller" --port 0 --device 0 --type hdd --medium `pwd`/VirtualBoxVM/${virtualbox_vm_name
}.vdi
vboxmanage storagectl ${virtualbox_vm_name} --name "IDE Controller" --add ide
vboxmanage storageattach ${virtualbox_vm_name} --storagectl "IDE Controller" --port 0 --device 0 --type dvddrive --medium `pwd`/${box_os}-${box_os_version}-C
ustom.iso
vboxmanage storageattach ${virtualbox_vm_name} --storagectl "IDE Controller" --port 1 --device 0 --type dvddrive --medium emptydrive
vboxmanage storageattach ${virtualbox_vm_name} --storagectl "IDE Controller" --port 1 --device 0 --type dvddrive --medium additions
vboxmanage modifyvm ${virtualbox_vm_name} --memory 512 --vram 12 --acpi on --ioapic on
vboxmanage modifyvm ${virtualbox_vm_name} --boot1 dvd --boot2 disk --boot3 none --boot4 none
echo "Unattended install start ..."
date
vboxmanage startvm ${virtualbox_vm_name} --type headless
# http://superuser.com/questions/547980/bash-script-to-wait-for-virtualbox-vm-shutdown
until $(vboxmanage showvminfo --machinereadable ${virtualbox_vm_name} | grep -q ^VMState=.poweroff.); do
sleep 10
done
echo "Unattended install end ..."
date
vboxmanage storagectl ${virtualbox_vm_name} --name "IDE Controller" --remove
vboxmanage storagectl ${virtualbox_vm_name} --name "IDE Controller" --add ide
vboxmanage storageattach ${virtualbox_vm_name} --storagectl "IDE Controller" --port 0 --device 0 --type dvddrive --medium emptydrive
# No intention of uploading to atlas at the moment. Use any name.
vagrant package --base ${virtualbox_vm_name} --output my-centos7.1-vbguestadditions.box
vagrant box add --force --provider virtualbox --name "my/centos7.1-vbguestadditions" my-centos7.1-vbguestadditions.box
echo "Finished `basename $0`"
#version=RHEL7
install
# System authorization information
auth --enableshadow --passalgo=sha512
# Use CDROM installation media
cdrom
# Use text mode install
text
# Run the Setup Agent on first boot
firstboot --enable
ignoredisk --only-use=sda
# Keyboard layouts
keyboard --vckeymap=us --xlayouts='us'
# System language
lang en_US.UTF-8
# Network information
network --bootproto=dhcp --device=enp0s3 --noipv6
network --hostname=localhost.localdomain
# Root password
# Password is "vagrant" without quotes
rootpw --iscrypted $6$7pSAZVtVyawkrXts$yRNGLL6x79QWXSmBQtPqAfEJ4kkg0NZttvE4gOrQgu11iwwM9ZlSvG8Ud8AMGa1HSE5fpnFdTozlvF44juqVy0
# Do not configure the X Window System
skipx
# System timezone
timezone Asia/Kolkata --isUtc
# Password is "vagrant" without quotes
user --groups=wheel --name=vagrant --password=$6$wPyxNMC5tmmb2zkx$QVwciP2LL/EC4xBAYLop7ADuog5KdQxG3KaQxABXPnCKNSD..e4HpeJPmhFWQdmxl8jNi2qWAaPrGOlHLB3qG/ --is
crypted --gecos="vagrant"
zerombr
# Partition clearing information
# clearpart --all --initlabel --drives=sda
clearpart --all --initlabel
# System bootloader configuration
bootloader --location=mbr --boot-drive=sda
autopart --type=lvm
poweroff
%packages
@core
%end
%addon com_redhat_kdump --disable --reserve-mb='auto'
%end
%post --log=/root/ks-post.log
# Login vagrant will be a member of group wheel because of kickstart
# Filename under sudoers.d should not end with ~ or have . character
echo '%wheel ALL=(ALL) NOPASSWD: ALL'> /etc/sudoers.d/wheel
echo 'Defaults!ALL !requiretty'> /etc/sudoers.d/norequiretty
yum install -y kernel-headers-$(uname -r) kernel-devel-$(uname -r)
yum install -y gcc dkms yum-utils bzip2
mkdir /tmp/vbguestadditions
mount -o ro /dev/sr1 /tmp/vbguestadditions
/tmp/vbguestadditions/VBoxLinuxAdditions.run --nox11
umount /tmp/vbguestadditions
rm -r /tmp/vbguestadditions
curl --location "https://github.com/mitchellh/vagrant/raw/master/keys/vagrant.pub" --output /tmp/vagrant.pub
mkdir -p /root/.ssh
cat /tmp/vagrant.pub >> /root/.ssh/authorized_keys
chmod -R g-rwx,o-rwx /root/.ssh
mkdir -p /home/vagrant/.ssh
cat /tmp/vagrant.pub >> /home/vagrant/.ssh/authorized_keys
chown -R vagrant:vagrant /home/vagrant
chmod -R g-rwx,o-rwx /home/vagrant
rm /tmp/vagrant.pub
# Clean up
yum erase -y kernel-headers kernel-devel gcc
package-cleanup --leaves --all
yum clean all
# https://gist.github.com/adrienbrault/3775253
# Zero free space to aid VM compression
dd if=/dev/zero of=/EMPTY bs=1M
rm -f /EMPTY
# Remove bash history
unset HISTFILE
rm -f /root/.bash_history
rm -f /home/vagrant/.bash_history
# Cleanup log files
find /var/log -type f | while read f; do echo -ne '' > $f; done;
# Whiteout root
count=`df --sync -kP / | tail -n1 | awk -F ' ' '{print $4}'`;
let count--
dd if=/dev/zero of=/tmp/whitespace bs=1024 count=$count;
rm /tmp/whitespace;
# Whiteout /boot
count=`df --sync -kP /boot | tail -n1 | awk -F ' ' '{print $4}'`;
let count--
dd if=/dev/zero of=/boot/whitespace bs=1024 count=$count;
rm /boot/whitespace;
swappart=`cat /proc/swaps | tail -n1 | awk -F ' ' '{print $1}'`
swapoff $swappart;
dd if=/dev/zero of=$swappart;
mkswap $swappart;
swapon $swappart;
%end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment