Skip to content

Instantly share code, notes, and snippets.

@betamax
Created January 13, 2017 10:10
Show Gist options
  • Save betamax/d18d0a83a29037da790922fbb62d93bd to your computer and use it in GitHub Desktop.
Save betamax/d18d0a83a29037da790922fbb62d93bd to your computer and use it in GitHub Desktop.
#!/bin/bash
# Create a VirtualBox VM from an Ubuntu Cloud Image
# Thanks to https://gist.github.com/smoser/6066204
name=$1
# URL to most recent cloud image of 14.04
# If you want a different version just find the URL from https://cloud-images.ubuntu.com/
img_url="https://cloud-images.ubuntu.com/trusty/current"
img_url="${img_url}/trusty-server-cloudimg-amd64-disk1.img"
img_dist="${img_url##*/}"
img_raw="${img_dist%.img}.raw"
disk="$name.vdi"
# Download the img
wget $img_url -O "$img_dist"
# Convert it to raw
qemu-img convert -O raw "${img_dist}" "${img_raw}"
# Create VirtualBox 'vdi' from raw
VBoxManage convertfromraw "$img_raw" "$disk"
rm "${img_raw}"
seed_iso="seed.iso"
# Create meta-data file
cat > meta-data <<EOF
local-hostname: localhost
EOF
# Create user-data file
cat > user-data <<EOF
#cloud-config
password: ubuntu
chpasswd: { expire: False }
ssh_pwauth: True
EOF
# Create seed.img to use the above to files to config the new instance on boot
gtruncate --size 100K seed.img
mkisofs -output seed.img -volid cidata -joliet -rock user-data meta-data
qemu-img convert -f raw -O raw seed.img "$seed_iso"
rm user-data meta-data seed.img
# Create the virtual machine
VBoxManage createvm --name "$name" --register
# Set RAM to 2048 MB
VBoxManage modifyvm "$name" --memory 2048
# Set the (dynamic) disk size to 30 GB
VBoxManage modifyhd "$disk" --resize 30720
# Set up NAT and port forwarding for SSH
VBoxManage modifyvm "$name" --nic1 nat --natpf1 "ssh,tcp,,2222,,22"
# Attach HD with disk image
VBoxManage storagectl "$name" --name SATA --add sata
VBoxManage storageattach "$name" --storagectl SATA --device 0 --port 0 --type hdd --medium "$disk"
# Attach ISO with seed.iso
VBoxManage storagectl "$name" --name IDE --add ide
VBoxManage storageattach "$name" --storagectl IDE --port 0 --device 0 --type dvddrive --medium "$seed_iso"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment