動機

vm與container的使用情境不同,還是要懂 同時這個也比docker或是k8s好懂、好操作多

安裝

  1. windows裝virtualbox
  2. wsl2中裝vagrant
  3. 在bashrc中加
    • export VAGRANT_WSL_ENABLE_WINDOWS_ACCESS="1"
    • export PATH="$PATH:/mnt/c/Program Files/Oracle/VirtualBox"
  4. virtualbox_WSL2,不然ssh沒辦法用

使用時

sync file

只能在/mnt/c之類的是windows的地方使用sync file,不然要手動去取消掉 config.vm.synced_folder '.', '/vagrant', disabled: true

複製public key

不想打密碼

Vagrant.configure("2") do |config|
 config.vm.provision "shell" do |s|
  ssh_pub_key = File.readlines("#{Dir.home}/.ssh/id_rsa.pub").first.strip
  s.inline = <<-SHELL
   echo  #{ssh_pub_key} >> /home/vagrant/.ssh/authorized_keys
  SHELL
 end

 config.vm.network "private_network", ip: "192.168.50.4"
end

設定private network

主要是因為這個才用vagrant,不然想從host連到docker或是k8s的container會很痛苦

  1. container預設沒有ssh,要自己裝與設定
  2. 網路要自己喬,痛苦

config.vm.network "private_network", ip: "192.168.50.4"

把serial port關掉 (only in Ubuntu)

預設第一個serial port會打開 起初是跑ubuntu的box不知道為什麼就是起不來,發現是kernel想往serial port打log。 之後把serial port給disconnect就可以boot,但是很慢(>3mins)。 所以要把serial port整個關掉,這樣就正常了。

config.vm.provider "virtualbox" do |v|
    v.customize [ "modifyvm", :id, "--uart1", "off" ]
end

一次跑很多台

Vagrant.configure("2") do |config|
  config.vm.define "centos" do |instance|
    # ...
  end

  config.vm.define "ubuntu" do |instance|
    # ...
  end
end

總結

def wsl(instance, ip)
  instance.vm.provision "shell" do |s|
    ssh_pub_key = File.readlines("#{Dir.home}/.ssh/id_rsa.pub").first.strip
    s.inline = <<-SHELL
      echo #{ssh_pub_key} >> /home/vagrant/.ssh/authorized_keys
    SHELL
  end

  instance.vm.synced_folder '.', '/vagrant', disabled: true
  instance.vm.network "private_network", ip: ip
end

Vagrant.configure("2") do |config|
  config.vm.define "centos" do |instance|
    # ...
  end

  config.vm.define "ubuntu" do |instance|
    instance.vm.box = "hashicorp/bionic64"
    instance.vm.provider "virtualbox" do |v|
      v.memory = 2048
      v.cpus = 2
      v.customize [ "modifyvm", :id, "--uart1", "off" ]
    end
    
    wsl(instance, "192.168.50.5")
  end
end

vagrant in WSL的模板

把先設定模板位置 export VAGRANT_DEFAULT_TEMPLATE=~/.vagrant.d/Vagrantfile.erb

之後打wsl的模板,放在VAGRANT_DEFAULT_TEMPLATE的位置

Vagrant.configure("2") do |config|
  config.vm.define "default" do |instance|
    instance.vm.box = "<%= box_name %>"
    <% if box_version -%>
    instance.vm.box_version = "<%= box_version %>"
    <% end -%>
    <% if box_url -%>
    instance.vm.box_url = "<%= box_url %>"
    <% end -%>
    instance.vm.provider "virtualbox" do |v|
      v.memory = 2048
      v.cpus = 2
      v.customize [ "modifyvm", :id, "--uart1", "off" ]
    end
    
    wsl(instance, YOUR_IP)
  end
end

之後就是 vagrant init ubuntu/focal64!!

Ref

Vagrant and Windows Subsystem for Linux multiple-vagrant-vms-in-one-vagrantfile virtualbox_WSL2 vagrant default configuration