Deploys a new VM with the ovftool on an ESXi Host
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

130 lines
2.8 KiB

#!/bin/sh
#####################################################################
#
# Deploys a new VM with the ovftool on an ESXi Host
#
# Syntax:
# ./deployNewVM.sh -t "20210327-deb10-arm64"
#
# Date: 2021-04-03
# Version: 0.3
#
# Changelog: 0.2 - Getting ip address outsourced
# 0.3 - Determines the next free possible VM name
#
#####################################################################
ovftoolBin="/scratch/downloads/ovftool/ovftool"
dataStore="DataStore1"
dataStorePath="/vmfs/volumes/$dataStore"
templatePath="/vmfs/volumes/$dataStore/Templates"
templateVMname="vm00"
maxVMs=10
while getopts t: flag
do
case "${flag}" in
t) template=${OPTARG};;
esac
done
#-----------------------
# Get next free VM name
aVMs=`vim-cmd vmsvc/getallvms | awk '{print $2}' | awk '(NR>1)'`
i=1
found=false
while [ "$i" -le $maxVMs ]
do
if ! echo "$aVMs" | grep -q "$i"; then
if [ $i -eq 10 ]; then
name="vm10"
else
name="vm0$i"
fi
found=true
break
fi
i=$(( i + 1 ))
done
if [ "$found" = false ]; then
echo "No free VM name found. Capacity reached!"
exit 1
fi
#echo "Template: $template";
#echo "Name for new VM: $name";
if ! [ -e $ofvtoolBin ]; then
echo "ovftool not found!"
exit 2
fi
if ! [ -d $templatePath/$template ]; then
echo "Template '$template' not found!"
exit 3
fi
#-----------------------
# This file is for ansible
if [ -e /tmp/newvm ]; then
rm -f /tmp/newvm
fi
#-----------------------
# Copy and modify template
cp -r $templatePath/$template $templatePath/$name
mv $templatePath/$name/vm00-0.vmdk $templatePath/$name/$name-0.vmdk
mv $templatePath/$name/vm00.nvram $templatePath/$name/$name.nvram
mv $templatePath/$name/vm00.ovf $templatePath/$name/$name.ovf
sed -i "s/$templateVMname/$name/g" $templatePath/$name/$name.ovf
#-----------------------
# Deploy VM
$ovftoolBin -ds=$dataStore $templatePath/$name/$name.ovf "vi://root:yourpassword@192.168.1.20"
#-----------------------
# Start VM, copy nvram again from template and stop VM
# https://kb.vmware.com/s/article/2061784
newVMid=`vim-cmd vmsvc/getallvms | grep $name | awk '{print $1}'`
vim-cmd vmsvc/power.on $newVMid
sleep 30
vim-cmd vmsvc/power.off $newVMid
rm -f $dataStorePath/$name/$name.nvram
cp $templatePath/$template/*.nvram $dataStorePath/$name/$name.nvram
#-----------------------
# Cleanup
rm -rf $templatePath/$name
#-----------------------
# Finally start the new VM
vim-cmd vmsvc/power.on $newVMid
#-----------------------
# Give VM (Tools) some time to collect data (e.g. the ip address informations are not directly accessable)
sleep 60
#-----------------------
# Exit and let Ansible do the rest
echo "$name" >> /tmp/newvm
exit 0