, ,

Automation | Add vCPU in VM if usage is more than 90%

Hi Guys,

I got this question from one of the VMware group so I thought to add it in my blog and then share. Automation of CPU addition is not tough but adding it with condition can be little challenging. You can do it with vROPS very easily but if you don't have vROPS then I have solution for you.

Pre-requisite is to enable hot add for CPU.

Below is the base code- 

Connect-VIServer vcenter_ip #to connect vcenter
$VM = Get-VM VM_Name #to get the vm name
#to convert the value in GHz. Default value comes in MHz
$maxcpu = ($vm.Extensiondata.Summary.Runtime.MaxCpuUsage)/1024
#to convert number of cpu into GHz speed. Here you need to replace 2.80 as per physical host's core speed at your end
$cpus = ($vm.Extensiondata.summary.config.NumCPU)*2.80
# to have percentage value
$cpulimit = $cpus*90/100
#below is the hot add cpu command
if ($maxcpu -gt $cpulimit){
get-vm $vm | Set-VM -NumCpu 2 -Confirm:$false #Current value is 1 and it will change it to 2
}

Now the question is how to automate it,

you can create a loop so that it can run infinite. I have created below function

Connect-VIServer vcenter_ip
Function AutoAddCPU{
$VM = Get-VM VM_Name
#to convert the value in GHz
$maxcpu = ($vm.Extensiondata.Summary.Runtime.MaxCpuUsage)/1024
#to convert number of cpu into GHz speed
$cpus = ($vm.Extensiondata.summary.config.NumCPU)*2.80
$cpulimit = $cpus*90/100

if ($maxcpu -gt $cpulimit){
get-vm $vm | Set-VM -NumCpu 2 -Confirm:$false
}
AutoAddCPU
}
AutoAddCPU #this is not a mistake. Use it as it is.

Now the problem is, how will it monitor that particular VM continuously.

Simple solution, use task scheduler from where you can access vcenter server. Add above script in task scheduler and then run it once, it will run forever.

Another problem is, what if that server or jump server restart then it will break the script. Solution is to create task scheduler to run this script at every system startup.

There must be many questions here. For example, you might need to monitor many VMs at the same time, you want to monitor the cpu usage if goes above than 95% and more....

This is the base solution I have provided and can be customized or enhance as per individual need.

If you have such requirement too then feel free to write me back. Will be glad to assist. 

If  anyone wants the same thing from vrops then let me know, I will create one post on that as well. Using vrops is more authentic and efficient way to do it.



1 comment:

  1. I will modify above script to detect the current number of CPUs and the add 1 in the counting. That sounds more logical and workable.
    Stay tuned!

    ReplyDelete