Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vagrant - how to detect windows host RAM and CPU

I'd like my vagrantfile to automatically set CPU and RAM based on the host specs.

I found this snippet:

 config.vm.provider "virtualbox" do |v|
      host = RbConfig::CONFIG['host_os']
      # Give VM 1/4 system memory & access to all cpu cores on the host
      if host =~ /darwin/
        cpus = `sysctl -n hw.ncpu`.to_i
        # sysctl returns Bytes and we need to convert to MB
        mem = `sysctl -n hw.memsize`.to_i / 1024 / 1024 / 4
      elsif host =~ /linux/
        cpus = `nproc`.to_i
        # meminfo shows KB and we need to convert to MB
        mem = `grep 'MemTotal' /proc/meminfo | sed -e 's/MemTotal://' -e 's/ kB//'`.to_i / 1024 / 4
      else # sorry Windows folks, I can't help you
        cpus = 2
        mem = 1024
      end

      v.customize ["modifyvm", :id, "--memory", mem]
      v.customize ["modifyvm", :id, "--cpus", cpus]
end

It however doesn't do Windows (it sets default values 2 and 1024 instead).

Anyone got any clue how to do this?

like image 591
Mentor Avatar asked Dec 24 '22 13:12

Mentor


1 Answers

I managed to figure it our and integrated it into a Git repo.

The code:

cpus = `wmic cpu get NumberOfCores`.split("\n")[2].to_i
mem = `wmic OS get TotalVisibleMemorySize`.split("\n")[2].to_i / 1024 /4
like image 165
Mentor Avatar answered Jan 25 '23 03:01

Mentor