我想让我的vagrantfile根据主机规格自动设置CPU和RAM。
我找到了这个片段:
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
但是它不支持Windows(它设置默认值2和1024)。
有人知道怎么做吗?
我设法把它弄明白了,并把它集成到一个Git仓库中。
代码:
cpus = `wmic cpu get NumberOfCores`.split("n")[2].to_i
mem = `wmic OS get TotalVisibleMemorySize`.split("n")[2].to_i / 1024 /4
要将上述答案统一为一个完整的示例,您的流浪汉文件应该包含以下配置部分:
注意mem_ratio
和cpu_exec_cap
变量,您可以使用它们来调整分配给VM的主机RAM和CPU周期的数量。
config.vm.provider "virtualbox" do |v|
mem_ratio = 3/4
cpu_exec_cap = 75
host = RbConfig::CONFIG['host_os']
# Give VM 3/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^2 * mem_ratio
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 * mem_ratio
else # Windows folks
cpus = `wmic cpu get NumberOfCores`.split("n")[2].to_i
mem = `wmic OS get TotalVisibleMemorySize`.split("n")[2].to_i / 1024 * mem_ratio
end
puts "Provisioning VM with #{cpus} CPU's (at #{cpu_exec_cap}%) and #{mem/1024} GB RAM."
v.customize ["modifyvm", :id, "--memory", mem]
v.customize ["modifyvm", :id, "--cpus", cpus]
v.customize ["modifyvm", :id, "--cpuexecutioncap", cpu_exec_cap]
end
它在您下载的脚本中:
对不起,Windows的朋友们,我不能帮助你
else # sorry Windows folks, I can't help you
cpus = 2
mem = 1024
end
所以你可以改变这些默认值但不幸的是Windows没有提供简单易用的命令来检索这些信息
现在如果你想自己做,这应该是可能的,看看wmic
命令,你可以得到很多,并且通过很少的解析你应该有必要的信息-例如
C:Usersfhenri>wmic os get freephysicalmemory
FreePhysicalMemory
1564244
C:Usersfhenri>wmic.exe cpu get NumberOfCores
NumberOfCores
1
你也可以看看systeminfo
这是相当冗长的和特定于地区的所以可能更难解析