- [orca@orcacomputers raid5]$ cat /usr/local/bin/mkvm.pl
- #!/bin/perl
- # This script simplifies the process of creating a KVM virtual machine by creating interactive prompts.
- use strict;
- use warnings;
- use v5.10;
- # Declare some constants (can be configured).
- my $VM_ROOT = "/mnt/raid5/VM";
- my $ISO_ROOT = "$VM_ROOT/ISO";
- my $DISK_ROOT = "$VM_ROOT/Disks";
- # Subroutine to create a menu prompt from a list of strings.
- sub menu {
- my @items = @_;
- my $count = 0;
- foreach my $item( @items ) {
- printf "%d: %sn", ++$count, $item =~ s/.*///gr;
- }
- print "n#: ";
- while( my $line = <STDIN> ) {
- chomp $line;
- if ( $line =~ m/d+/ && $line <= @items && $line > 0 ) {
- if ($line == @items + 1) {
- exit;
- }
- return $items[$line - 1];
- }
- print "#: ";
- }
- }
- # Subroutine to prompt for a value with a given prompt, default value, minimum, and maximum value.
- sub prompt {
- my $prompt = $_[0];
- my $default = $_[1];
- my $min = $_[2];
- my $max = $_[3];
- print "n$prompt, $min-$max ($default): ";
- while (my $input = <STDIN>) {
- chomp $input;
- if ($input eq "") {
- return $default;
- } elsif ($input =~ m/d+/ && $input >= $min && $input <= $max) {
- return $input;
- }
- print "$prompt, $min-$max ($default): ";
- }
- }
- # Select which disk image to use.
- print "Select ISO:nn";
- my $ISO = menu(glob("$ISO_ROOT/*"));
- # Configure the size of the disk.
- my $disk = prompt("Disk size (GB)", 50, 5, 1000);
- # Configure the amount of RAM to give to the VM.
- my $RAM = prompt("RAM (GB)", 1, 0.5, 10);
- $RAM *= $RAM * 1024;
- # Configure the amount of virtual CPU cores the VM will have access to.
- my $CPU = prompt("CPU cores", 2, 1, 8);
- # Prompt for the ID of the machine.
- print "nID: ";
- my $ID;
- while ($ID = <STDIN>) {
- $ID =~ s/[^w-]//g;
- if ($ID ne "") {
- last;
- }
- print "ID: ";
- }
- if (grep(/^.*/$ID.qcow2$/, glob("$DISK_ROOT/*"))) {
- print "nFailed: VM with ID `$ID` already exists.n";
- exit;
- }
- # Prompt for the name of the OS.
- # print "nOS: ";
- # my $OS = <STDIN>;
- # chomp $OS;
- my $OS = "centos7.0";
- print "nnConfirm:nnISO: $ISOnDisk size: $disk GBnRAM: $RAM MBnCPU cores: $CPUnID: $IDnOS: $OSnn(y,n): ";
- while (my $confirm = <STDIN>) {
- chomp $confirm;
- if ($confirm eq "y" || $confirm eq "Y") {
- last;
- } elsif ($confirm eq "n" || $confirm eq "N") {
- exit;
- }
- print "(y,n): ";
- }
- print "n";
- system "sudo virt-install --virt-type=kvm --name $ID --ram $RAM --vcpus $CPU --os-variant "$OS" --cdrom "$ISO" --network=bridge=virbr0,model=virtio --graphics vnc --disk path="$DISK_ROOT/$ID.qcow2",size=$disk,bus=virtio,format=qcow2 &";
- system "sleep 5s; sudo virsh dumpxml $ID | grep vnc";