Search code examples
vagrantvirtualboxvagrantfileubuntu-server

Setting up 1/4 of memory of virtualbox on vagrantfile


I'm new on vagrant and I'm trying to put my machine to 1/4 of system memory like this:

config.vm.define "UbuntuServer2" do |server2|
server2.vm.box = "ubuntu/trusty64"
server2.vm.provider :virtualbox do |vb|
  vb.customize ["modifyvm", :id, "--cpuexecutioncap", "50"]
  vb.customize ["modifyvm", :id, "--memory", 'echo -n $($(awk '/MemTotal/' {print $2} /proc/meminfo / 1024 / 4))']

 end
end

But i'm getting this error: Path: Line number: 38 Message: NameError: uninitialized constant MemTotal

How I can init this variable? I'm using MacOs 10.11.5 Thanks in advance.


Solution

  • Here's what I am using in such case if your host OS is mac

    config.vm.define "UbuntuServer2" do |server2|
      server2.vm.box = "ubuntu/trusty64"
      server2.vm.provider :virtualbox do |vb|
        vb.customize ["modifyvm", :id, "--cpuexecutioncap", "50"]
        mem = `sysctl -n hw.memsize`.to_i / 1024 / 1024 / 4
        vb.customize ["modifyvm", :id, "--memory", mem]
    
      end
    end
    

    I got a more complete script that can help anyone if needed

      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
            cpus = `wmic cpu get NumberOfCores`.split("\n")[2].to_i
            mem = `wmic OS get TotalVisibleMemorySize`.split("\n")[2].to_i / 1024 /4
          end
    
          v.customize ["modifyvm", :id, "--memory", mem]
          v.customize ["modifyvm", :id, "--cpus", cpus]
      end