Vagrant简介

本文环境基于macOS

Virtualbox

1
2
brew cask install virtualbox
# brew cask reinstall virtualbox

Vagrant

1
2
3
4
5
brew cask install vagrant
# brew cask reinstall vagrant

vagrant -v
# 2.2.5

Box

1
2
3
4
vagrant box add ubuntu/xenial64

vagrant box list
# ubuntu/xenial64 (virtualbox, 20191024.0.0)

Vagrantfile

1
2
3
4
5
mkdir playbook && cd playbook

vagrant init ubuntu/xenial64

vim Vagrantfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"
config.vm.host_name = "node1"
config.vm.network "private_network", ip: "192.168.56.100"
config.vm.provider "virtualbox" do |vb|
vb.name = "node1"
vb.memory = "3000"
vb.cpus = "2"
end
config.vm.provision "file", source: "~/.ssh/id_rsa.pub", destination: "~/.ssh/id_rsa.pub"
config.vm.provision "shell", inline: <<-SHELL
cat /home/vagrant/.ssh/id_rsa.pub >> /home/vagrant/.ssh/authorized_keys
SHELL
end
1
2
3
4
5
6
vagrant up

vagrant ssh
# ssh vagrant@192.168.56.100

vagrant destroy

Cluster

1
vim Vagrantfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
(1..2).each do |i|
config.vm.define "node#{i}" do |node|
node.vm.box = "ubuntu/xenial64"
node.vm.host_name = "node#{i}"
node.vm.network "private_network", ip: "192.168.56.#{100+i}"

node.vm.provider "virtualbox" do |vb|
vb.name = "node#{i}"
vb.memory = "1500"
vb.cpus = "1"
end

node.vm.provision "file", source: "~/.ssh/id_rsa.pub", destination: "~/.ssh/id_rsa.pub"
node.vm.provision "shell", inline: <<-SHELL
cat /home/vagrant/.ssh/id_rsa.pub >> /home/vagrant/.ssh/authorized_keys
SHELL
end
end
end
1
2
3
4
5
6
7
8
9
vagrant up

vagrant ssh node1
# ssh vagrant@192.168.56.101

vagrant ssh node2
# ssh vagrant@192.168.56.102

vagrant destroy

参考