Skip to content

Instantly share code, notes, and snippets.

@aortbals
Created March 22, 2022 22:02
Show Gist options
  • Save aortbals/251b6e40fd9253846b1046b6a9bb4a66 to your computer and use it in GitHub Desktop.
Save aortbals/251b6e40fd9253846b1046b6a9bb4a66 to your computer and use it in GitHub Desktop.
Create a kvm image using libvirt and uvtool. Image is configured with bridge networking.
#! /usr/bin/env bash
### Create VM
#
# Create a kvm image using libvirt and uvtool. Image is configured with
# bridge networking.
#
## Functions
usage() {
echo "Usage: vm-create [-m <memory MB>] [-d <disk GB>] [-c <cpu>] [-r <release>] [-s] <name>"
exit 1
}
## Arguments
memory="2048"
disk="20"
cpu="1"
release="bionic"
sync="false"
while getopts :m:d:c:r:s opt; do
case $opt in
m)
memory=$OPTARG
;;
d)
disk=$OPTARG
;;
c)
cpu=$OPTARG
;;
r)
release=$OPTARG
;;
s)
sync="true"
;;
*)
usage
;;
esac
done
shift $((OPTIND - 1))
if (( $# != 1 ))
then
usage
fi
## Main
if [[ $sync = "true" ]]; then
echo "Syncing $release cloud images..."
uvt-simplestreams-libvirt sync release=$release arch=amd64
fi
echo -e "\n=== VM ==="
echo -e "name:\t$1"
echo -e "memory:\t$memory MB"
echo -e "disk:\t$disk GB"
echo -e "cpu:\t$cpu"
echo -e "\nCreating $1..."
uvt-kvm create --bridge br0 --memory $memory --disk $disk --cpu $cpu $1 release=$release
echo -e "Done."
echo -e "\nVirtual Machines:\n"
virsh -c qemu:///system list
echo -e "\nWaiting for vm to come online..."
sleep 15
echo -e "\nNetwork interface:\n"
interface=`virsh domiflist $1`
echo -e "$interface"
echo -e "\nRetrieving IP address..."
mac_address=`echo "$interface" | grep 'bridge' | awk '{print $5;}'`
ip=`sudo arp-scan --interface=br0 --localnet | grep $mac_address | awk '{print $1;}'`
echo -e "IP: $ip"
read -p "Add IP to hosts file? (Y/n) " add_ip_hosts
add_ip_hosts=${add_ip_hosts:-Y}
if [[ $add_ip_hosts = [Yy]* ]]; then
echo "$ip $1" | sudo tee -a /etc/hosts
echo 'Added to hosts file.'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment