1つのVagrantfileで複数台の仮想マシンを作り、仮想的なネットワークを構築する方法

Vagrantは、1つのVagrantfileで複数台の仮想マシンを作成する事が可能です。これにより、自分のPC上に仮想的なネットワークを構築し、そのネットワーク内にWeb・API・DBサーバなどを起動し、サーバやネットワークの学習やテストする環境が作れます。ここでは、その方法について説明していきます。

※ 本ページはプロモーションが含まれています。

目的と環境

最終更新日:2021/4/20

Vagrantでは、1つのVagrantfileファイルで複数台の仮想マシンを作成し、コントロールする事が可能です。
これによって、自分のPC上に仮想的なネットワークを構築し、そのネットワーク内にWebサーバ、APIサーバ、DBサーバなどを想定して作ることができますので、サーバやネットワークを勉強したりテストする環境が作れます。

ここでは、1つのVagrantfileファイルから複数台の仮想マシンを作成し、起動するまでのやり方について説明していきます。

◾️動作環境とバージョン情報です。
OS:macOS Big Sur(バージョン11.1)
Vagrant 2.2.7
VirtualBox 6.1.16

$ vagrant -v
Vagrant 2.2.7

$ VirtualBox -h
Oracle VM VirtualBox VM Selector v6.1.16

これ以降は、VagrantとVirtualBoxをインストールしてある事が前提で説明していきます。

同じネットワーク内に2台の仮想マシンを作成してみる

まずは仮想マシンを作るために、vagrant initコマンドで適当なBoxを用意します。ここでは、"hashicorp/bionic64"というBoxを使っていきます。

$ vagrant init hashicorp/bionic64
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

ここではhashicorp/bionic64を使いますが、皆さんの環境に他のBoxがあれば、そのBoxを使って問題ないと思います。
ちなみにhashicorp/bionic64は、Ubuntu 18.04.3 LTSのBoxです。

Vagrantfileファイルが作成されたら編集します(見やすくするために、コメント文はすべて削除しています)。

$ cat Vagrantfile 
Vagrant.configure("2") do |config|

  config.vm.define "host1" do |host1|
    host1.vm.box = "hashicorp/bionic64"
    host1.vm.network :private_network, ip: "192.168.33.10"
  end

  config.vm.define "host2" do |host2|
    host2.vm.box = "hashicorp/bionic64"
    host2.vm.network :private_network, ip: "192.168.33.11"
  end

end
このVagrantfileでは、config.vm.defineメソッドを使って2台の仮想マシン(host1とhost2)を作成するようにしています。
それぞれの仮想マシンで、BoxとプライベートIPを指定しています。

config.vm.defineメソッドをさらに追加して、2台ではなくもっと多くの仮想マシンを作ることができますが、あまり作りすぎるとメモリ不足でPC全体の動作が遅く(重く)なるかもしれないので、皆さんのPCスペック環境に合わせて試してみてください。

ここでvagrant statusを実行すると、2台分の状態が表示されます。

$ vagrant status
Current machine states:

host1                     not created (virtualbox)
host2                     not created (virtualbox)

This environment represents multiple VMs. The VMs are all listed
above with their current state. For more information about a specific
VM, run `vagrant status NAME`.

準備ができたので、起動します。

$ vagrant up
Bringing machine 'host1' up with 'virtualbox' provider...
Bringing machine 'host2' up with 'virtualbox' provider...
==> host1: Box 'hashicorp/bionic64' could not be found. Attempting to find and install...
    host1: Box Provider: virtualbox
    host1: Box Version: >= 0
==> host1: Loading metadata for box 'hashicorp/bionic64'
    host1: URL: https://vagrantcloud.com/hashicorp/bionic64
==> host1: Adding box 'hashicorp/bionic64' (v1.0.282) for provider: virtualbox
    host1: Downloading: https://vagrantcloud.com/hashicorp/boxes/bionic64/versions/1.0.282/providers/virtualbox.box
    host1: Download redirected to host: vagrantcloud-files-production.s3.amazonaws.com
==> host1: Successfully added box 'hashicorp/bionic64' (v1.0.282) for 'virtualbox'!
==> host1: Importing base box 'hashicorp/bionic64'...
==> host1: Matching MAC address for NAT networking...
==> host1: Checking if box 'hashicorp/bionic64' version '1.0.282' is up to date...
==> host1: Setting the name of the VM: tmp_host1_1610817024479_40318
==> host1: Fixed port collision for 22 => 2222. Now on port 2201.
==> host1: Clearing any previously set network interfaces...
==> host1: Preparing network interfaces based on configuration...
    host1: Adapter 1: nat
    host1: Adapter 2: hostonly
==> host1: Forwarding ports...
    host1: 22 (guest) => 2201 (host) (adapter 1)
==> host1: Booting VM...
==> host1: Waiting for machine to boot. This may take a few minutes...
    host1: SSH address: 127.0.0.1:2201
    host1: SSH username: vagrant
    host1: SSH auth method: private key
    host1: 
    host1: Vagrant insecure key detected. Vagrant will automatically replace
    host1: this with a newly generated keypair for better security.
    host1: 
    host1: Inserting generated public key within guest...
    host1: Removing insecure key from the guest if it's present...
    host1: Key inserted! Disconnecting and reconnecting using new SSH key...
