我希望我的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)。
任何人都知道如何做到这一点?
答案 0 :(得分:4)
我设法将其计算为Git repo。
代码:
cpus = `wmic cpu get NumberOfCores`.split("\n")[2].to_i
mem = `wmic OS get TotalVisibleMemorySize`.split("\n")[2].to_i / 1024 /4
答案 1 :(得分:2)
要将上述答案统一到一个完整的示例中,您的流浪文件应包含此配置部分:
请注意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
答案 2 :(得分:1)
您下载的脚本就在那里:
抱歉Windows人员,我帮不了你
else # sorry Windows folks, I can't help you
cpus = 2
mem = 1024
end
因此您可以更改这些默认值,但遗憾的是,Windows不提供易于使用的命令来检索这些信息
现在,如果您想自己动手,那么应该可以,查看wmic
命令,您可以获得很多,而且只需很少的解析就可以获得必要的信息 - 例如
C:\Users\fhenri>wmic os get freephysicalmemory
FreePhysicalMemory
1564244
C:\Users\fhenri>wmic.exe cpu get NumberOfCores
NumberOfCores
1
您还可以查看systeminfo
这是非常详细且特定于语言环境,因此可能更难解析