==> host1: Machine booted and ready!
==> host1: Checking for guest additions in VM...
    host1: The guest additions on this VM do not match the installed version of
    host1: VirtualBox! In most cases this is fine, but in rare cases it can
    host1: prevent things such as shared folders from working properly. If you see
    host1: shared folder errors, please make sure the guest additions within the
    host1: virtual machine match the version of VirtualBox you have installed on
    host1: your host and reload your VM.
    host1: 
    host1: Guest Additions Version: 6.0.10
    host1: VirtualBox Version: 6.1
==> host1: Configuring and enabling network interfaces...
==> host1: Mounting shared folders...
    host1: /vagrant => /Users/hogeuser/MyVagrant/tmp
==> host2: Box 'hashicorp/bionic64' could not be found. Attempting to find and install...
    host2: Box Provider: virtualbox
〜
    host2: VirtualBox Version: 6.1
==> host2: Configuring and enabling network interfaces...
==> host2: Mounting shared folders...
    host2: /vagrant => /Users/hogeuser/MyVagrant/tmp

$ vagrant status
Current machine states:

host1                     running (virtualbox)
host2                     running (virtualbox)
〜
仮想マシン2台を作成して起動する事ができました!
最初の方のメッセージにDownloadingとありますが、私のVagrant環境にはBoxの"hashicorp/bionic64"がなかったので、最初に"hashicorp/bionic64"をダウンロードしてから仮想マシンを作成しています。ですので、少し時間がかかりました。
ここでBox一覧を確認したら、hashicorp/bionic64が追加されているはずです。
$ vagrant box list
bento/centos-6.7                  (virtualbox, 2.2.3)
bento/centos-6.8                  (virtualbox, 2.3.4)
centos-7.1                        (virtualbox, 0)
debian-7.4_c64                    (virtualbox, 0)
hashicorp/bionic64                (virtualbox, 1.0.282)
precise32                         (virtualbox, 0)

仮想マシンを起動できたので、今度は接続確認をします。
仮想マシンが複数台ある場合、vagrant sshのあとに仮想マシンの名前を指定する必要があります。

$ vagrant ssh host1
Welcome to Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-58-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sat Jan 16 17:19:52 UTC 2021

  System load:  0.0               Processes:           88
  Usage of /:   2.5% of 61.80GB   Users logged in:     0
  Memory usage: 11%               IP address for eth0: 10.0.2.15
  Swap usage:   0%                IP address for eth1: 192.168.33.10

 * Introducing self-healing high availability clusters in MicroK8s.
   Simple, hardened, Kubernetes for production, from RaspberryPi to DC.

     https://microk8s.io/high-availability

0 packages can be updated.
0 updates are security updates.


vagrant@vagrant:~$ 
接続もできました。
プライベートIPアドレスも確認してみます。
vagrant@vagrant:~$ ip a
〜
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:43:d5:a8:66 brd ff:ff:ff:ff:ff:ff
    inet 192.168.33.10/24 brd 192.168.33.255 scope global eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fee7:a977/64 scope link 
       valid_lft forever preferred_lft forever
Vagrantfileで指定したIPアドレス(192.168.33.10)になっています。

今度はもう1台の仮想マシン(192.168.33.11)にpingを送って、疎通確認をします。

$ ping 192.168.33.11
PING 192.168.33.11 (192.168.33.11): 56 data bytes
64 bytes from 192.168.33.11: icmp_seq=0 ttl=64 time=0.610 ms
64 bytes from 192.168.33.11: icmp_seq=1 ttl=64 time=0.502 ms
〜
ちゃんとpingも送れました。
これで、同じネットワーク内に2台の仮想マシンを作ることができました!

ホスト側(自分のPC)からゲスト側(仮想マシン、host1とhost2)へも通信できるので、ホスト側から192.168.33.11へpingを送ることもできます。

接続(vagrant ssh)だけでなく、1台ずつ起動(vagrant up)やシャットダウン(vagrant halt)を操作したい場合も、コマンドのあとに仮想マシン名を指定すればできます。

#状態確認。最初は2台共起動中
$ vagrant status
Current machine states:

host1                     running (virtualbox)
host2                     running (virtualbox)
〜

$ #host1だけをシャットダウンする
$ vagrant halt host1
==> host1: Attempting graceful shutdown of VM...

$ #状態確認
$ vagrant status
Current machine states:

host1                     poweroff (virtualbox)
host2                     running (virtualbox)

$ #今度はhost1だけを起動する
$ vagrant up host1
Bringing machine 'host1' up with 'virtualbox' provider...
==> host1: Checking if box 'hashicorp/bionic64' version '1.0.282' is up to date...
〜
==> host1: flag to force provisioning. Provisioners marked to run always will still run.

$ #状態確認
$ vagrant status
Current machine states:

host1                     running (virtualbox)
host2                     running (virtualbox)

最後に

以上簡単ですが、1つのVagrantfileで仮想マシンを複数台の作り方について説明してきました。

最初にも話しましたが、これによって、自分のPC上に仮想的なネットワークを構築し、そこに複数のWebサーバ、APIサーバ、DBサーバなどの仮想マシンを作ることができます。 ですので、サーバだけでなくネットワークなどのインフラの学習環境やテスト環境が簡単にできます。

AWSなどの便利なクラウドサービスもありますが、個人で有料のクラウドサービス上に仮想マシンを何個も起動するのはそれなりにお金もかかりますから、Vagrantをうまく活用するのも良いかと思います。